opensips-js 0.1.19 → 0.1.20
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/README.md +17 -2
- package/dist/index.d.ts +2 -0
- package/dist/opensips-js.cjs.js +1 -1
- package/dist/opensips-js.es.js +17 -9
- package/dist/opensips-js.iife.js +1 -1
- package/dist/opensips-js.umd.js +1 -1
- package/package.json +1 -1
package/dist/opensips-js.iife.js
CHANGED
|
@@ -155,5 +155,5 @@ a=accept-types:text/plain text/html
|
|
|
155
155
|
a=path:${t.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 Wr(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:s=>{this.onTransportError(),console.log(s)},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s),s.status_code===200&&(s.parseSDP(!0),this._status=Ce.STATUS_CONFIRMED,this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Ce.STATUS_INVITE_SENT}terminate(t={}){const n=t.cause||H.causes.BYE,a=Pe.cloneArray(t.extraHeaders),o=t.body;let s,r=t.status_code,d=t.reason_phrase;if(this._status===Ce.STATUS_TERMINATED)throw new Ns.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:if(r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(d=d||H.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${d}"`),this._status===Ce.STATUS_NULL||this._status===Ce.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===Ce.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=Ce.STATUS_CANCELED,this._failed("local",null,H.causes.CANCELED);break;case Ce.STATUS_WAITING_FOR_ANSWER:case Ce.STATUS_ANSWERED:if(r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,d,a,o),this._failed("local",null,H.causes.REJECTED);break;case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:if(d=t.reason_phrase||H.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&a.push(`Reason: SIP ;cause=${r}; text="${d}"`),this._status===Ce.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ht.C.STATUS_TERMINATED){const h=this._dialog;this.receiveRequest=({method:_})=>{_===H.ACK&&(this.sendRequest(H.BYE,{extraHeaders:a,body:o}),h.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ht.C.STATUS_TERMINATED&&(this.sendRequest(H.BYE,{extraHeaders:a,body:o}),h.terminate())}),this._ended("local",null,n),this._dialog=h,this._ua.newDialog(h)}else this.sendRequest(H.BYE,{extraHeaders:a,body:o}),this._ended("local",null,n)}}sendRequest(t,n){return this._dialog.sendRequest(t,n)}authenticate(t){this.status="auth";let n=new Vn("");n.method="AUTH",n.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),n.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),t&&n.addHeader("Authorization",t.toString());let a=n.toString(),o=[];for(var s=0;s<a.length;s++)o.push(a.charCodeAt(s).toString(16));this._connection.send(n.toString())}onmessage(t){const n=new Vn(t.data);if(this.status==="auth"&&n.code===401){const a=this.parseAuth(n.getHeader("WWW-Authenticate")),o=new Om(this.credentials);o.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},a,Pe.createRandomToken(12)),this.authenticate(o)}this.status==="auth"&&n.code===200&&this._direction==="outgoing"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.inviteParty(n)):this.status==="auth"&&n.code===200&&this._direction==="incoming"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.acceptParty(n),this.emit("confirmed")):n.method==="SEND"&&(this._sendOk(n),this._sendReport(n),n.direction="incoming",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)),n.code===480&&this._close()}onclose(){console.log("close")}onopen(){const t=new RTCPeerConnection({iceServers:[]});t.createDataChannel(""),t.createOffer().then(t.setLocalDescription.bind(t)),t.onicecandidate=n=>{if(!n||!n.candidate||!n.candidate.candidate)return;const a=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,o=n.candidate.candidate.match(a);this.my_ip=o&&o[1],t.onicecandidate=()=>{},this.authenticate(null)}}onerror(t){console.log(t)}_receiveInviteResponse(t){if(console.log("resp0000000000000",t),this._dialog&&t.status_code>=200&&t.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest(H.ACK);return}else{const n=new ua(this,t,"UAC");if(n.error!==void 0){console.log(n.error);return}this.sendRequest(H.ACK),this.sendRequest(H.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==Ce.STATUS_INVITE_SENT&&this._status!==Ce.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(t.status_code):this._status=Ce.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){console.log("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=Ce.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",t)).catch(o=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(console.log("maybe here???"),this._status=Ce.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,H.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",t,H.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n),new RTCSessionDescription({type:"answer",sdp:n.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(t,500,a.toString()),console.log("failed 4"),this._failed("local",t,H.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(H.ACK),this._confirmed("local",null)});break}default:{const n=Pe.sipErrorCause(t.status_code);console.log("failed 5"),this._failed("remote",t,n)}}}sendMSRP(t){const n=new Vn("");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]),n.method="SEND",n.addHeader("To-Path",a),n.addHeader("From-Path",`${this.my_addr[0]}`),n.addHeader("Message-ID",Pe.createRandomToken(10)),n.addHeader("Byte-Range","1-25/25"),n.addHeader("Content-Type","text/plain"),n.addHeader("Success-Report","yes"),n.addHeader("Failure-Report","yes"),n.body=t;let o=n.toString();console.log(o);let s=[];for(var r=0;r<o.length;r++)s.push(o.charCodeAt(r).toString(16));console.log(s),this._connection.send(n.toString()),n.direction="outgoing",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(t){let n=t.ident,a=t.getHeader("Message-ID"),o=new Vn("");o.method="200 OK",o.addHeader("To-Path",`${this.my_addr[1]}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",a),o.ident=n;let s=o.toString();console.log(s);let r=[];for(var d=0;d<s.length;d++)r.push(s.charCodeAt(d).toString(16));console.log(r),this._connection.send(o.toString())}_sendReport(t){let n=t.ident,a=t.getHeader("Message-ID"),o=new Vn("");o.method="REPORT",o.addHeader("To-Path",`${t.getHeader("From-Path")}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",a),o.addHeader("Byte-Range","1-25/25"),o.addHeader("Status","000 200 OK"),o.ident=n;let s=o.toString();console.log(s);let r=[];for(var d=0;d<s.length;d++)r.push(s.charCodeAt(d).toString(16));console.log(r),this._connection.send(o.toString())}parseAuth(t){const n={},a=t.replace("Digest","").split(",");for(const o of a){const s=o.trim().split("=");n[s[0]]=s[1].match('^"(.+)"$')[1]}return n}init_incoming(t,n){let a;const o=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&o!=="application/sdp"){t.reply(415);return}if(this._status=Ce.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(a=t.getHeader("expires")*1e3),t.to_tag=Pe.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ce.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),console.log("failed 6"),this._failed("local",null,H.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),console.log("failed 7"),this._failed("system",null,H.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,n&&n(this),t.parseSDP(!0),this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",t),this._status!==Ce.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(t,n,a){this.emit("_failed",{originator:t,message:n||null,cause:a}),this._close(),this.emit("failed",{originator:t,message:n||null,cause:a})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ce.STATUS_TERMINATED){if(this._status=Ce.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){console.log("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyMSRPSession(this)}}_createDialog(t,n,a){const o=n==="UAS"?t.to_tag:t.from_tag,s=n==="UAS"?t.from_tag:t.to_tag,r=t.call_id+o+s;let d=this._earlyDialogs[r];if(a)return d?!0:(d=new ua(this,t,n,ua.C.STATUS_EARLY),d.error?(console.log("failed 8"),this._failed("remote",t,H.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=d,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,d)return d.update(t,n),this._dialog=d,delete this._earlyDialogs[r],!0;const h=new ua(this,t,n);return h.error?(console.log("failed 9"),this._failed("remote",t,H.causes.INTERNAL_ERROR),!1):(this._dialog=h,!0)}}_newMSRPSession(t,n){this._ua.newMSRPSession(this,{originator:t,session:this,request:n})}_progress(t,n){this.emit("progress",{originator:t,response:n||null})}isEnded(){switch(this._status){case Ce.STATUS_CANCELED:case Ce.STATUS_TERMINATED:return!0;default:return!1}}_accepted(t,n){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:t,response:n||null})}_confirmed(t,n){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:n||null})}_ended(t,n,a){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:t,message:n||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 t=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(n){console.error("Failed to send keep-alive:",n)}this._sessionTimers.running=!1,this._runKeepAliveTimer()},t*1e3*.5)}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let n;t.session_expires&&t.session_expires>=H.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,n=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runKeepAliveTimer()}receiveRequest(t){if(console.log("receiveRequest()"),t.method===H.CANCEL)(this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED)&&(this._status=Ce.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",t,H.causes.CANCELED));else switch(t.method){case H.ACK:if(this._status!==Ce.STATUS_WAITING_FOR_ACK)return;if(this._status=Ce.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:H.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(o=>{this.terminate({cause:H.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)})}else this._is_confirmed||this._confirmed("remote",t);break;case H.BYE:this._status===Ce.STATUS_CONFIRMED||this._status===Ce.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,H.causes.BYE)):this._status===Ce.STATUS_INVITE_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,H.causes.BYE)):t.reply(403,"Wrong Status");break;case H.INVITE:this._status===Ce.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case H.INFO:this._status===Ce.STATUS_1XX_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED||this._status===Ce.STATUS_WAITING_FOR_ACK||this._status===Ce.STATUS_CONFIRMED?(t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new nu(this).init_incoming(t):t.reply(415):t.reply(403,"Wrong Status");break;case H.UPDATE:this._status===Ce.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case H.REFER:this._status===Ce.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case H.NOTIFY:this._status===Ce.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:H.causes.CONNECTION_ERROR,cause:H.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:H.causes.REQUEST_TIMEOUT,cause:H.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:H.causes.DIALOG_ERROR,cause:H.causes.DIALOG_ERROR})}}var TT=Yt();const yu=Me(TT),Ea=new na("Parser"),vT=(c,t)=>{let n,a,o=c.indexOf(`\r
|
|
157
157
|
`);if(o===-1){Ea.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=c.substring(0,o);let r=yu.parse(s,"Request_Response");if(r===-1){Ea.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else r.status_code?(n=new Ln.IncomingResponse,n.status_code=r.status_code,n.reason_phrase=r.reason_phrase):(n=new Ln.IncomingRequest(t),n.method=r.method,n.ruri=r.uri);n.data=c;let d=o+2;for(;;){if(o=ST(c,d),o===-2){a=d+2;break}else if(o===-1){Ea.warn("parseMessage() | malformed message");return}if(r=ET(n,c,d,o),r!==!0){Ea.warn("parseMessage() |",r.error);return}d=o+2}if(n.hasHeader("content-length")){const h=n.getHeader("content-length");n.body=c.substr(a,h)}else n.body=c.substring(a);return n};function ST(c,t){let n=t,a=0,o=0;if(c.substring(n,n+2).match(/(^\r\n)/))return-2;for(;a===0;){if(o=c.indexOf(`\r
|
|
158
|
-
`,n),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?n=o+2:a=o}return a}function ET(c,t,n,a){let o;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),d=t.substring(s+1,a).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",d),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",d),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",d),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=yu.parse(d,"Record_Route"),o===-1)o=void 0;else for(const h of o)c.addHeader("record-route",d.substring(h.possition,h.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=h.parsed;break;case"call-id":case"i":c.setHeader("call-id",d),o=c.parseHeader("call-id"),o&&(c.call_id=d);break;case"contact":case"m":if(o=yu.parse(d,"Contact"),o===-1)o=void 0;else for(const h of o)c.addHeader("contact",d.substring(h.possition,h.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=h.parsed;break;case"content-length":case"l":c.setHeader("content-length",d),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",d),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",d),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof Ln.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",d),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",d),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",d),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",d),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",d),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",d),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",d),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(r,d),o=0}return o===void 0?{error:`error parsing header "${r}"`}:!0}const yT={parseMessage:vT},si=new na("Registrator"),ya=10;class AT{constructor(t,n){this._reg_id=1,this._ua=t,this._transport=n,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=vs.createRandomToken(22),this._cseq=0,this._to_uri=t.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 o=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=o}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){si.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),t.push(`Expires: ${this._expires}`);const n=new Tt.OutgoingRequest(H.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),a=new Wr(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,H.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,H.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:o=>{if(o.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):{if(this._registering=!1,!o.hasHeader("Contact")){si.debug("no Contact header in response to REGISTER, response ignored");break}const s=o.headers.Contact.reduce((_,g)=>_.concat(g.parsed),[]);let r=s.find(_=>this._sipInstance===_.getParam("+sip.instance")&&this._reg_id===parseInt(_.getParam("reg-id")));if(r||(r=s.find(_=>_.uri.user===this._ua.contact.uri.user)),!r){si.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let d=r.getParam("expires");!d&&o.hasHeader("expires")&&(d=o.getHeader("expires")),d||(d=this._expires),d=Number(d),d<ya&&(d=ya);const h=d>64?d*1e3/2+Math.floor((d/2-32)*1e3*Math.random()):d*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},h),r.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=r.getParam("temp-gruu").replace(/"/g,"")),r.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=r.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:o}));break}case/^423$/.test(o.status_code):{o.hasHeader("min-expires")?(this._expires=Number(o.getHeader("min-expires")),this._expires<ya&&(this._expires=ya),this.register()):(si.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(o,H.causes.SIP_FAILURE_CODE));break}default:{const s=vs.sipErrorCause(o.status_code);this._registrationFailure(o,s)}}}});this._registering=!0,a.send()}unregister(t={}){if(!this._registered){si.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();t.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),n.push("Expires: 0");const a=new Tt.OutgoingRequest(H.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new Wr(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,H.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,H.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const r=vs.sipErrorCause(s.status_code);this._unregistered(s,r)}}}}).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(t,n){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:n}))}_unregistered(t,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:n||null})}}const et=console,ks={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},CT=cT;class RT extends CT{constructor(t){super(t),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 AT(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(t,n){return super.call(t,n)}joinVideoCall(t,n,a){et.debug("call()");const o=new Sa(this);return o.configureMedia({audio:!0,video:!0}),o.connect(t,n,a),o}startScreenShare(){et.debug("startScreenShare()");for(const t in this._janus_sessions)this._janus_sessions[t].connectScreenShare()}changeMediaConstraints(t){for(const n in this._janus_sessions)this._janus_sessions[n].changeMediaConstraints(t)}startBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].connectBlur()}stopBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].stopBlur()}_loadConfig(t){try{ti.load(this._configuration,t)}catch(s){throw s}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=vs.newUUID());let n;typeof window<"u"&&typeof window.document<"u"?n=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(n=self.navigator.userAgent),n+=" "+De.USER_AGENT,this._configuration.user_agent=t.overrideUserAgent&&typeof t.overrideUserAgent=="function"?t.overrideUserAgent(n):n,t.onTransportCallback&&typeof t.onTransportCallback=="function"&&(this.onTransportCallback=t.onTransportCallback),this._configuration.jssip_id=vs.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new Mg(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=IT.bind(this),this._transport.onconnect=bT.bind(this),this._transport.ondisconnect=wT.bind(this),this._transport.ondata=OT.bind(this)}catch(s){throw et.warn(s),new Ns.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 s=this._configuration.uri.clone();s.user=null,s.clearParams(),s.clearHeaders(),this._configuration.registrar_server=s}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ln("sip",vs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(s={}){const r=s.anonymous||null,d=s.outbound||null;let h="<";return r?h+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":h+=this.pub_gruu||this.uri.toString(),d&&(r?!this.temp_gruu:!this.pub_gruu)&&(h+=";ob"),h+=">",h}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(o.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));et.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(ti.settings,s))switch(s){case"uri":case"registrar_server":et.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":et.debug(`- ${s}: NOT SHOWN`);break;default:et.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,n){t.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",n)}newJanusSession(t,n){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(a=>{a.setSession(t)}),this.processStreamPlugins.forEach(a=>{a.setSession(t)}),this.emit("newJanusSession",n)}kill(){}destroyMSRPSession(t){delete this._msrp_sessions[t.id]}destroyJanusSession(t){delete this._janus_sessions[t.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(t){var s,r,d,h;const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){et.debug("Request-URI does not point to us"),t.method!==De.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===De.SIPS){t.reply_sl(416);return}if(Ht.checkTransaction(this,t))return;if(n===De.INVITE?new Ht.InviteServerTransaction(this,this._transport,t):n!==De.ACK&&n!==De.CANCEL&&new Ht.NonInviteServerTransaction(this,this._transport,t),n===De.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const g=Date.now(),T=this.lastOptionsTimestamp>g-35e3,S=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>g;T&&S&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){t.reply(200);return}new yf.Options(this).init_incoming(t)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new yf.Message(this).init_incoming(t)}else if(n===De.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let a,o;if(t.to_tag)if(a=this._findDialog(t.call_id,t.from_tag,t.to_tag),a)a.receiveRequest(t);else if(n===De.NOTIFY)if(o=this._findSession(t),o)o.receiveRequest(t);else{if(t.body)try{const _=JSON.parse(t.body)||{};(r=(s=_.plugindata)==null?void 0:s.data)!=null&&r.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(_),(h=(d=_.plugindata)==null?void 0:d.data)!=null&&h.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(_.plugindata.data.unpublished)}catch(_){console.error(_)}t.reply(200)}else n!==De.ACK&&t.reply(481);else switch(n){case De.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const _=t.replaces;a=this._findDialog(_.call_id,_.from_tag,_.to_tag),a?(o=a.owner,o.isEnded()?t.reply(603):o.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(o=new Eu(this),o.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(o=new Sg(this),o.init_incoming(t));else et.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case De.BYE:t.reply(481);break;case De.CANCEL:o=this._findSession(t),o?o.receiveRequest(t):et.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}startMSRP(t,n){et.debug("startMSRP()",n);const a=new Eu(this);return a.connect(t),a}startJanus(t,n){et.debug("startJanus()",n);const a=new Eu(this);return a.connect(t),a}terminateMSRPSessions(t){et.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(t)}terminateJanusSessions(t){et.debug("terminateSessions()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||this._janus_sessions[n].terminate(t)}enableJanusAudio(t){et.debug("enableJanusAudio()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startAudio():this._janus_sessions[n].stopAudio())}enableJanusVideo(t){et.debug("enableJanusVideo()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startVideo():this._janus_sessions[n].stopVideo())}terminateAllSessions(){for(const t in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,t)){et.debug(`closing session ${t}`);try{this._sessions[t].terminate()}catch(n){console.error(n)}}}stop(t=!0){if(et.debug("stop()"),this._dynConfiguration={},this._status===ks.STATUS_USER_CLOSED){et.debug("UA already closed");return}this._registrator.close();const n=Object.keys(this._sessions).length;t&&this.terminateAllSessions();for(const o in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,o)){et.debug(`closing session ${o}`);try{this._msrp_sessions[o].terminate()}catch(s){console.error(s)}}for(const o in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,o)){et.debug(`closing session ${o}`);try{this._janus_sessions[o].terminate()}catch(s){console.error(s)}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch(s){console.error(s)}this._status=ks.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&&n===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function IT(c){this.emit("connecting",c)}function bT(c){this._status!==ks.STATUS_USER_CLOSED&&(this._status=ks.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function wT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const a in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],a)&&this._transactions[n][a].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==ks.STATUS_USER_CLOSED&&(this._status=ks.STATUS_NOT_READY,this._error=ks.NETWORK_ERROR)}function OT(c){const t=c.transport;let n=c.message;const a=n;if(n=yT.parseMessage(n,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(n,a),!!n&&!(this._status===ks.STATUS_USER_CLOSED&&n instanceof Ln.IncomingRequest)&&Xg(n,this,t)){if(n instanceof Ln.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Ln.IncomingResponse){let o;switch(n.method){case De.INVITE:o=this._transactions.ict[n.via_branch],o&&o.receiveResponse(n);break;case De.ACK:break;default:o=this._transactions.nict[n.via_branch],o&&o.receiveResponse(n);break}}}}const DT=["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"],NT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function gh(c){const t={};return DT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t.localHold=c._localHold,t}function Th(c){const t={};return NT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t}async function Au(c,t,n){const a=c.createMediaStreamSource(t),o=c.createMediaStreamDestination(),s=c.createGain();return a.connect(s),s.connect(o),s.gain.value=n,o.stream}function UT(c,t,n,a){if(vh())return;const o=document.createElement("audio");o.id=t._id,o.className="audioTag",o.srcObject=c,o.setSinkId(n),o.volume=a,o.play(),t.audioTag=o}function xT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function vh(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const PT=at,kT=Yt(),Ot=new PT("WebSocketInterface");var MT=class{constructor(t){Ot.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=kT.parse(t,"absoluteURI");if(n===-1)throw Ot.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Ot.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${t}`);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(t){this._via_transport=t.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Ot.debug("connect()"),this.isConnected()){Ot.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Ot.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Ot.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(t){this._onError(t)}}disconnect(){Ot.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(t){return Ot.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Ot.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(){Ot.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:n,reason:a}){Ot.debug(`WebSocket ${this._url} closed`),t===!1&&Ot.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,n,a)}_onMessage({data:t}){Ot.debug("received WebSocket message"),this.ondata(t)}_onError(t){Ot.warn(`WebSocket ${this._url} error: `,t)}};const Cu=Tl,LT=De,$T=Ts,HT=mt(),FT=_h,VT=ps(),jT=qo(),qT=Yt(),BT=MT;Nn("JsSIP")("version %s",Cu.version);var GT={C:LT,Exceptions:$T,Utils:HT,UA:FT,URI:VT,NameAddrHeader:jT,WebSocketInterface:BT,Grammar:qT,debug:Nn,get name(){return Cu.title},get version(){return Cu.version}};const WT=Me(GT);function Ru(c){return c<10?`0${c}`:`${c}`}function KT(c){let t=c.hours||0,n=c.minutes||0,a=c.seconds||0;a++,a===60&&(a=0,n++,n===60&&(n=0,t++));const o=`${Ru(t)}:${Ru(n)}:${Ru(a)}`;return{seconds:a,minutes:n,hours:t,formatted:o}}function YT(c){let t=0;for(let n=0;n<c.length;n++)t+=c[n]*c[n];return Math.sqrt(t/c.length)}async function JT(c,t,n=150){const a=t.createMediaStreamSource(c),o=t.createDelay();o.delayTime.value=n/1e3;const s=t.createGain();s.gain.value=0;const r=t.createMediaStreamDestination();return a.connect(o).connect(s).connect(r),{stream:r.stream,setSpeaking:d=>{s.gain.value=d?1:0}}}var yt={};yt.forEach=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)if(o in c){const s=Promise.resolve(c[o]).then(r=>t.call(n||globalThis,r,o,c));a.push(s)}await Promise.all(a)},yt.forEachSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)a in c&&await t.call(n||globalThis,await c[a],a,c)},yt.map=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=Promise.resolve(c[o]).then(s=>t.call(n||globalThis,s,o,c)));return Promise.all(a)},yt.mapSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=await t.call(n||globalThis,await c[o],o,c));return a},yt.find=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a();let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(c[r]):s===c.length&&a(),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.findSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return c[a]},yt.findIndex=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(-1);let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(r):s===c.length&&a(-1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.findIndexSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return a},yt.some=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!1);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?a(!0):s===c.length&&a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.someSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&await t.call(n||globalThis,await c[a],a,c))return!0;return!1},yt.every=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!0);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?s===c.length&&a(!0):a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.everySeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&!await t.call(n||globalThis,await c[a],a,c))return!1;return!0},yt.filter=(c,t,n)=>new Promise(async(a,o)=>{const s=[];for(let d=0;d<c.length;d++)d in c&&(s[d]=Promise.resolve(c[d]).then(h=>t.call(n||globalThis,h,d,c)).catch(o));const r=[];for(let d=0;d<s.length;d++)await s[d]&&r.push(await c[d]);a(r)}),yt.filterSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&await t.call(n||globalThis,await c[o],o,c)&&a.push(await c[o]);return a},yt.reduce=async(c,t,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let a,o;for(n!==void 0?(o=n,a=0):(o=c[0],a=1),a;a<c.length;a++)a in c&&(o=await t(await o,await c[a],a,c));return o};var Sh={};(function(c){const t=yt;Object.keys(t).forEach(n=>{const a=n.charAt(0).toUpperCase()+n.slice(1);c[`async${a}`]=async function(...o){return t[n](this,...o)}})})(Sh);var zT=Object.assign(yt,{instanceMethods:Sh});const Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},XT={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 QT={exports:{}};(function(c){var t=function(n){var a=Object.prototype,o=a.hasOwnProperty,s=Object.defineProperty||function(ee,Y,G){ee[Y]=G.value},r,d=typeof Symbol=="function"?Symbol:{},h=d.iterator||"@@iterator",_=d.asyncIterator||"@@asyncIterator",g=d.toStringTag||"@@toStringTag";function T(ee,Y,G){return Object.defineProperty(ee,Y,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[Y]}try{T({},"")}catch{T=function(Y,G,re){return Y[G]=re}}function S(ee,Y,G,re){var ge=Y&&Y.prototype instanceof ie?Y:ie,be=Object.create(ge.prototype),ke=new x(re||[]);return s(be,"_invoke",{value:J(ee,G,ke)}),be}n.wrap=S;function E(ee,Y,G){try{return{type:"normal",arg:ee.call(Y,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",C="suspendedYield",R="executing",k="completed",M={};function ie(){}function N(){}function V(){}var Ee={};T(Ee,h,function(){return this});var ve=Object.getPrototypeOf,L=ve&&ve(ve(se([])));L&&L!==a&&o.call(L,h)&&(Ee=L);var D=V.prototype=ie.prototype=Object.create(Ee);N.prototype=V,s(D,"constructor",{value:V,configurable:!0}),s(V,"constructor",{value:N,configurable:!0}),N.displayName=T(V,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(Y){T(ee,Y,function(G){return this._invoke(Y,G)})})}n.isGeneratorFunction=function(ee){var Y=typeof ee=="function"&&ee.constructor;return Y?Y===N||(Y.displayName||Y.name)==="GeneratorFunction":!1},n.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,V):(ee.__proto__=V,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},n.awrap=function(ee){return{__await:ee}};function q(ee,Y){function G(be,ke,Re,ae){var ye=E(ee[be],ee,ke);if(ye.type==="throw")ae(ye.arg);else{var lt=ye.arg,ot=lt.value;return ot&&typeof ot=="object"&&o.call(ot,"__await")?Y.resolve(ot.__await).then(function(Se){G("next",Se,Re,ae)},function(Se){G("throw",Se,Re,ae)}):Y.resolve(ot).then(function(Se){lt.value=Se,Re(lt)},function(Se){return G("throw",Se,Re,ae)})}}var re;function ge(be,ke){function Re(){return new Y(function(ae,ye){G(be,ke,ae,ye)})}return re=re?re.then(Re,Re):Re()}s(this,"_invoke",{value:ge})}B(q.prototype),T(q.prototype,_,function(){return this}),n.AsyncIterator=q,n.async=function(ee,Y,G,re,ge){ge===void 0&&(ge=Promise);var be=new q(S(ee,Y,G,re),ge);return n.isGeneratorFunction(Y)?be:be.next().then(function(ke){return ke.done?ke.value:be.next()})};function J(ee,Y,G){var re=A;return function(be,ke){if(re===R)throw new Error("Generator is already running");if(re===k){if(be==="throw")throw ke;return it()}for(G.method=be,G.arg=ke;;){var Re=G.delegate;if(Re){var ae=F(Re,G);if(ae){if(ae===M)continue;return ae}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=k,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=R;var ye=E(ee,Y,G);if(ye.type==="normal"){if(re=G.done?k:C,ye.arg===M)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=k,G.method="throw",G.arg=ye.arg)}}}function F(ee,Y){var G=Y.method,re=ee.iterator[G];if(re===r)return Y.delegate=null,G==="throw"&&ee.iterator.return&&(Y.method="return",Y.arg=r,F(ee,Y),Y.method==="throw")||G!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+G+"' method")),M;var ge=E(re,ee.iterator,Y.arg);if(ge.type==="throw")return Y.method="throw",Y.arg=ge.arg,Y.delegate=null,M;var be=ge.arg;if(!be)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,M;if(be.done)Y[ee.resultName]=be.value,Y.next=ee.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=r);else return be;return Y.delegate=null,M}B(D),T(D,g,"Generator"),T(D,h,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function Z(ee){var Y={tryLoc:ee[0]};1 in ee&&(Y.catchLoc=ee[1]),2 in ee&&(Y.finallyLoc=ee[2],Y.afterLoc=ee[3]),this.tryEntries.push(Y)}function U(ee){var Y=ee.completion||{};Y.type="normal",delete Y.arg,ee.completion=Y}function x(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(Z,this),this.reset(!0)}n.keys=function(ee){var Y=Object(ee),G=[];for(var re in Y)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in Y)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var Y=ee[h];if(Y)return Y.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(o.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=r,ge.done=!0,ge};return re.next=re}}return{next:it}}n.values=se;function it(){return{value:r,done:!0}}return x.prototype={constructor:x,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(U),!ee)for(var Y in this)Y.charAt(0)==="t"&&o.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=r)},stop:function(){this.done=!0;var ee=this.tryEntries[0],Y=ee.completion;if(Y.type==="throw")throw Y.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var Y=this;function G(ae,ye){return be.type="throw",be.arg=ee,Y.next=ae,ye&&(Y.method="next",Y.arg=r),!!ye}for(var re=this.tryEntries.length-1;re>=0;--re){var ge=this.tryEntries[re],be=ge.completion;if(ge.tryLoc==="root")return G("end");if(ge.tryLoc<=this.prev){var ke=o.call(ge,"catchLoc"),Re=o.call(ge,"finallyLoc");if(ke&&Re){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0);if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else if(ke){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0)}else if(Re){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,Y){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&o.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=Y&&Y<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=Y,ge?(this.method="next",this.next=ge.finallyLoc,M):this.complete(be)},complete:function(ee,Y){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&Y&&(this.next=Y),M},finish:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),M}},catch:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.tryLoc===ee){var re=G.completion;if(re.type==="throw"){var ge=re.arg;U(G)}return ge}}throw new Error("illegal catch attempt")},delegateYield:function(ee,Y,G){return this.delegate={iterator:se(ee),resultName:Y,nextLoc:G},this.method==="next"&&(this.arg=r),M}},n}(c.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(QT);var Eh={exports:{}};(function(c){(function(t,n){c.exports?c.exports=n():t.log=n()})(cs,function(){var t=function(){},n="undefined",a=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function s(C,R){var k=C[R];if(typeof k.bind=="function")return k.bind(C);try{return Function.prototype.bind.call(k,C)}catch{return function(){return Function.prototype.apply.apply(k,[C,arguments])}}}function r(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(C){return C==="debug"&&(C="log"),typeof console===n?!1:C==="trace"&&a?r:console[C]!==void 0?s(console,C):console.log!==void 0?s(console,"log"):t}function h(C,R){for(var k=0;k<o.length;k++){var M=o[k];this[M]=k<C?t:this.methodFactory(M,C,R)}this.log=this.debug}function _(C,R,k){return function(){typeof console!==n&&(h.call(this,R,k),this[C].apply(this,arguments))}}function g(C,R,k){return d(C)||_.apply(this,arguments)}function T(C,R,k){var M=this,ie;R=R??"WARN";var N="loglevel";typeof C=="string"?N+=":"+C:typeof C=="symbol"&&(N=void 0);function V(D){var B=(o[D]||"silent").toUpperCase();if(!(typeof window===n||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Ee(){var D;if(!(typeof window===n||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===n)try{var B=window.document.cookie,q=B.indexOf(encodeURIComponent(N)+"=");q!==-1&&(D=/^([^;]+)/.exec(B.slice(q))[1])}catch{}return M.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===n||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}M.name=C,M.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},M.methodFactory=k||g,M.getLevel=function(){return ie},M.setLevel=function(D,B){if(typeof D=="string"&&M.levels[D.toUpperCase()]!==void 0&&(D=M.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=M.levels.SILENT){if(ie=D,B!==!1&&V(D),h.call(M,D,C),typeof console===n&&D<M.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},M.setDefaultLevel=function(D){R=D,Ee()||M.setLevel(D,!1)},M.resetLevel=function(){M.setLevel(R,!1),ve()},M.enableAll=function(D){M.setLevel(M.levels.TRACE,D)},M.disableAll=function(D){M.setLevel(M.levels.SILENT,D)};var L=Ee();L==null&&(L=R),M.setLevel(L,!1)}var S=new T,E={};S.getLogger=function(R){if(typeof R!="symbol"&&typeof R!="string"||R==="")throw new TypeError("You must supply a name when creating a logger.");var k=E[R];return k||(k=E[R]=new T(R,S.getLevel(),S.methodFactory)),k};var A=typeof window!==n?window.log:void 0;return S.noConflict=function(){return typeof window!==n&&window.log===S&&(window.log=A),S},S.getLoggers=function(){return E},S.default=S,S})})(Eh);var It=Eh.exports;const Ss=()=>`${new Date().toISOString()} | metrics`,Es=(c,t,n)=>`${c} | ${t} | ${n}`;It.setDefaultLevel(It.levels.TRACE);const ZT=c=>{It.info(Es(Ss(),"log ",`set log level to ${c?"verbose":"info"}`)),It.setLevel(c?It.levels.TRACE:It.levels.INFO)},ev=c=>{const t=[...Object.keys(It.levels)];t.includes(c)?(It.info(Es(Ss(),"log ",`update log level to ${c.toLowerCase()}`)),It.setLevel(c)):It.warn(Es(Ss(),"log ","Incorrect log level please choose one of "),t)},xe=(c,t,n)=>{n?It.debug(Es(Ss(),c,t),n):It.debug(Es(Ss(),c,t))},Iu=(c,t)=>{It.info(Es(Ss(),c,t))},an=(c,t)=>{It.info(Es(Ss(),c,t))},Aa=(c,t)=>{It.warn(Es(Ss(),c,t))},jn=(c,t)=>{It.error(Es(Ss(),c,t))};function tv(c){return Math.floor(Math.random()*c).toString()}function yh(c,t){let n=t;return c.forEach(a=>{n=n.replace(a,"")}),n}function sv(c,t){let n="";for(let a=0;a<t;a+=1)n+=c[tv(c.length)];return n}function nv({length:c=20,useLetters:t=!0,useNumbers:n=!0,includeSymbols:a=[],excludeSymbols:o=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",r="0123456789",d=[],h=[],_=[];return t&&(o.length&&(s=yh(o,s)),h=s.split("")),n&&(o.length&&(r=yh(o,r)),_=r.split("")),d=[...h,..._,...a],sv(d,c)}var rv=nv;const ni=Me(rv),iv=()=>"WebRTCMetrics",lv=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},ys={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ri={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},av=()=>({...{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:[]}}),Ah={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:$e.INBOUND},Ch={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:$e.OUTBOUND},Rh={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:$e.INBOUND},Ih={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:$e.OUTBOUND},ov=c=>{const t={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const n={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(a=>{n.audio[a]={...c.audio[a]}}),Object.keys(c.video).forEach(a=>{n.video[a]={...c.video[a]}}),n}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},uv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${ni()}`,cid:`c-${ni()}`,uid:`u-${ni()}`,record:!1,ticket:!0},Qt={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"},j={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"},P={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},ii={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},bu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},wu="config ",cv=(c,t={},n)=>{const a={...n,...t};return t.pname||Aa(wu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),t.cid||Aa(wu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),t.uid||Aa(wu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),a.pc=c,a},fv=(c={})=>{const t={...uv,...c};return t.name=iv(),t.version=lv(),t},li=(c,t,n,a=!1,o)=>{let s=c.map(r=>{if(!n)return r[t];if(!o)return r[t][n];const d=r[t][o];return d?d[n]:null});return s=s.filter(r=>a?Number.isFinite(r)&&r>0:Number.isFinite(r)),s.length===0?[]:s},Ms=c=>c.reduce((t,n)=>t+n,0)/c.length,hv=()=>`probe-${ni()}`,dv=()=>`coltr-${ni()}`,bh=c=>new Promise(t=>setTimeout(t,c)),Ou=(c,t,n)=>{t?c.call(t,n):c(n)},We=(c,t,n,a)=>{const o=li(c,t,n,!0,a);if(o.length===0)return null;const s=o.reduce((_,g)=>_+g,0)/o.length;return s===0?null:o.map(_=>Math.abs(s-_)).reduce((_,g)=>_+g,0)/o.length*100/s},Xe=(c,t,n,a=!1,o)=>{const s=li(c,t,n,a,o);return s.length===0?null:s.reduce((r,d)=>r+d,0)/s.length},on=(c,t,n)=>li(c,t,n).reduce((o,s)=>o+s,0),Ke=(c,t,n,a)=>{const o=li(c,t,n,!0,a);return o.length===0?null:Math.min(...o)},Ye=(c,t,n,a)=>{const o=li(c,t,n,!1,a);return o.length===0?null:Math.max(...o)},At=(c,t,n,a)=>{const o=c.slice().pop();if(!o)return null;if(!n)return o[t];if(!a)return o[t][n];const s=o[t][a];return s?s[n]:null},_v=c=>c.slice().pop(),ht=(c,t,n)=>{if(!t)return null;const a={};let o=t[P.AUDIO][c];o||(o=n===$e.INBOUND?{...Ah}:{...Ch}),a[P.AUDIO]=o;let s=t[P.VIDEO][c];return s||(s=n===$e.INBOUND?{...Rh}:{...Ih}),a[P.VIDEO]=s,a},ai="exporter ",pv="2.0",wh=(c,t,n)=>{if(!c||c.length===0)return 0;const a=c[c.length-1];if(!a)return 0;const o=a[t][n];if(o){const s=o.total_rtt_ms_out,r=o.total_rtt_measure_out;return!r||!s?Xe(c,t,"delta_rtt_ms_out",!1,n):Number(s/r)}return null},mv=(c,t)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const a=n[t].total_rtt_connectivity_ms,o=n[t].total_rtt_connectivity_measure;return!o||!a?Xe(c,t,"delta_rtt_connectivity_ms"):Number(a/o)},gv=c=>At(c,"network","local_candidate_type")!=="relay"?`direct/${At(c,"network","local_candidate_protocol")}`:`turn/${At(c,"network","local_candidate_relay_protocol")}`,Tv=c=>{const t=At(c,"network","remote_candidate_type"),n=At(c,"network","remote_candidate_protocol");return t!=="relay"?`direct/${n}`:`turn/${n}`};class vv{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){Iu(ai,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){Iu(ai,"stop() - stop exporter...");const t=new Date;return this._end=t.toJSON(),t}saveReferenceReport(t){this._referenceReport=t}getReferenceReport(){return this._referenceReport}addReport(t){this._cfg.ticket&&(xe(ai,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){Iu(ai,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){xe(ai,"ticket() - generate ticket");const t=At(this._reports,"audio","total_packets_lost_in"),n=At(this._reports,"audio","total_packets_in"),a=At(this._reports,"video","total_packets_lost_in"),o=At(this._reports,"video","total_packets_in"),s={},r=_v(this._reports);return r&&(Object.keys(r[P.AUDIO]).forEach(d=>{const h=r[P.AUDIO][d];if(s[h.ssrc]={type:P.AUDIO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,P.AUDIO,"delta_jitter_ms_in",!1,d),min:Ke(this._reports,P.AUDIO,"delta_jitter_ms_in",d),max:Ye(this._reports,P.AUDIO,"delta_jitter_ms_in",d),volatility:We(this._reports,P.AUDIO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,P.AUDIO,"delta_kbs_in",!1,d),min:Ke(this._reports,P.AUDIO,"delta_kbs_in",d),max:Ye(this._reports,P.AUDIO,"delta_kbs_in",d),volatility:We(this._reports,P.AUDIO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,P.AUDIO,"delta_KBytes_in",!1,d),min:Ke(this._reports,P.AUDIO,"delta_KBytes_in",d),max:Ye(this._reports,P.AUDIO,"delta_KBytes_in",d),volatility:We(this._reports,P.AUDIO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={emodel:{avg:Xe(this._reports,P.AUDIO,"mos_emodel_in",!1,d),min:Ke(this._reports,P.AUDIO,"mos_emodel_in",d),max:Ye(this._reports,P.AUDIO,"mos_emodel_in",d),volatility:We(this._reports,P.AUDIO,"mos_emodel_in",d)},effective:{avg:Xe(this._reports,P.AUDIO,"mos_in",!1,d),min:Ke(this._reports,P.AUDIO,"mos_in",d),max:Ye(this._reports,P.AUDIO,"mos_in",d),volatility:We(this._reports,P.AUDIO,"mos_in",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},E=At(this._reports,P.AUDIO,"total_packets_lost_in",d),A=At(this._reports,P.AUDIO,"total_packets_in",d),C={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].mos=S,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}else{const _={avg:Xe(this._reports,P.AUDIO,"delta_jitter_ms_out",!1,d),min:Ke(this._reports,P.AUDIO,"delta_jitter_ms_out",d),max:Ye(this._reports,P.AUDIO,"delta_jitter_ms_out",d),volatility:We(this._reports,P.AUDIO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,P.AUDIO,"delta_kbs_out",!1,d),min:Ke(this._reports,P.AUDIO,"delta_kbs_out",d),max:Ye(this._reports,P.AUDIO,"delta_kbs_out",d),volatility:We(this._reports,P.AUDIO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,P.AUDIO,"delta_KBytes_out",!1,d),min:Ke(this._reports,P.AUDIO,"delta_KBytes_out",d),max:Ye(this._reports,P.AUDIO,"delta_KBytes_out",d),volatility:We(this._reports,P.AUDIO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},S={avg:wh(this._reports,P.AUDIO,d),min:Ke(this._reports,P.AUDIO,"delta_rtt_ms_out",d),max:Ye(this._reports,P.AUDIO,"delta_rtt_ms_out",d),volatility:We(this._reports,P.AUDIO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=At(this._reports,P.AUDIO,"total_packets_lost_out",d),A=At(this._reports,P.AUDIO,"total_packets_out",d),C={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},R={emodel:{avg:Xe(this._reports,P.AUDIO,"mos_emodel_out",!1,d),min:Ke(this._reports,P.AUDIO,"mos_emodel_out",d),max:Ye(this._reports,P.AUDIO,"mos_emodel_out",d),volatility:We(this._reports,P.AUDIO,"mos_emodel_out",d)},effective:{avg:Xe(this._reports,P.AUDIO,"mos_out",!1,d),min:Ke(this._reports,P.AUDIO,"mos_out",d),max:Ye(this._reports,P.AUDIO,"mos_out",d),volatility:We(this._reports,P.AUDIO,"mos_out",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[d].jitter=_,s[d].rtt=S,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C,s[d].mos=R}}),Object.keys(r[P.VIDEO]).forEach(d=>{const h=r[P.VIDEO][d];if(s[d]={type:P.VIDEO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,P.VIDEO,"delta_jitter_ms_in",!1,d),min:Ke(this._reports,P.VIDEO,"delta_jitter_ms_in",d),max:Ye(this._reports,P.VIDEO,"delta_jitter_ms_in",d),volatility:We(this._reports,P.VIDEO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,P.VIDEO,"delta_kbs_in",!1,d),min:Ke(this._reports,P.VIDEO,"delta_kbs_in",d),max:Ye(this._reports,P.VIDEO,"delta_kbs_in",d),volatility:We(this._reports,P.VIDEO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,P.VIDEO,"delta_KBytes_in",!1,d),min:Ke(this._reports,P.VIDEO,"delta_KBytes_in",d),max:Ye(this._reports,P.VIDEO,"delta_KBytes_in",d),volatility:We(this._reports,P.VIDEO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S=At(this._reports,P.VIDEO,"total_packets_lost_in",d),E=At(this._reports,P.VIDEO,"total_packets_in",d),A={lost:S,avg:Math.round((S/(S+E)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].traffic=T,s[d].bitrate=g,s[d].loss=A}else{const _={avg:Xe(this._reports,P.VIDEO,"delta_jitter_ms_out",!1,d),min:Ke(this._reports,P.VIDEO,"delta_jitter_ms_out",d),max:Ye(this._reports,P.VIDEO,"delta_jitter_ms_out",d),volatility:We(this._reports,P.VIDEO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,P.VIDEO,"delta_kbs_out",!1,d),min:Ke(this._reports,P.VIDEO,"delta_kbs_out",d),max:Ye(this._reports,P.VIDEO,"delta_kbs_out",d),volatility:We(this._reports,P.VIDEO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,P.VIDEO,"delta_KBytes_out",!1,d),min:Ke(this._reports,P.VIDEO,"delta_KBytes_out",d),max:Ye(this._reports,P.VIDEO,"delta_KBytes_out",d),volatility:We(this._reports,P.VIDEO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={avg:wh(this._reports,P.VIDEO,d),min:Ke(this._reports,P.VIDEO,"delta_rtt_ms_out",d),max:Ye(this._reports,P.VIDEO,"delta_rtt_ms_out",d),volatility:We(this._reports,P.VIDEO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=At(this._reports,P.VIDEO,"total_packets_lost_out",d),A=At(this._reports,P.VIDEO,"total_packets_out",d),C={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].rtt=S,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}})),{version:pv,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:s,data:{rtt:{avg:mv(this._reports,"data"),min:Ke(this._reports,"data","delta_rtt_connectivity_ms"),max:Ye(this._reports,"data","delta_rtt_connectivity_ms"),volatility:We(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((t/(t+n)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+o)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Xe(this._reports,"data","delta_kbs_in"),min:Ke(this._reports,"data","delta_kbs_in"),max:Ye(this._reports,"data","delta_kbs_in"),volatility:We(this._reports,"data","delta_kbs_in")},out:{avg:Xe(this._reports,"data","delta_kbs_out"),min:Ke(this._reports,"data","delta_kbs_out"),max:Ye(this._reports,"data","delta_kbs_out"),volatility:We(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Xe(this._reports,"data","delta_KBytes_in"),min:Ke(this._reports,"data","delta_KBytes_in"),max:Ye(this._reports,"data","delta_KBytes_in"),volatility:We(this._reports,"data","delta_KBytes_in")},out:{avg:Xe(this._reports,"data","delta_KBytes_out"),min:Ke(this._reports,"data","delta_KBytes_out"),max:Ye(this._reports,"data","delta_KBytes_out"),volatility:We(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:gv(this._reports),remoteConnection:Tv(this._reports)}}}}updateConfig(t){this._cfg=t}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const t=this._reports.slice();return t.pop(),t.pop()||null}getReportsNumber(){return this._reports.length}}const Ls="extractor ",Oh=(c,t,n,a)=>{let o=!1;const s=a[t].total_rtt_ms_out,r=a[t].total_rtt_measure_out,d=n?n[t].total_rtt_ms_out:0,h=n?n[t].total_rtt_measure_out:0,_={rtt:null,totalRTT:s,totalRTTMeasurements:r};if(c[j.TIMESTAMP]===a[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,j.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,j.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(o=!0,Number(c[j.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[j.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h===r))return _;const g=1e3*Number(c[j.ROUND_TRIP_TIME]);let T=s+g,S=r+1;return o&&(T=1e3*Number(c[j.TOTAL_ROUND_TRIP_TIME])-d,S=Number(c[j.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h),{rtt:g,totalRTT:T,totalRTTMeasurements:S}},Sv=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,j.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[t].total_rtt_connectivity_ms,totalRTTMeasurements:a[t].total_rtt_connectivity_measure};const o=1e3*Number(c[j.CURRENT_ROUND_TRIP_TIME]);let s=a[t].total_rtt_connectivity_ms+o,r=a[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,j.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(c[j.TOTAL_ROUND_TRIP_TIME])-(n?n[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,j.RESPONSES_RECEIVED)&&(r=Number(c[j.RESPONSES_RECEIVED])-(n?n[t].total_rtt_connectivity_measure:0)),{rtt:o,totalRTT:s,totalRTTMeasurements:r}},Ca=(c,t,n)=>c[j.TIMESTAMP]===n[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,j.JITTER)?null:1e3*(Number(c[j.JITTER])||0),Ev=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,j.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,j.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:t[P.VIDEO].delta_ms_decode_frame_in,frames_decoded:t[P.VIDEO].total_frames_decoded_in,total_decode_time:t[P.VIDEO].total_time_decoded_in};const n=c[j.FRAMES_DECODED],a=c[j.TOTAL_DECODE_TIME],o=a-t[P.VIDEO].total_time_decoded_in,s=n-t[P.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?o*1e3/s:0,frames_decoded:n,total_decode_time:a}},yv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,j.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,j.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:t[P.VIDEO].delta_ms_encode_frame_out,frames_encoded:t[P.VIDEO].total_frames_encoded_out,total_encode_time:t[P.VIDEO].total_time_encoded_out};const n=c[j.FRAMES_ENCODED],a=c[j.TOTAL_ENCODE_TIME],o=a-t[P.VIDEO].total_time_encoded_out,s=n-t[P.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&o?o*1e3/s:0,frames_encoded:n,total_encode_time:a}},Dh=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,j.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,j.BYTES_SENT))return{packetsSent:n[t].total_packets_out,packetsLost:n[t].total_packets_lost_out,bytesSent:n[t].total_KBytes_out};const o=Number(c[j.PACKETS_SENT])||0-(a?a[t].total_packets_out:0),s=o-n[t].total_packets_out,r=Number(c[j.BYTES_SENT])/1024-(a?a[t].total_KBytes_out:0),d=r-n[t].total_KBytes_out,h=c[j.TIMESTAMP]||Date.now(),_=a?a.timestamp:null;let g=n.timestamp;!g&&_&&(g=_);const T=g?h-g:0,S=T>0?d*.008*1024/T*1e3:0;return{packetsSent:o,deltaPacketsSent:s,KBytesSent:r,deltaKBytesSent:d,kbsSent:S}},Nh=(c,t,n,a)=>{let o=n[t].total_packets_lost_out,s=0,r=0;return Object.prototype.hasOwnProperty.call(c,j.PACKETS_LOST)&&(o=Number(c[j.PACKETS_LOST])||0-(a?a[t].total_packets_lost_out:0),s=o-n[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,j.FRACTION_LOST)&&(r=Number(100*c[j.FRACTION_LOST])),{packetsLost:o,deltaPacketsLost:s,fractionLost:r}},Uh=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,j.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,j.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,j.BYTES_RECEIVED))return{percent_packets_lost:n[t].percent_packets_lost_in,packetsReceived:n[t].total_packets_in,packetsLost:n[t].total_packets_lost_in,bytesReceived:n[t].total_KBytes_in};const o=Number(c[j.PACKETS_RECEIVED])||0-(a?a[t].total_packets_in:0),s=Number(c[j.PACKETS_LOST])||0-(a?a[t].total_packets_lost_in:0),r=s-n[t].total_packets_lost_in,d=o-n[t].total_packets_in,h=o!==n[t].total_packets_in?r*100/(r+d):0,_=Number(c[j.BYTES_RECEIVED])/1024-(a?a[t].total_KBytes_in:0),g=_-n[t].total_KBytes_in,T=c[j.TIMESTAMP]||Date.now(),S=a?a.timestamp:null;let E=n.timestamp;!E&&S&&(E=S);const A=E?T-E:0,C=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:h,packetsReceived:o,deltaPacketsReceived:d,packetsLost:s,deltaPacketsLost:r,KBytesReceived:_,deltaKBytesReceived:g,kbsReceived:C}},Av=c=>c[j.CANDIDATE_TYPE]!=="relay"?"":c[j.RELAY_PROTOCOL]||"",Cv=c=>{if(!Object.prototype.hasOwnProperty.call(c,j.NETWORK_TYPE))return ii.WIFI;switch(c[j.NETWORK_TYPE]){case bu.ETHERNET:return ii.ETHERNET;case bu.CELLULAR_4G:return ii.CELLULAR_4G;case bu.WIFI:return ii.WIFI;default:return ii.CELLULAR}},xh=c=>!Object.prototype.hasOwnProperty.call(c,j.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,j.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[j.FRAME_WIDTH]||null,height:c[j.FRAME_HEIGHT]||null,framerate:c[j.FRAMES_PER_SECOND]},Rv=c=>{const t=Object.prototype.hasOwnProperty.call(c,j.QUALITY_LIMITATION_REASON)?c[j.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,j.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[j.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(c,j.QUALITY_LIMITATION_DURATIONS)?c[j.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(o=>{a[o]>1e3&&(a[o]=Number(a[o]/1e3))}),{reason:t,durations:a,resolutionChanges:n}},Iv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,j.PLI)||!Object.prototype.hasOwnProperty.call(c,j.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(c[j.PLI]||0)-(n?n[P.VIDEO].total_pli_sent_in:0),o=(c[j.NACK]||0)-(n?n[P.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[P.VIDEO].total_pli_sent_in,deltaNackCount:o-t[P.VIDEO].total_nack_sent_in}},bv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,j.PLI)||!Object.prototype.hasOwnProperty.call(c,j.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(c[j.PLI]||0)-(n?n[P.VIDEO].total_pli_received_out:0),o=(c[j.NACK]||0)-(n?n[P.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[P.VIDEO].total_pli_received_out,deltaNackCount:o-t[P.VIDEO].total_nack_received_out}},wv=c=>({channels:c[j.CHANNELS]||null,clock_rate:c[j.CLOCK_RATE]||null,mime_type:c[j.MIME_TYPE]||null,sdp_fmtp_line:c[j.SDP_FMTP_LINE]||null}),Ov=c=>({clock_rate:c[j.CLOCK_RATE]||null,mime_type:c[j.MIME_TYPE]||null}),Dv=(c,t,n)=>{const a=(c[j.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),o=(c[j.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),s=c[j.TIMESTAMP]||Date.now(),r=a-t.data.total_KBytes_in,d=o-t.data.total_KBytes_out,h=n?n.timestamp:null;let _=t.timestamp;!_&&h&&(_=h);const g=_?s-_:0,T=g>0?r*.008*1024/g*1e3:0,S=g>0?d*.008*1024/g*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:o,delta_KBytes_received:r,delta_KBytes_sent:d,kbs_speed_received:T,kbs_speed_sent:S}},Nv=c=>{const t=c[j.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[j.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:n}},Uv=(c,t,n,a)=>{if(!c)return[];switch(c[j.TYPE]){case Qt.CANDIDATE_PAIR:let o=!1;if(c[j.NOMINATED]&&c[j.STATE]===P.SUCCEEDED&&(o=!0,xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c),j.SELECTED in c&&!c[j.SELECTED]&&(o=!1)),o){const r=c[j.LOCAL_CANDIDATE_ID],d=c[j.REMOTE_CANDIDATE_ID],h=Dv(c,t,a),_=Nv(c),g=Sv(c,"data",a,t);return[{type:ne.NETWORK,value:{local_candidate_id:r}},{type:ne.NETWORK,value:{remote_candidate_id:d}},{type:ne.DATA,value:{total_KBytes_in:h.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:h.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:h.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:h.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:h.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:h.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:_.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:_.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case Qt.LOCAL_CANDIDATE:if(c[j.ID]===t.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:Cv(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[j.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[j.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:Av(c)}}];break;case Qt.REMOTE_CANDIDATE:if(c[j.ID]===t.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[j.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[j.PROTOCOL]||""}}];break;case Qt.INBOUND_RTP:{xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);const r=c[j.SSRC],d=ht(r,t,$e.INBOUND);d&&(d.timestamp=t.timestamp);const h=ht(r,a,$e.INBOUND);if(h&&(h.timestamp=a.timestamp),c[j.MEDIA_TYPE]===P.AUDIO){const _=Uh(c,P.AUDIO,d,h),g=Ca(c,P.AUDIO,d),T=c[j.CODEC_ID]||"";return[{ssrc:r,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:r,type:ne.AUDIO,value:{total_packets_in:_.packetsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_in:_.deltaPacketsReceived}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_in:_.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_in:_.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_in:_.percentPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_in:_.KBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_in:_.deltaKBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_in:_.kbsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[j.MEDIA_TYPE]===P.VIDEO){const _=Ev(c,d),g=Uh(c,P.VIDEO,d,h),T=Ca(c,P.VIDEO,d),S=c[j.DECODER_IMPLEMENTATION]||null,E=c[j.CODEC_ID]||null,A=xh(c),C=Iv(c,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_in:E}},{ssrc:r,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:r,type:ne.VIDEO,value:{decoder_in:S}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_decode_frame_in:_.delta_ms_decode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_decoded_in:_.frames_decoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_decoded_in:_.total_decode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_sent_in:C.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_sent_in:C.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_sent_in:C.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_sent_in:C.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_in:A}}]}break}case Qt.OUTBOUND_RTP:{xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);const r=c[j.SSRC],d=ht(r,t,$e.OUTBOUND);d&&(d.timestamp=t.timestamp);const h=ht(r,a,$e.OUTBOUND);if(h&&(h.timestamp=a.timestamp),c[j.MEDIA_TYPE]===P.AUDIO){const _=c[j.CODEC_ID]||null,g=Dh(c,P.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{codec_id_out:_}},{ssrc:r,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[j.MEDIA_TYPE]===P.VIDEO){const _=c[j.ENCODER_IMPLEMENTATION]||null,g=c[j.CODEC_ID]||null,T=yv(c,d),S=xh(c),E=Rv(c),A=bv(c,d,h),C=Dh(c,P.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:r,type:ne.VIDEO,value:{total_packets_out:C.packetsSent}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_out:C.deltaPacketsSent}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_out:C.KBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_out:C.deltaKBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_out:C.kbsSent}},{ssrc:r,type:ne.VIDEO,value:{encoder_out:_}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_out:S}},{ssrc:r,type:ne.VIDEO,value:{limitation_out:E}}]}break}case Qt.MEDIA_SOURCE:{xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);break}case Qt.TRACK:{xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);break}case Qt.CODEC:const s=[];return Object.keys(t[P.AUDIO]).forEach(r=>{const d=t[P.AUDIO][r];if(d.codec_id_in===c[j.ID]||d.codec_id_out===c[j.ID]){xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);const h=wv(c);c[j.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_out:h}})}}),Object.keys(t[P.VIDEO]).forEach(r=>{const d=t[P.VIDEO][r];if(d.codec_id_in===c[j.ID]||d.codec_id_out===c[j.ID]){xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);const h=Ov(c);c[j.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_out:h}})}}),s;case Qt.REMOTE_INBOUND_RTP:{xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);const r=c[j.SSRC],d=ht(r,t,$e.OUTBOUND),h=ht(r,a,$e.OUTBOUND);if(c[j.KIND]===P.AUDIO){const _=Oh(c,P.AUDIO,h,d),g=Ca(c,P.AUDIO,d),T=Nh(c,P.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.AUDIO,value:{timestamp_out:c[j.TIMESTAMP]}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[j.KIND]===P.VIDEO){const _=Oh(c,P.VIDEO,h,d),g=Ca(c,P.VIDEO,d),T=Nh(c,P.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.VIDEO,value:{timestamp_out:c[j.TIMESTAMP]}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Ra=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),xv=(c,t=P.AUDIO,n,a,o)=>{const s=ht(o,c,$e.INBOUND),r=ht(o,n,$e.INBOUND),d=ht(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in,T=s[t].delta_jitter_ms_in,S=r&&r[t].delta_jitter_ms_in||null,E=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,R=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),R&&h.push(R),T&&_.push(T),n&&S&&_.push(S),a&&E&&_.push(E);const k=h.length>0?Ms(h):100,M=_.length>0?Ms(_):10,ie=93.2-g,N=.18*ie*ie-27.9*ie+1126.62,V=(k+M)/2,Ee=V-177.3<0?0:1,ve=.024*V+.11*(V-177.3)*Ee,L=N-ve;return Ra(L)},Pv=(c,t=P.AUDIO,n,a,o)=>{const s=ht(o,c,$e.OUTBOUND),r=ht(o,n,$e.OUTBOUND),d=ht(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out,T=s[t].delta_rtt_ms_out,S=r&&r[t].delta_rtt_ms_out||null,E=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,R=d&&d[t].delta_jitter_ms_out||null,k=c.data.delta_rtt_connectivity_ms,M=n&&n.data.delta_rtt_connectivity_ms||null,ie=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):k&&h.push(k),S?h.push(S):M&&h.push(M),E?h.push(E):ie&&h.push(ie),A&&_.push(A),n&&C&&_.push(C),a&&R&&_.push(R);const N=h.length>0?Ms(h):100,V=_.length>0?Ms(_):10,Ee=93.2-g,ve=.18*Ee*Ee-27.9*Ee+1126.62,L=(N+V)/2,D=L-177.3<0?0:1,B=.024*L+.11*(L-177.3)*D,q=ve-B;return Ra(q)},kv=(c,t=P.AUDIO,n,a,o)=>{const s=ht(o,c,$e.INBOUND),r=ht(o,n,$e.INBOUND),d=ht(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in/100,T=s[t].delta_jitter_ms_in,S=r&&r[t].delta_jitter_ms_in||null,E=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,R=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),R&&h.push(R),T&&_.push(T),r&&S&&_.push(S),d&&E&&_.push(E);const k=h.length>0?Ms(h):100,M=_.length>0?Ms(_):10,ie=0,N=19.8,V=29.7,Ee=30,ve=(k+M)/2+Ee,L=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*L,q=93.2-(ie+N*Math.log(1+V*g)+D);return Ra(q)},Mv=(c,t=P.AUDIO,n,a,o)=>{const s=ht(o,c,$e.OUTBOUND),r=ht(o,n,$e.OUTBOUND),d=ht(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out/100,T=s[t].delta_rtt_ms_out,S=r&&r[t].delta_rtt_ms_out||null,E=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,R=d&&d[t].delta_jitter_ms_out||null,k=c.data.delta_rtt_connectivity_ms,M=n&&n.data.delta_rtt_connectivity_ms||null,ie=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):k&&h.push(k),S?h.push(S):M&&h.push(M),E?h.push(E):ie&&h.push(ie),A&&_.push(A),r&&C&&_.push(C),d&&R&&_.push(R);const N=h.length>0?Ms(h):100,V=_.length>0?Ms(_):10,Ee=0,ve=19.8,L=29.7,D=30,B=(N+V)/2+D,q=B-177.3<0?0:1,J=.024*B+.11*(B-177.3)*q,Z=93.2-(Ee+ve*Math.log(1+L*g)+J);return Ra(Z)};class Lv{constructor(t,n){this._callbacks={onreport:null,onticket:null},this._id=dv(),this._moduleName=this._id,this._probeId=n,this._config=t,this._exporter=new vv(t),this._state=ys.IDLE,this.registerToPCEvents(),an(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,n,a,o){const s=(h,_)=>h===P.AUDIO?_===Qt.INBOUND_RTP?{...Ah}:{...Ch}:_===Qt.INBOUND_RTP?{...Rh}:{...Ih},r=ov(n);r.pname=this._config.pname,r.call_id=this._config.cid,r.user_id=this._config.uid,r.count=n?n.count+1:1;let d=null;return t.forEach(h=>{!d&&h.timestamp&&(d=h.timestamp),Uv(h,r,r.pname,o).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=r[g.type][g.ssrc];T||(T=s(g.type,h.type),T.ssrc=g.ssrc,r[g.type][g.ssrc]=T),Object.keys(g.value).forEach(S=>{T[S]=g.value[S]})}else Object.keys(g.value).forEach(T=>{r[g.type][T]=g.value[T]})})}),r.timestamp=d,Object.keys(r[P.AUDIO]).forEach(h=>{const _=r[P.AUDIO][h];_.direction===$e.INBOUND?(_.mos_emodel_in=xv(r,P.AUDIO,n,a,_.ssrc),_.mos_in=kv(r,P.AUDIO,n,a,_.ssrc)):(_.mos_emodel_out=Pv(r,P.AUDIO,n,a,_.ssrc),_.mos_out=Mv(r,P.AUDIO,n,a,_.ssrc))}),r}async takeReferenceStats(){return new Promise((t,n)=>{const a=Date.now();setTimeout(async()=>{try{const o=Date.now()-a,s=Date.now(),r=await this._config.pc.getStats(),d=this.analyze(r,null,null,null),h=Date.now();d.experimental.time_to_measure_ms=h-s,d.experimental.time_to_wait_ms=o,this._exporter.saveReferenceReport(d),xe(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(o){n(o)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ys.RUNNING||!this._config.pc)return xe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const t=Date.now(),n=await this._config.pc.getStats(),a=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),o=Date.now();return a.experimental.time_to_measure_ms=o-t,this._exporter.addReport(a),xe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(t){return jn(this._moduleName,`got error ${t}`),null}}async start(){xe(this._moduleName,"starting"),this.state=ys.RUNNING,this._startedTime=this._exporter.start(),xe(this._moduleName,"started")}async mute(){this.state=ys.MUTED,xe(this._moduleName,"muted")}async unmute(){this.state=ys.RUNNING,xe(this._moduleName,"unmuted")}async stop(t){if(xe(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ys.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),xe(this._moduleName,"stopped")}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},xe(this._moduleName,`registered callback '${t}'`)):jn(this._moduleName,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],xe(this._moduleName,`unregistered callback '${t}'`)):jn(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReport(t){this._callbacks.onreport&&Ou(this._callbacks.onreport.callback,this._callbacks.onreport.context,t)}fireOnTicket(t){this._callbacks.onticket&&Ou(this._callbacks.onticket.callback,this._callbacks.onticket.context,t)}updateConfig(t){this._config=t,this._exporter.updateConfig(t)}get state(){return this._state}set state(t){this._state=t,xe(this._moduleName,`state changed to ${t}`)}addCustomEvent(t,n,a,o){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:n,name:a,description:o})}async registerToPCEvents(){const{pc:t}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const n=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${n.length} devices found`,"Media Devices state")}catch{jn(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const a=t.iceConnectionState;a===ri.CONNECTED||a===ri.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ri.DISCONNECTED||a===ri.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ri.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const a=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},t.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},t.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const n=t.getReceivers();if(n&&n.length>0){const a=n[0],{transport:o}=a;if(o){const{iceTransport:s}=o;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class $v{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||hv(),this._moduleName=this._id,an(this._moduleName,"probe created"),this._config=t,this._collector=new Lv(this._config,this._id)}set onreport(t){t?this._collector.registerCallback("onreport",t):this._collector.unregisterCallback("onreport")}set onticket(t){t?this._collector.registerCallback("onticket",t):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(t){this._collector.state=t}addCustomEvent(t,n,a,o=new Date().toJSON()){this._collector.addCustomEvent(o,n,t,a)}get isRunning(){return this._collector.state===ys.RUNNING}get isIdle(){return this._collector.state===ys.IDLE}updateUserId(t){this._config.uid=t,this._collector.updateConfig(this._config)}updateCallId(t){this._config.cid=t,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Aa(this._moduleName,"probe is already running");return}this._collector.start()}stop(t=!1){this.isRunning&&this._collector.stop(t)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const bt="engine ";class Hv{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},an(bt,`configured for probing every ${this._config.refreshEvery}ms`),an(bt,`configured for starting after ${this._config.startAfter}ms`),an(bt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),xe(bt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(t=>t.isRunning)}get isIdle(){return this._probes.every(t=>t.isIdle)}addNewProbe(t,n){if(!t)throw new Error("undefined peer connection");const a=cv(t,n,this._config),o=new $v(a);return this._probes.push(o),xe(bt,`${this._probes.length} probes registered`),o}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===ys.RUNNING&&t.stop(),this._probes=this._probes.filter(n=>t.id!==n.id)}async start(){const t=()=>{this._probes.forEach(s=>s.start())},n=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,o=async()=>{const s=av(),r=this._probes.filter(d=>d.isRunning);for(const d of r){const h=await d.collectStats();h&&s.probes.push(h),xe(bt,`got probe ${d.id}`),await bh(0)}return s.delta_time_to_measure_probes_ms=on(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=on(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=on(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=on(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=on(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=on(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=on(s.probes,"video","total_time_encoded_out"),s};for(xe(bt,"starting to collect"),t(),xe(bt,"generating reference reports..."),await n(),xe(bt,"reference reports generated"),this._startedTime=Date.now();a();)if(xe(bt,`wait ${this._config.refreshEvery}ms before collecting`),await bh(this._config.refreshEvery),a()){xe(bt,"collecting...");const s=Date.now(),r=await o(),d=Date.now();r.delta_time_consumed_to_measure_ms=d-s,this.fireOnReports(r),xe(bt,"collected")}xe(bt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const n=a=>{this._probes.forEach(o=>{o.stop(a)})};an(bt,"stop collecting"),n(t)}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},xe(bt,`registered callback '${t}'`)):jn(bt,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],xe(this._moduleName,`unregistered callback '${t}'`)):jn(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReports(t){this._callbacks.onresult&&t.probes.length>0&&Ou(this._callbacks.onresult.callback,this._callbacks.onresult.context,t)}}const Fv="interface ";class Vv{constructor(t){this._config=fv(t),an(Fv,`welcome to ${this._config.name} version ${this._config.version}`),ZT(this._config.verbose||!1),this._engine=new Hv(this._config)}setupLogLevel(t){ev(t)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(t,n){return this._engine.addNewProbe(t,n)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(t){this._engine.removeExistingProbe(t)}set onresult(t){t?this._engine.registerCallback("onresult",t):this._engine.unregisterCallback("onresult")}}function jv(c,t){return Object.keys(c).filter(n=>t.includes(n)).reduce((n,a)=>{const o=a;return{...n,[o]:c[o]}},{})}const qv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],Bv={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class Gv{constructor(t){this.intervals={},this.analysers={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}async start(t,n,a){n&&n.getTracks().length&&await this.beginCalculation(t,n,a)}stop(t){this.clearVolumeInterval(t),this.analysers[t]&&typeof this.analysers[t].disconnect=="function"&&(this.analysers[t].disconnect(),delete this.analysers[t])}clearVolumeInterval(t){this.intervals[t]&&(clearInterval(this.intervals[t]),delete this.intervals[t])}clearAllIntervals(){Object.keys(this.intervals).forEach(t=>{this.stop(t)}),this.intervals={},this.analysers={}}async beginCalculation(t,n,a){this.clearVolumeInterval(a);const o=t.createAnalyser(),s=t.createMediaStreamSource(n);o.smoothingTimeConstant=.8,o.fftSize=1024,s.connect(o),this.analysers[a]=o,this.intervals[a]=setInterval(()=>{const r=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(r);let d=0;const h=r.length;for(let g=0;g<h;g++)d+=r[g];const _=d/h;this.onChangeFunction(a,_)},this.emitInterval)}}class Wv{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(t=>{throw this.resumePromise=null,t})),await this.resumePromise),this.context}}const Ia={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},Kv=0;class Yv{constructor(t){var n,a;if(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 Wv,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new Gv({onChangeFunction:this.emitVolumeChange.bind(this)}),this.processVADConfiguration(),this.initializeMediaDevices(),["enabled","dynamic"].includes(this.noiseReduction.mode)){const o=(a=(n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)==null?void 0:a.vadModule;o&&o.MicVAD?(this.MicVAD=o.MicVAD,console.log("✅ VAD module loaded successfully")):(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(){var n;const t=((n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)||{};this.noiseReduction={mode:t.mode||"disabled",checkEveryMs:t.checkEveryMs||500,noiseCheckInterval:t.noiseCheckInterval||2e3,noiseThreshold:t.noiseThreshold||.004,vadConfig:t.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(t){this.currentActiveRoomIdValue=t,this.context.emit("currentActiveRoomChanged",t)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(t){this.isCallAddingInProgress=t,this.context.emit("callAddingInProgressChanged",t)}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(a=>!a.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audiooutput")}get getUserMediaConstraints(){return vh()?{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(t){this.availableMediaDevices=t,this.context.emit("changeAvailableDeviceList",t)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}async initializeMediaDevices(){const t=localStorage.getItem(Ia.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(Ia.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),o=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(o),await this.setMicrophone(t),await this.setSpeaker(n),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),a.getTracks().forEach(s=>s.stop())}catch(a){console.error(a)}}async cleanupConferenceNodes(t){const n=this.conferenceNodes[t];if(!n)return;let a=0;n.sources.forEach((r,d)=>{try{r.disconnect(),a++}catch(h){console.error(`[cleanupConferenceNodes] Error disconnecting source ${d}:`,h)}});let o=0;n.destinations.forEach((r,d)=>{try{r.disconnect(),o++}catch(h){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${d}:`,h)}});let s=0;n.gains.forEach((r,d)=>{try{r.disconnect(),s++}catch(h){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${d}:`,h)}}),delete this.conferenceNodes[t]}setCallTime(t){const n={...t};delete n.callId,this.callTime={...this.callTime,[t.callId]:n},this.context.emit("changeCallTime",this.callTime)}removeCallTime(t){const n={...this.callTime};delete n[t],this.callTime={...n},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(t,n){this.timeIntervals={...this.timeIntervals,[t]:n}}removeTimeInterval(t){const n={...this.timeIntervals};n[t]&&(clearInterval(n[t]),delete n[t],this.timeIntervals={...n})}stopCallTimer(t){this.removeTimeInterval(t),this.removeCallTime(t)}emitVolumeChange(t,n){this.context.emit("changeCallVolume",{callId:t,volume:n})}setMetricsConfig(t){this.metricConfig={...this.metricConfig,...t}}sendDTMF(t,n){if(!/^[A-D0-9*#]+$/g.test(n))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[t].sendDTMF(n)}setIsMuted(t){this.muted=t,this.context.emit("changeIsMuted",t)}processMute(t){const n=this.currentActiveRoomId;this.setIsMuted(t),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!t),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:n,automatic:a}){const o=this.extendedCalls[t];if(!o)return;o._automaticHold=a??!1;const s=new Promise((r,d)=>{const h=setTimeout(()=>{d(new Error("Hold operation timeout"))},5e3),_=()=>{clearTimeout(h),o.putOnHoldTimestamp=n?Date.now():void 0,r()},g=T=>{clearTimeout(h),d(T)};try{n?(this.stopSessionVad(o._id),o.hold({},_)):o.unhold({},_)}catch(T){g(T)}});try{await s,this.updateCall(o);const r=Object.values(this.extendedCalls).filter(d=>d.roomId===o.roomId&&(n?t!==d._id:!0));r.length>1&&await this.doConference(r)}catch(r){throw console.error("Hold operation failed:",r),r}}holdCall(t,n=!1){return this.processHold({callId:t,automatic:n,toHold:!0})}unholdCall(t){return this.processHold({callId:t,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(t=>t.direction==="outgoing"&&t.status===Kv).forEach(t=>this.terminateCall(t._id))}answerCall(t){const n=this.extendedCalls[t];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setActiveRoom(n.roomId),n.connection.addEventListener("track",a=>{this.triggerAddStream(a,n)})}async moveCall(t,n){this.updateCallStatus({callId:t,isMoving:!0}),await this.processRoomChange({callId:t,roomId:n}),this.updateCallStatus({callId:t,isMoving:!1})}updateCall(t){this.activeCalls[t._id]=gh(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const a={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...a}},this.context.emit("updateRoom",{room:a,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const n=/answer-after=0/,o=t.request.getHeader("Call-Info");return o&&n.test(o)}addCall(t,n=!0){this.activeCalls={...this.activeCalls,[t._id]:gh(t)},this.extendedCalls[t._id]=t,n&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(t){this.callStatus={...this.callStatus,[t]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(t){const a={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(a.isMoving=t.isMoving),t.isTransferring!==void 0&&(a.isTransferring=t.isTransferring),t.isMerging!==void 0&&(a.isMerging=t.isMerging),t.isTransferred!==void 0&&(a.isTransferred=t.isTransferred),this.callStatus={...this.callStatus,[t.callId]:{...a}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(t){const n={...this.callStatus};delete n[t],this.callStatus={...n},this.context.emit("changeCallStatus",this.callStatus)}addRoom(t){this.activeRooms={...this.activeRooms,[t.roomId]:t},this.context.emit("addRoom",{room:t,roomList:this.activeRooms})}async setupActiveStream(){const t=await Au(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);t.getTracks().forEach(n=>n.enabled=!this.isMuted),await this.setActiveStream(t)}async getActiveStream(){const t=await Au(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return t.getTracks().forEach(n=>n.enabled=!this.isMuted),await this.setActiveStream(t),t}async setMicrophone(t){if(!this.getInputDeviceList.find(({deviceId:a})=>a===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async a=>{await this.setupActiveStream();const o=this.activeStream;a.connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.updateCall(a)}):await this.doConference(n)}async setActiveStream(t){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(t,"origin"),this.activeStreamValue=t,this.context.emit("changeActiveStream",t)}async setSpeaker(t){if(!this.getOutputDeviceList.find(({deviceId:o})=>o===t))return;this.setSelectedOutputDevice(t);const n=Object.values(this.extendedCalls);if(n.length===0)return;const a=n.filter(o=>o.roomId===this.currentActiveRoomId);a.length===1?n.forEach(o=>{var s;(s=o.audioTag)==null||s.setSinkId(t),this.updateCall(o)}):await this.doConference(a)}removeRoom(t){const n={...this.activeRooms},a={...n[t]};delete n[t],this.activeRooms={...n},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(t){t!==void 0&&Object.values(this.extendedCalls).filter(n=>n.roomId===t).length===0&&(this.removeRoom(t),this.currentActiveRoomId===t&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(t){this.muted?t.mute({audio:!0}):t.unmute({audio:!0})}startNoiseMonitor({sessionId:t,stream:n,onNoiseDetected:a,onNoiseStop:o}){const s=new AudioContext,r=s.createMediaStreamSource(n.clone()),d=s.createAnalyser();d.fftSize=1024;const h=new Float32Array(d.fftSize);r.connect(d);const _=[];this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),this.vadIntervals[t]=null),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),this.vadMrsIntervals[t]=null),this.vadMrsIntervals[t]=setInterval(()=>{d.getFloatTimeDomainData(h);const g=YT(h);_.push(g);const T=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);_.length>T&&_.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[t]=setInterval(()=>{if(_.length===0)return;const g=_.reduce((E,A)=>E+A,0)/_.length,T=this.vadSessionsState[t],S=g>this.noiseReduction.noiseThreshold;T.isSpeaking||(S&&T.currentMode==="clean"?(T.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!0}),a()):!S&&T.currentMode==="noisy"&&(T.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!1}),o()))},this.noiseReduction.noiseCheckInterval)}async processVAD(t,n){const a=n.clone();this.stopSessionVad(t._id),this.vadSessionsState[t._id]={currentMode:"clean",isSpeaking:!1};const o=await this.managedAudioContext.getContext(),s=await JT(a,o,150);let r=!1;const d=await this.MicVAD.new({getStream:()=>new Promise(h=>h(a)),...Bv,...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(!r){if(r=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){t.connection.getSenders()[0]&&t.connection.getSenders()[0].replaceTrack(s.stream.getAudioTracks()[0]);return}this.startNoiseMonitor({sessionId:t._id,stream:a,onNoiseDetected:async()=>{var h;console.log("Replace track with Vad Controlled"),await((h=t.connection.getSenders()[0])==null?void 0:h.replaceTrack(s.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const h=t.connection.getSenders()[0];h&&h.track&&h.transport&&h.transport.state!=="closed"&&h.transport.state!=="failed"&&(console.log("Replace track with Original"),await h.replaceTrack(a.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var h;console.log("🎤 Speech started"),s.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((h=t.connection.getSenders()[0])==null||h.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!0},onSpeechEnd:()=>{var h;console.log("🛑 Speech end"),s.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((h=t.connection.getSenders()[0])==null||h.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!1}});this.vadSessions[t._id]&&(this.vadSessions[t._id].pause(),delete this.vadSessions[t._id]),this.vadSessions[t._id]=d,d.start()}stopSessionVad(t){this.vadSessions[t]&&(this.vadSessions[t].pause(),delete this.vadSessions[t]),this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),delete this.vadIntervals[t]),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),delete this.vadMrsIntervals[t]),this.vadSessionsState[t]&&delete this.vadSessionsState[t]}async roomReconfigure(t){var o;if(t===void 0)return;const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t),a=this.currentActiveRoomId===t;if(n.forEach((s,r)=>{if(s.audioTag){s.connection.getReceivers().forEach(h=>{h.track.enabled=!s.localMuted}),a&&this.muteReconfigure(s);const d=!a;s.audioTag.muted=d,this.updateCall(s)}}),n.length===0){!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t),this.deleteRoomIfEmpty(t);return}if(n.length===1&&!a){const s=n[0];s.isOnHold().local||await this.holdCall(s._id,!0),!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}if(n.length===1&&a){const s=n[0];s.isOnHold().local&&s._automaticHold&&await this.unholdCall(s._id);const h=(((o=s.connection)==null?void 0:o.getSenders())||[])[0];if(s.connection&&h)try{await this.setupActiveStream();const g=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(n[0],g);const T=g.getTracks();await h.replaceTrack(T[0]),this.muteReconfigure(s)}catch(g){console.error(g)}!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}n.length>1&&await this.doConference(n)}async doConference(t){if(t.length===0)return;const n=t[0].roomId,a=this.currentActiveRoomId===n;if(t.find(h=>h.roomId!==n))return;const s=await this.managedAudioContext.getContext();if(s.state!=="running"){console.error(`[doConference] ERROR: AudioContext is not running! State: ${s.state}`);return}await this.cleanupConferenceNodes(n),this.conferenceNodes[n]={sources:new Map,destinations:new Map,gains:new Map};const r=this.conferenceNodes[n],d=new Map;t.forEach((h,_)=>{h&&h.connection&&h.connection.getReceivers().forEach((T,S)=>{var C,R,k;T.track.enabled=!h.localMuted;const E=(C=T.track)==null?void 0:C.id;(R=T.track)==null||R.readyState,(k=T.track)==null||k.kind;const A=`${h._id}-${E}`;T.track&&T.track.readyState==="live"&&d.set(A,T.track)})}),await this.setupActiveStream(),await zT.forEach(t,async(h,_)=>{if(!h||!h.connection)return;const g=s.createMediaStreamDestination();r.destinations.set(h._id,g);let T=0;if(d.forEach((C,R)=>{if(!R.startsWith(h._id))try{const k=s.createMediaStreamSource(new MediaStream([C])),M=s.createGain(),ie=`${h._id}-${R}`;k.connect(M),M.connect(g),r.sources.set(ie,k),r.gains.set(ie,M),T++}catch(k){console.error(k)}}),a&&this.activeStreamValue)try{const C=this.activeStream,R=s.createMediaStreamSource(C),k=s.createGain(),M=`${h._id}-local`;R.connect(k),k.connect(g),r.sources.set(M,R),r.gains.set(M,k)}catch(C){console.error(C)}else a&&console.error(`Host room but no activeStreamValue - skipping host microphone for session ${h._id}`);const E=h.connection.getSenders()[0],A=g.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(h,g.stream),E&&A[0])try{await E.replaceTrack(A[0]),this.muteReconfigure(h)}catch(C){console.error(C)}})}processCallerMute(t,n){const a=this.extendedCalls[t];a&&a.connection.getReceivers().length&&(a.localMuted=n,a.connection.getReceivers().forEach(o=>{o.track.enabled=!n}),this.updateCall(a))}muteCaller(t){this.processCallerMute(t,!0)}unmuteCaller(t){this.processCallerMute(t,!1)}terminateCall(t){const n=this.extendedCalls[t];n._status===4?n.terminate({status_code:603,reason_phrase:"Decline"}):n._status!==8&&n.terminate()}transferCall(t,n){if(n.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[t];if(!a._is_confirmed&&!a._is_canceled){const o=`sip:${n}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${o}`]});return}this.updateCallStatus({callId:t,isTransferring:!0,isTransferred:!1}),a.refer(`sip:${n}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(a)}mergeCall(t){const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(n.length!==2)return;const a=n[0],o=n[1];!a||!o||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:o._id,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a))}mergeCallByIds(t,n){const a=Object.values(this.extendedCalls).find(s=>s._id===t),o=Object.values(this.extendedCalls).find(s=>s._id===n);if(!a||!o)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:n,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a)}setDND(t){this.isDNDEnabled=t,this.context.emit("changeIsDND",t)}setCallWaiting(t){this.isCallWaitingEnabled=t,this.context.emit("changeIsCallWaiting",t)}startCallTimer(t){this.removeTimeInterval(t);const n={callId:t,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(n);const a=setInterval(()=>{const o={...this.callTime[t]},s=KT(o);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,a)}async setActiveRoom(t){const n=this.currentActiveRoomId;t!==n&&(this.currentActiveRoomId=t,await this.roomReconfigure(n),await this.roomReconfigure(t))}getNewRoomId(){const t=Object.keys(this.activeRooms);return t.length===0?1:parseInt(t.sort()[t.length-1])+1}async setupCall(t){var _,g;const n=t.session;if(this.getActiveCalls[n.id]!==void 0)return;const o=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:o};if(n.direction==="incoming")this.context.logger.log("New incoming call from",(g=(_=n._remote_identity)==null?void 0:_._uri)==null?void 0:g._user),s.incomingInProgress=!0,this.context.subscribe(Xt.CALL_CONFIRMED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.startCallTimer(n.id))}),this.context.subscribe(Xt.CALL_FAILED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.deleteRoomIfEmpty(o))});else if(n.direction==="outgoing"){const T=S=>{S.response&&S.response.status_code===XT.SESSION_PROGRESS&&(this.startCallTimer(n.id),n.off("progress",T))};n.on("progress",T),n.once("confirmed",()=>{this.startCallTimer(n.id)})}const r=n,d=this.hasAutoAnswerHeaders(t),h=r.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);r.roomId=o,r.localMuted=!1,r.autoAnswer=h,h?this.addCall(r,!1):this.addCall(r),this.addCallStatus(n.id),this.addRoom(s),h&&this.answerCall(r._id)}removeCall(t){const n={...this.activeCalls};delete n[t],this.activeCalls={...n};const a={...this.extendedCalls};delete a[t],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(t){const n=this.extendedCalls[t._id];if(!n)return;this.stopVUMeter("origin"),this.stopVUMeter(t._id);const a=n.roomId;this.removeCall(t._id),this.roomReconfigure(a).then(()=>{}).catch(o=>{console.error("Error reconfiguring room after call removal:",o)})}shouldTerminateNewSession(t){if(t.session.direction==="outgoing")return!1;const a=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||a}async newRTCSessionCallback(t){const n=t.session;if(this.shouldTerminateNewSession(t)){n.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Xt.NEW_CALL,session:n,event:t}),n.on("ended",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session ended for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:n,event:a}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(n._id);const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("progress",a=>{var o,s;this.context.logger.log("Session in progress for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:n,event:a})}),n.on("failed",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session failed for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:n,event:a}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(n._id),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("confirmed",a=>{var o,s;this.context.logger.log("Session confirmed for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(t),n.direction==="outgoing"){const a=this.getActiveCalls[n.id].roomId;await this.setActiveRoom(a)}}setMuteWhenJoin(t){this.muteWhenJoinEnabled=t,this.context.emit("changeMuteWhenJoin",t)}setMicrophoneSensitivity(t){if(t<0||t>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=t,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(t){this.speakerVolumeValue=t,Object.values(this.extendedCalls).forEach(n=>{n.audioTag&&(n.audioTag.volume=t,this.updateCall(n))})}setAutoAnswer(t){this.isAutoAnswer=t}setSelectedInputDevice(t){localStorage.setItem(Ia.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(Ia.SELECTED_OUTPUT_DEVICE,t),this.selectedMediaDevices.output=t,this.context.emit("changeActiveOutputMediaDevice",t)}setCallMetrics(t){const n={...t};delete n.callId,this.callMetrics={...this.callMetrics,[t.callId]:n},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(t){const n={...this.callMetrics};delete n[t],this.callMetrics={...n},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(t){const n=new Vv(this.metricConfig),a=n.createProbe(t.connection,{cid:t._id}),o=[];let s;a.onreport=r=>{Object.entries(r.audio).forEach(([_,g])=>{g.direction==="inbound"&&!o.includes(_)&&(o.push(_),s=_)});const d=r.audio[s];if(!d)return;const h=jv(d,qv);h.callId=t._id,this.setCallMetrics(h)},this.context.subscribe(Xt.CALL_ENDED,r=>{r._id===t._id&&n.stopAllProbes()}),n.startAllProbes()}async setupVUMeter(t,n){await this.VUMeter.start(await this.managedAudioContext.getContext(),t,n)}stopVUMeter(t){this.VUMeter.stop(t)}async setupStream(){try{const t=Date.now(),n=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((o,s)=>{o.stop()}),this.initialStreamValue=null),this.initialStreamValue=n}catch(t){throw t}}async triggerAddStream(t,n){const a=this.muteWhenJoin||this.isMuted;this.setIsMuted(a),this.initialStreamValue||await this.setupStream();const o=await this.managedAudioContext.getContext(),s=await Au(o,this.initialStreamValue,this.microphoneInputLevel*2),r=this.isMuted||this.muteWhenJoin;s.getTracks().forEach(S=>{S.enabled=!r}),await this.setActiveStream(s),await n.connection.getSenders()[0].replaceTrack(s.getTracks()[0]);const _=new MediaStream([t.track]);!Object.values(this.extendedCalls).find(S=>S.audioTag&&S.audioTag.id===n._id)&&UT(_,n,this.selectedOutputDevice,this.speakerVolume);const T=n.roomId===this.currentActiveRoomId;n.audioTag&&(n.audioTag.muted=!T),await this.setupVUMeter(_,n._id),this.getCallQuality(n),this.updateCall(n),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(n,s)}initCall(t,n,a=!1){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${t}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=o.id,n&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),a)){const s=Object.values(this.extendedCalls).filter(r=>r.roomId===this.currentActiveRoomId&&r._id!==o.id);for(const r of s)this.holdCall(r._id,!0)}o.connection.addEventListener("track",s=>{this.triggerAddStream(s,o)})}async processRoomChange({callId:t,roomId:n}){const a=this.extendedCalls[t];if(!a)return;const o=a.roomId;a.roomId=n,this.updateCall(a),await this.roomReconfigure(o),await this.roomReconfigure(n)}}class Jv{constructor(t){this.context=t}get sipOptions(){return{...this.context.options.sipOptions}}initCall(t,n){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${t}@${this.context.sipDomain}`,n,this.sipOptions)}stop(t={}){this.context.terminateJanusSessions(t)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(t){this.context.changeMediaConstraints(t)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class zv{constructor(t){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=t,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(t){const n=this.extendedMessages[t];this.updateMSRPSession(n)}updateMSRPSession(t){this.activeMessages[t._id]=Th(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:Th(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,n){const a=this.msrpHistory[n.id]||[];a.push(t),this.msrpHistory={...this.msrpHistory,[n.id]:[...a]},this.context.emit("newMSRPMessage",{message:t,session:n})}messageTerminate(t){const n=this.extendedMessages[t];n._status!==8&&n.terminate()}addMessageSession(t){if(!t._id||this.getActiveMessages[t._id]!==void 0)return;const a=t;this.addMMSRPSession(a)}triggerMSRPListener({listenerType:t,session:n,event:a}){const o=this.context.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}removeMMSRPSession(t){const n={...this.activeMessages};delete n[t],this.activeMessages={...n};const a={...this.extendedMessages};delete a[t],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(t){this.removeMMSRPSession(t._id)}newMSRPSessionCallback(t){t.session._id||(t.session._id=t.request.call_id+t.request.from._parameters.tag);const n=t.session;n.on("ended",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("failed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateMSRPSession(n)}),n.on("newMessage",a=>{this.addMSRPMessage(a,n)}),this.addMessageSession(n)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,n,a){if(t.length===0)return console.error("Target must be a valid string");const o=this.context.startMSRP(t,a);o.on("active",()=>{this.addMessageSession(o),o.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,n){const a=this.extendedMessages[t];if(!a)throw new Error(`MSRP session with id ${t} doesn't exist!`);a.sendMSRP(n)}}const ba={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Ph{constructor(t){this.opensips=null,this.session=null,this.name=null,this.name=t}setOpensips(t){this.opensips=t}setSession(t){this.session=t}kill(){this.opensips.kill(this.name)}}class kh extends Ph{constructor(t,n){super(t),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=n}connect(t={}){this.opaqueId=this.session.generateOpaqueId();const n=Pe.cloneArray(t.extraHeaders),a={from_tag:this.session._from_tag};t.fromUserName&&(a.from_uri=new ln("sip",t.fromUserName,this.session._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(a.from_display_name=t.fromDisplayName),n.push(`Contact: ${this.session._contact}`),n.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&n.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Tt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,n),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 t;this._connection.onicecandidate=n=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||n.candidate&&(this._candidates.push(n.candidate),clearTimeout(t),t=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(t){t.forEach(n=>{this._connection.addTrack(n)})}async _sendInitialRequest(){const t=new Wr(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const n={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(n),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},o=JSON.stringify(a);this._request.body=o,t.send()}_receiveInviteResponse(t){if(this._publisherSubscribeSent||!t.body)return;const n=JSON.parse(t.body);this.handleId=n.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},o=[this.session.getPTypeHeader(Pt.PUBLISHER)];this.session.sendRequest(H.SUBSCRIBE,{extraHeaders:o,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async s=>{var r,d,h,_;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((d=(r=g.plugindata)==null?void 0:r.data)==null?void 0:d.videoroom)==="joined"&&this.session.myFeedList.push(g.plugindata.data.id),(_=(h=g.plugindata)==null?void 0:h.data)!=null&&_.publishers&&this.session.receivePublishers(g)}catch(g){console.error(g)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(t){const n=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handleId,session_id:this.session.session_id})),o={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...t},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...n]},s=["Content-Type: application/json",this.session.getPTypeHeader(Pt.ICE)];this.session.sendRequest(H.INFO,{extraHeaders:s,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async r=>{this._configureSent=!0;const h=r.data.split(`\r
|
|
158
|
+
`,n),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?n=o+2:a=o}return a}function ET(c,t,n,a){let o;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),d=t.substring(s+1,a).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",d),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",d),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",d),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=yu.parse(d,"Record_Route"),o===-1)o=void 0;else for(const h of o)c.addHeader("record-route",d.substring(h.possition,h.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=h.parsed;break;case"call-id":case"i":c.setHeader("call-id",d),o=c.parseHeader("call-id"),o&&(c.call_id=d);break;case"contact":case"m":if(o=yu.parse(d,"Contact"),o===-1)o=void 0;else for(const h of o)c.addHeader("contact",d.substring(h.possition,h.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=h.parsed;break;case"content-length":case"l":c.setHeader("content-length",d),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",d),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",d),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof Ln.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",d),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",d),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",d),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",d),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",d),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",d),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",d),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(r,d),o=0}return o===void 0?{error:`error parsing header "${r}"`}:!0}const yT={parseMessage:vT},si=new na("Registrator"),ya=10;class AT{constructor(t,n){this._reg_id=1,this._ua=t,this._transport=n,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=vs.createRandomToken(22),this._cseq=0,this._to_uri=t.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 o=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=o}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){si.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),t.push(`Expires: ${this._expires}`);const n=new Tt.OutgoingRequest(H.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),a=new Wr(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,H.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,H.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:o=>{if(o.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):{if(this._registering=!1,!o.hasHeader("Contact")){si.debug("no Contact header in response to REGISTER, response ignored");break}const s=o.headers.Contact.reduce((_,g)=>_.concat(g.parsed),[]);let r=s.find(_=>this._sipInstance===_.getParam("+sip.instance")&&this._reg_id===parseInt(_.getParam("reg-id")));if(r||(r=s.find(_=>_.uri.user===this._ua.contact.uri.user)),!r){si.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let d=r.getParam("expires");!d&&o.hasHeader("expires")&&(d=o.getHeader("expires")),d||(d=this._expires),d=Number(d),d<ya&&(d=ya);const h=d>64?d*1e3/2+Math.floor((d/2-32)*1e3*Math.random()):d*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},h),r.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=r.getParam("temp-gruu").replace(/"/g,"")),r.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=r.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:o}));break}case/^423$/.test(o.status_code):{o.hasHeader("min-expires")?(this._expires=Number(o.getHeader("min-expires")),this._expires<ya&&(this._expires=ya),this.register()):(si.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(o,H.causes.SIP_FAILURE_CODE));break}default:{const s=vs.sipErrorCause(o.status_code);this._registrationFailure(o,s)}}}});this._registering=!0,a.send()}unregister(t={}){if(!this._registered){si.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();t.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),n.push("Expires: 0");const a=new Tt.OutgoingRequest(H.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new Wr(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,H.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,H.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const r=vs.sipErrorCause(s.status_code);this._unregistered(s,r)}}}}).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(t,n){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:n}))}_unregistered(t,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:n||null})}}const et=console,ks={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},CT=cT;class RT extends CT{constructor(t){super(t),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 AT(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(t,n){return super.call(t,n)}joinVideoCall(t,n,a){et.debug("call()");const o=new Sa(this);return o.configureMedia({audio:!0,video:!0}),o.connect(t,n,a),o}startScreenShare(){et.debug("startScreenShare()");for(const t in this._janus_sessions)this._janus_sessions[t].connectScreenShare()}changeMediaConstraints(t){for(const n in this._janus_sessions)this._janus_sessions[n].changeMediaConstraints(t)}startBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].connectBlur()}stopBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].stopBlur()}_loadConfig(t){try{ti.load(this._configuration,t)}catch(s){throw s}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=vs.newUUID());let n;typeof window<"u"&&typeof window.document<"u"?n=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(n=self.navigator.userAgent),n+=" "+De.USER_AGENT,this._configuration.user_agent=t.overrideUserAgent&&typeof t.overrideUserAgent=="function"?t.overrideUserAgent(n):n,t.onTransportCallback&&typeof t.onTransportCallback=="function"&&(this.onTransportCallback=t.onTransportCallback),this._configuration.jssip_id=vs.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new Mg(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=IT.bind(this),this._transport.onconnect=bT.bind(this),this._transport.ondisconnect=wT.bind(this),this._transport.ondata=OT.bind(this)}catch(s){throw et.warn(s),new Ns.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 s=this._configuration.uri.clone();s.user=null,s.clearParams(),s.clearHeaders(),this._configuration.registrar_server=s}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ln("sip",vs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(s={}){const r=s.anonymous||null,d=s.outbound||null;let h="<";return r?h+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":h+=this.pub_gruu||this.uri.toString(),d&&(r?!this.temp_gruu:!this.pub_gruu)&&(h+=";ob"),h+=">",h}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(o.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));et.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(ti.settings,s))switch(s){case"uri":case"registrar_server":et.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":et.debug(`- ${s}: NOT SHOWN`);break;default:et.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,n){t.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",n)}newJanusSession(t,n){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(a=>{a.setSession(t)}),this.processStreamPlugins.forEach(a=>{a.setSession(t)}),this.emit("newJanusSession",n)}kill(){}destroyMSRPSession(t){delete this._msrp_sessions[t.id]}destroyJanusSession(t){delete this._janus_sessions[t.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(t){var s,r,d,h;const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){et.debug("Request-URI does not point to us"),t.method!==De.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===De.SIPS){t.reply_sl(416);return}if(Ht.checkTransaction(this,t))return;if(n===De.INVITE?new Ht.InviteServerTransaction(this,this._transport,t):n!==De.ACK&&n!==De.CANCEL&&new Ht.NonInviteServerTransaction(this,this._transport,t),n===De.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const g=Date.now(),T=this.lastOptionsTimestamp>g-35e3,S=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>g;T&&S&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){t.reply(200);return}new yf.Options(this).init_incoming(t)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new yf.Message(this).init_incoming(t)}else if(n===De.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let a,o;if(t.to_tag)if(a=this._findDialog(t.call_id,t.from_tag,t.to_tag),a)a.receiveRequest(t);else if(n===De.NOTIFY)if(o=this._findSession(t),o)o.receiveRequest(t);else{if(t.body)try{const _=JSON.parse(t.body)||{};(r=(s=_.plugindata)==null?void 0:s.data)!=null&&r.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(_),(h=(d=_.plugindata)==null?void 0:d.data)!=null&&h.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(_.plugindata.data.unpublished)}catch(_){console.error(_)}t.reply(200)}else n!==De.ACK&&t.reply(481);else switch(n){case De.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const _=t.replaces;a=this._findDialog(_.call_id,_.from_tag,_.to_tag),a?(o=a.owner,o.isEnded()?t.reply(603):o.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(o=new Eu(this),o.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(o=new Sg(this),o.init_incoming(t));else et.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case De.BYE:t.reply(481);break;case De.CANCEL:o=this._findSession(t),o?o.receiveRequest(t):et.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}startMSRP(t,n){et.debug("startMSRP()",n);const a=new Eu(this);return a.connect(t),a}startJanus(t,n){et.debug("startJanus()",n);const a=new Eu(this);return a.connect(t),a}terminateMSRPSessions(t){et.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(t)}terminateJanusSessions(t){et.debug("terminateSessions()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||this._janus_sessions[n].terminate(t)}enableJanusAudio(t){et.debug("enableJanusAudio()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startAudio():this._janus_sessions[n].stopAudio())}enableJanusVideo(t){et.debug("enableJanusVideo()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startVideo():this._janus_sessions[n].stopVideo())}terminateAllSessions(){for(const t in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,t)){et.debug(`closing session ${t}`);try{this._sessions[t].terminate()}catch(n){console.error(n)}}}stop(t=!0){if(et.debug("stop()"),this._dynConfiguration={},this._status===ks.STATUS_USER_CLOSED){et.debug("UA already closed");return}this._registrator.close();const n=Object.keys(this._sessions).length;t&&this.terminateAllSessions();for(const o in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,o)){et.debug(`closing session ${o}`);try{this._msrp_sessions[o].terminate()}catch(s){console.error(s)}}for(const o in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,o)){et.debug(`closing session ${o}`);try{this._janus_sessions[o].terminate()}catch(s){console.error(s)}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch(s){console.error(s)}this._status=ks.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&&n===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function IT(c){this.emit("connecting",c)}function bT(c){this._status!==ks.STATUS_USER_CLOSED&&(this._status=ks.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function wT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const a in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],a)&&this._transactions[n][a].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==ks.STATUS_USER_CLOSED&&(this._status=ks.STATUS_NOT_READY,this._error=ks.NETWORK_ERROR)}function OT(c){const t=c.transport;let n=c.message;const a=n;if(n=yT.parseMessage(n,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(n,a),!!n&&!(this._status===ks.STATUS_USER_CLOSED&&n instanceof Ln.IncomingRequest)&&Xg(n,this,t)){if(n instanceof Ln.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Ln.IncomingResponse){let o;switch(n.method){case De.INVITE:o=this._transactions.ict[n.via_branch],o&&o.receiveResponse(n);break;case De.ACK:break;default:o=this._transactions.nict[n.via_branch],o&&o.receiveResponse(n);break}}}}const DT=["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"],NT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function gh(c){const t={};return DT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t.localHold=c._localHold,t}function Th(c){const t={};return NT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t}async function Au(c,t,n){const a=c.createMediaStreamSource(t),o=c.createMediaStreamDestination(),s=c.createGain();return a.connect(s),s.connect(o),s.gain.value=n,o.stream}function UT(c,t,n,a){if(vh())return;const o=document.createElement("audio");o.id=t._id,o.className="audioTag",o.srcObject=c,o.setSinkId(n),o.volume=a,o.play(),t.audioTag=o}function xT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function vh(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const PT=at,kT=Yt(),Ot=new PT("WebSocketInterface");var MT=class{constructor(t){Ot.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=kT.parse(t,"absoluteURI");if(n===-1)throw Ot.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Ot.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${t}`);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(t){this._via_transport=t.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Ot.debug("connect()"),this.isConnected()){Ot.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Ot.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Ot.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(t){this._onError(t)}}disconnect(){Ot.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(t){return Ot.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Ot.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(){Ot.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:n,reason:a}){Ot.debug(`WebSocket ${this._url} closed`),t===!1&&Ot.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,n,a)}_onMessage({data:t}){Ot.debug("received WebSocket message"),this.ondata(t)}_onError(t){Ot.warn(`WebSocket ${this._url} error: `,t)}};const Cu=Tl,LT=De,$T=Ts,HT=mt(),FT=_h,VT=ps(),jT=qo(),qT=Yt(),BT=MT;Nn("JsSIP")("version %s",Cu.version);var GT={C:LT,Exceptions:$T,Utils:HT,UA:FT,URI:VT,NameAddrHeader:jT,WebSocketInterface:BT,Grammar:qT,debug:Nn,get name(){return Cu.title},get version(){return Cu.version}};const WT=Me(GT);function Ru(c){return c<10?`0${c}`:`${c}`}function KT(c){let t=c.hours||0,n=c.minutes||0,a=c.seconds||0;a++,a===60&&(a=0,n++,n===60&&(n=0,t++));const o=`${Ru(t)}:${Ru(n)}:${Ru(a)}`;return{seconds:a,minutes:n,hours:t,formatted:o}}function YT(c){let t=0;for(let n=0;n<c.length;n++)t+=c[n]*c[n];return Math.sqrt(t/c.length)}async function JT(c,t,n=150){const a=t.createMediaStreamSource(c),o=t.createDelay();o.delayTime.value=n/1e3;const s=t.createGain();s.gain.value=0;const r=t.createMediaStreamDestination();return a.connect(o).connect(s).connect(r),{stream:r.stream,setSpeaking:d=>{s.gain.value=d?1:0}}}var yt={};yt.forEach=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)if(o in c){const s=Promise.resolve(c[o]).then(r=>t.call(n||globalThis,r,o,c));a.push(s)}await Promise.all(a)},yt.forEachSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)a in c&&await t.call(n||globalThis,await c[a],a,c)},yt.map=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=Promise.resolve(c[o]).then(s=>t.call(n||globalThis,s,o,c)));return Promise.all(a)},yt.mapSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=await t.call(n||globalThis,await c[o],o,c));return a},yt.find=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a();let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(c[r]):s===c.length&&a(),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.findSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return c[a]},yt.findIndex=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(-1);let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(r):s===c.length&&a(-1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.findIndexSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return a},yt.some=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!1);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?a(!0):s===c.length&&a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.someSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&await t.call(n||globalThis,await c[a],a,c))return!0;return!1},yt.every=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!0);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?s===c.length&&a(!0):a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.everySeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&!await t.call(n||globalThis,await c[a],a,c))return!1;return!0},yt.filter=(c,t,n)=>new Promise(async(a,o)=>{const s=[];for(let d=0;d<c.length;d++)d in c&&(s[d]=Promise.resolve(c[d]).then(h=>t.call(n||globalThis,h,d,c)).catch(o));const r=[];for(let d=0;d<s.length;d++)await s[d]&&r.push(await c[d]);a(r)}),yt.filterSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&await t.call(n||globalThis,await c[o],o,c)&&a.push(await c[o]);return a},yt.reduce=async(c,t,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let a,o;for(n!==void 0?(o=n,a=0):(o=c[0],a=1),a;a<c.length;a++)a in c&&(o=await t(await o,await c[a],a,c));return o};var Sh={};(function(c){const t=yt;Object.keys(t).forEach(n=>{const a=n.charAt(0).toUpperCase()+n.slice(1);c[`async${a}`]=async function(...o){return t[n](this,...o)}})})(Sh);var zT=Object.assign(yt,{instanceMethods:Sh});const Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},XT={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 QT={exports:{}};(function(c){var t=function(n){var a=Object.prototype,o=a.hasOwnProperty,s=Object.defineProperty||function(ee,Y,G){ee[Y]=G.value},r,d=typeof Symbol=="function"?Symbol:{},h=d.iterator||"@@iterator",_=d.asyncIterator||"@@asyncIterator",g=d.toStringTag||"@@toStringTag";function T(ee,Y,G){return Object.defineProperty(ee,Y,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[Y]}try{T({},"")}catch{T=function(Y,G,re){return Y[G]=re}}function S(ee,Y,G,re){var ge=Y&&Y.prototype instanceof ie?Y:ie,be=Object.create(ge.prototype),ke=new x(re||[]);return s(be,"_invoke",{value:J(ee,G,ke)}),be}n.wrap=S;function E(ee,Y,G){try{return{type:"normal",arg:ee.call(Y,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",C="suspendedYield",R="executing",k="completed",M={};function ie(){}function N(){}function V(){}var Ee={};T(Ee,h,function(){return this});var ve=Object.getPrototypeOf,L=ve&&ve(ve(se([])));L&&L!==a&&o.call(L,h)&&(Ee=L);var D=V.prototype=ie.prototype=Object.create(Ee);N.prototype=V,s(D,"constructor",{value:V,configurable:!0}),s(V,"constructor",{value:N,configurable:!0}),N.displayName=T(V,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(Y){T(ee,Y,function(G){return this._invoke(Y,G)})})}n.isGeneratorFunction=function(ee){var Y=typeof ee=="function"&&ee.constructor;return Y?Y===N||(Y.displayName||Y.name)==="GeneratorFunction":!1},n.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,V):(ee.__proto__=V,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},n.awrap=function(ee){return{__await:ee}};function q(ee,Y){function G(be,ke,Re,ae){var ye=E(ee[be],ee,ke);if(ye.type==="throw")ae(ye.arg);else{var lt=ye.arg,ot=lt.value;return ot&&typeof ot=="object"&&o.call(ot,"__await")?Y.resolve(ot.__await).then(function(Se){G("next",Se,Re,ae)},function(Se){G("throw",Se,Re,ae)}):Y.resolve(ot).then(function(Se){lt.value=Se,Re(lt)},function(Se){return G("throw",Se,Re,ae)})}}var re;function ge(be,ke){function Re(){return new Y(function(ae,ye){G(be,ke,ae,ye)})}return re=re?re.then(Re,Re):Re()}s(this,"_invoke",{value:ge})}B(q.prototype),T(q.prototype,_,function(){return this}),n.AsyncIterator=q,n.async=function(ee,Y,G,re,ge){ge===void 0&&(ge=Promise);var be=new q(S(ee,Y,G,re),ge);return n.isGeneratorFunction(Y)?be:be.next().then(function(ke){return ke.done?ke.value:be.next()})};function J(ee,Y,G){var re=A;return function(be,ke){if(re===R)throw new Error("Generator is already running");if(re===k){if(be==="throw")throw ke;return it()}for(G.method=be,G.arg=ke;;){var Re=G.delegate;if(Re){var ae=F(Re,G);if(ae){if(ae===M)continue;return ae}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=k,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=R;var ye=E(ee,Y,G);if(ye.type==="normal"){if(re=G.done?k:C,ye.arg===M)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=k,G.method="throw",G.arg=ye.arg)}}}function F(ee,Y){var G=Y.method,re=ee.iterator[G];if(re===r)return Y.delegate=null,G==="throw"&&ee.iterator.return&&(Y.method="return",Y.arg=r,F(ee,Y),Y.method==="throw")||G!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+G+"' method")),M;var ge=E(re,ee.iterator,Y.arg);if(ge.type==="throw")return Y.method="throw",Y.arg=ge.arg,Y.delegate=null,M;var be=ge.arg;if(!be)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,M;if(be.done)Y[ee.resultName]=be.value,Y.next=ee.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=r);else return be;return Y.delegate=null,M}B(D),T(D,g,"Generator"),T(D,h,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function Z(ee){var Y={tryLoc:ee[0]};1 in ee&&(Y.catchLoc=ee[1]),2 in ee&&(Y.finallyLoc=ee[2],Y.afterLoc=ee[3]),this.tryEntries.push(Y)}function U(ee){var Y=ee.completion||{};Y.type="normal",delete Y.arg,ee.completion=Y}function x(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(Z,this),this.reset(!0)}n.keys=function(ee){var Y=Object(ee),G=[];for(var re in Y)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in Y)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var Y=ee[h];if(Y)return Y.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(o.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=r,ge.done=!0,ge};return re.next=re}}return{next:it}}n.values=se;function it(){return{value:r,done:!0}}return x.prototype={constructor:x,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(U),!ee)for(var Y in this)Y.charAt(0)==="t"&&o.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=r)},stop:function(){this.done=!0;var ee=this.tryEntries[0],Y=ee.completion;if(Y.type==="throw")throw Y.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var Y=this;function G(ae,ye){return be.type="throw",be.arg=ee,Y.next=ae,ye&&(Y.method="next",Y.arg=r),!!ye}for(var re=this.tryEntries.length-1;re>=0;--re){var ge=this.tryEntries[re],be=ge.completion;if(ge.tryLoc==="root")return G("end");if(ge.tryLoc<=this.prev){var ke=o.call(ge,"catchLoc"),Re=o.call(ge,"finallyLoc");if(ke&&Re){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0);if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else if(ke){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0)}else if(Re){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,Y){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&o.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=Y&&Y<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=Y,ge?(this.method="next",this.next=ge.finallyLoc,M):this.complete(be)},complete:function(ee,Y){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&Y&&(this.next=Y),M},finish:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),M}},catch:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.tryLoc===ee){var re=G.completion;if(re.type==="throw"){var ge=re.arg;U(G)}return ge}}throw new Error("illegal catch attempt")},delegateYield:function(ee,Y,G){return this.delegate={iterator:se(ee),resultName:Y,nextLoc:G},this.method==="next"&&(this.arg=r),M}},n}(c.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(QT);var Eh={exports:{}};(function(c){(function(t,n){c.exports?c.exports=n():t.log=n()})(cs,function(){var t=function(){},n="undefined",a=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function s(C,R){var k=C[R];if(typeof k.bind=="function")return k.bind(C);try{return Function.prototype.bind.call(k,C)}catch{return function(){return Function.prototype.apply.apply(k,[C,arguments])}}}function r(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(C){return C==="debug"&&(C="log"),typeof console===n?!1:C==="trace"&&a?r:console[C]!==void 0?s(console,C):console.log!==void 0?s(console,"log"):t}function h(C,R){for(var k=0;k<o.length;k++){var M=o[k];this[M]=k<C?t:this.methodFactory(M,C,R)}this.log=this.debug}function _(C,R,k){return function(){typeof console!==n&&(h.call(this,R,k),this[C].apply(this,arguments))}}function g(C,R,k){return d(C)||_.apply(this,arguments)}function T(C,R,k){var M=this,ie;R=R??"WARN";var N="loglevel";typeof C=="string"?N+=":"+C:typeof C=="symbol"&&(N=void 0);function V(D){var B=(o[D]||"silent").toUpperCase();if(!(typeof window===n||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Ee(){var D;if(!(typeof window===n||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===n)try{var B=window.document.cookie,q=B.indexOf(encodeURIComponent(N)+"=");q!==-1&&(D=/^([^;]+)/.exec(B.slice(q))[1])}catch{}return M.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===n||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}M.name=C,M.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},M.methodFactory=k||g,M.getLevel=function(){return ie},M.setLevel=function(D,B){if(typeof D=="string"&&M.levels[D.toUpperCase()]!==void 0&&(D=M.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=M.levels.SILENT){if(ie=D,B!==!1&&V(D),h.call(M,D,C),typeof console===n&&D<M.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},M.setDefaultLevel=function(D){R=D,Ee()||M.setLevel(D,!1)},M.resetLevel=function(){M.setLevel(R,!1),ve()},M.enableAll=function(D){M.setLevel(M.levels.TRACE,D)},M.disableAll=function(D){M.setLevel(M.levels.SILENT,D)};var L=Ee();L==null&&(L=R),M.setLevel(L,!1)}var S=new T,E={};S.getLogger=function(R){if(typeof R!="symbol"&&typeof R!="string"||R==="")throw new TypeError("You must supply a name when creating a logger.");var k=E[R];return k||(k=E[R]=new T(R,S.getLevel(),S.methodFactory)),k};var A=typeof window!==n?window.log:void 0;return S.noConflict=function(){return typeof window!==n&&window.log===S&&(window.log=A),S},S.getLoggers=function(){return E},S.default=S,S})})(Eh);var It=Eh.exports;const Ss=()=>`${new Date().toISOString()} | metrics`,Es=(c,t,n)=>`${c} | ${t} | ${n}`;It.setDefaultLevel(It.levels.TRACE);const ZT=c=>{It.info(Es(Ss(),"log ",`set log level to ${c?"verbose":"info"}`)),It.setLevel(c?It.levels.TRACE:It.levels.INFO)},ev=c=>{const t=[...Object.keys(It.levels)];t.includes(c)?(It.info(Es(Ss(),"log ",`update log level to ${c.toLowerCase()}`)),It.setLevel(c)):It.warn(Es(Ss(),"log ","Incorrect log level please choose one of "),t)},xe=(c,t,n)=>{n?It.debug(Es(Ss(),c,t),n):It.debug(Es(Ss(),c,t))},Iu=(c,t)=>{It.info(Es(Ss(),c,t))},an=(c,t)=>{It.info(Es(Ss(),c,t))},Aa=(c,t)=>{It.warn(Es(Ss(),c,t))},jn=(c,t)=>{It.error(Es(Ss(),c,t))};function tv(c){return Math.floor(Math.random()*c).toString()}function yh(c,t){let n=t;return c.forEach(a=>{n=n.replace(a,"")}),n}function sv(c,t){let n="";for(let a=0;a<t;a+=1)n+=c[tv(c.length)];return n}function nv({length:c=20,useLetters:t=!0,useNumbers:n=!0,includeSymbols:a=[],excludeSymbols:o=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",r="0123456789",d=[],h=[],_=[];return t&&(o.length&&(s=yh(o,s)),h=s.split("")),n&&(o.length&&(r=yh(o,r)),_=r.split("")),d=[...h,..._,...a],sv(d,c)}var rv=nv;const ni=Me(rv),iv=()=>"WebRTCMetrics",lv=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},ys={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ri={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},av=()=>({...{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:[]}}),Ah={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:$e.INBOUND},Ch={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:$e.OUTBOUND},Rh={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:$e.INBOUND},Ih={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:$e.OUTBOUND},ov=c=>{const t={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const n={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(a=>{n.audio[a]={...c.audio[a]}}),Object.keys(c.video).forEach(a=>{n.video[a]={...c.video[a]}}),n}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},uv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${ni()}`,cid:`c-${ni()}`,uid:`u-${ni()}`,record:!1,ticket:!0},Qt={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"},j={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"},P={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},ii={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},bu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},wu="config ",cv=(c,t={},n)=>{const a={...n,...t};return t.pname||Aa(wu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),t.cid||Aa(wu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),t.uid||Aa(wu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),a.pc=c,a},fv=(c={})=>{const t={...uv,...c};return t.name=iv(),t.version=lv(),t},li=(c,t,n,a=!1,o)=>{let s=c.map(r=>{if(!n)return r[t];if(!o)return r[t][n];const d=r[t][o];return d?d[n]:null});return s=s.filter(r=>a?Number.isFinite(r)&&r>0:Number.isFinite(r)),s.length===0?[]:s},Ms=c=>c.reduce((t,n)=>t+n,0)/c.length,hv=()=>`probe-${ni()}`,dv=()=>`coltr-${ni()}`,bh=c=>new Promise(t=>setTimeout(t,c)),Ou=(c,t,n)=>{t?c.call(t,n):c(n)},We=(c,t,n,a)=>{const o=li(c,t,n,!0,a);if(o.length===0)return null;const s=o.reduce((_,g)=>_+g,0)/o.length;return s===0?null:o.map(_=>Math.abs(s-_)).reduce((_,g)=>_+g,0)/o.length*100/s},Xe=(c,t,n,a=!1,o)=>{const s=li(c,t,n,a,o);return s.length===0?null:s.reduce((r,d)=>r+d,0)/s.length},on=(c,t,n)=>li(c,t,n).reduce((o,s)=>o+s,0),Ke=(c,t,n,a)=>{const o=li(c,t,n,!0,a);return o.length===0?null:Math.min(...o)},Ye=(c,t,n,a)=>{const o=li(c,t,n,!1,a);return o.length===0?null:Math.max(...o)},At=(c,t,n,a)=>{const o=c.slice().pop();if(!o)return null;if(!n)return o[t];if(!a)return o[t][n];const s=o[t][a];return s?s[n]:null},_v=c=>c.slice().pop(),ht=(c,t,n)=>{if(!t)return null;const a={};let o=t[P.AUDIO][c];o||(o=n===$e.INBOUND?{...Ah}:{...Ch}),a[P.AUDIO]=o;let s=t[P.VIDEO][c];return s||(s=n===$e.INBOUND?{...Rh}:{...Ih}),a[P.VIDEO]=s,a},ai="exporter ",pv="2.0",wh=(c,t,n)=>{if(!c||c.length===0)return 0;const a=c[c.length-1];if(!a)return 0;const o=a[t][n];if(o){const s=o.total_rtt_ms_out,r=o.total_rtt_measure_out;return!r||!s?Xe(c,t,"delta_rtt_ms_out",!1,n):Number(s/r)}return null},mv=(c,t)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const a=n[t].total_rtt_connectivity_ms,o=n[t].total_rtt_connectivity_measure;return!o||!a?Xe(c,t,"delta_rtt_connectivity_ms"):Number(a/o)},gv=c=>At(c,"network","local_candidate_type")!=="relay"?`direct/${At(c,"network","local_candidate_protocol")}`:`turn/${At(c,"network","local_candidate_relay_protocol")}`,Tv=c=>{const t=At(c,"network","remote_candidate_type"),n=At(c,"network","remote_candidate_protocol");return t!=="relay"?`direct/${n}`:`turn/${n}`};class vv{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){Iu(ai,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){Iu(ai,"stop() - stop exporter...");const t=new Date;return this._end=t.toJSON(),t}saveReferenceReport(t){this._referenceReport=t}getReferenceReport(){return this._referenceReport}addReport(t){this._cfg.ticket&&(xe(ai,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){Iu(ai,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){xe(ai,"ticket() - generate ticket");const t=At(this._reports,"audio","total_packets_lost_in"),n=At(this._reports,"audio","total_packets_in"),a=At(this._reports,"video","total_packets_lost_in"),o=At(this._reports,"video","total_packets_in"),s={},r=_v(this._reports);return r&&(Object.keys(r[P.AUDIO]).forEach(d=>{const h=r[P.AUDIO][d];if(s[h.ssrc]={type:P.AUDIO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,P.AUDIO,"delta_jitter_ms_in",!1,d),min:Ke(this._reports,P.AUDIO,"delta_jitter_ms_in",d),max:Ye(this._reports,P.AUDIO,"delta_jitter_ms_in",d),volatility:We(this._reports,P.AUDIO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,P.AUDIO,"delta_kbs_in",!1,d),min:Ke(this._reports,P.AUDIO,"delta_kbs_in",d),max:Ye(this._reports,P.AUDIO,"delta_kbs_in",d),volatility:We(this._reports,P.AUDIO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,P.AUDIO,"delta_KBytes_in",!1,d),min:Ke(this._reports,P.AUDIO,"delta_KBytes_in",d),max:Ye(this._reports,P.AUDIO,"delta_KBytes_in",d),volatility:We(this._reports,P.AUDIO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={emodel:{avg:Xe(this._reports,P.AUDIO,"mos_emodel_in",!1,d),min:Ke(this._reports,P.AUDIO,"mos_emodel_in",d),max:Ye(this._reports,P.AUDIO,"mos_emodel_in",d),volatility:We(this._reports,P.AUDIO,"mos_emodel_in",d)},effective:{avg:Xe(this._reports,P.AUDIO,"mos_in",!1,d),min:Ke(this._reports,P.AUDIO,"mos_in",d),max:Ye(this._reports,P.AUDIO,"mos_in",d),volatility:We(this._reports,P.AUDIO,"mos_in",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},E=At(this._reports,P.AUDIO,"total_packets_lost_in",d),A=At(this._reports,P.AUDIO,"total_packets_in",d),C={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].mos=S,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}else{const _={avg:Xe(this._reports,P.AUDIO,"delta_jitter_ms_out",!1,d),min:Ke(this._reports,P.AUDIO,"delta_jitter_ms_out",d),max:Ye(this._reports,P.AUDIO,"delta_jitter_ms_out",d),volatility:We(this._reports,P.AUDIO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,P.AUDIO,"delta_kbs_out",!1,d),min:Ke(this._reports,P.AUDIO,"delta_kbs_out",d),max:Ye(this._reports,P.AUDIO,"delta_kbs_out",d),volatility:We(this._reports,P.AUDIO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,P.AUDIO,"delta_KBytes_out",!1,d),min:Ke(this._reports,P.AUDIO,"delta_KBytes_out",d),max:Ye(this._reports,P.AUDIO,"delta_KBytes_out",d),volatility:We(this._reports,P.AUDIO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},S={avg:wh(this._reports,P.AUDIO,d),min:Ke(this._reports,P.AUDIO,"delta_rtt_ms_out",d),max:Ye(this._reports,P.AUDIO,"delta_rtt_ms_out",d),volatility:We(this._reports,P.AUDIO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=At(this._reports,P.AUDIO,"total_packets_lost_out",d),A=At(this._reports,P.AUDIO,"total_packets_out",d),C={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},R={emodel:{avg:Xe(this._reports,P.AUDIO,"mos_emodel_out",!1,d),min:Ke(this._reports,P.AUDIO,"mos_emodel_out",d),max:Ye(this._reports,P.AUDIO,"mos_emodel_out",d),volatility:We(this._reports,P.AUDIO,"mos_emodel_out",d)},effective:{avg:Xe(this._reports,P.AUDIO,"mos_out",!1,d),min:Ke(this._reports,P.AUDIO,"mos_out",d),max:Ye(this._reports,P.AUDIO,"mos_out",d),volatility:We(this._reports,P.AUDIO,"mos_out",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[d].jitter=_,s[d].rtt=S,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C,s[d].mos=R}}),Object.keys(r[P.VIDEO]).forEach(d=>{const h=r[P.VIDEO][d];if(s[d]={type:P.VIDEO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,P.VIDEO,"delta_jitter_ms_in",!1,d),min:Ke(this._reports,P.VIDEO,"delta_jitter_ms_in",d),max:Ye(this._reports,P.VIDEO,"delta_jitter_ms_in",d),volatility:We(this._reports,P.VIDEO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,P.VIDEO,"delta_kbs_in",!1,d),min:Ke(this._reports,P.VIDEO,"delta_kbs_in",d),max:Ye(this._reports,P.VIDEO,"delta_kbs_in",d),volatility:We(this._reports,P.VIDEO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,P.VIDEO,"delta_KBytes_in",!1,d),min:Ke(this._reports,P.VIDEO,"delta_KBytes_in",d),max:Ye(this._reports,P.VIDEO,"delta_KBytes_in",d),volatility:We(this._reports,P.VIDEO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S=At(this._reports,P.VIDEO,"total_packets_lost_in",d),E=At(this._reports,P.VIDEO,"total_packets_in",d),A={lost:S,avg:Math.round((S/(S+E)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].traffic=T,s[d].bitrate=g,s[d].loss=A}else{const _={avg:Xe(this._reports,P.VIDEO,"delta_jitter_ms_out",!1,d),min:Ke(this._reports,P.VIDEO,"delta_jitter_ms_out",d),max:Ye(this._reports,P.VIDEO,"delta_jitter_ms_out",d),volatility:We(this._reports,P.VIDEO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,P.VIDEO,"delta_kbs_out",!1,d),min:Ke(this._reports,P.VIDEO,"delta_kbs_out",d),max:Ye(this._reports,P.VIDEO,"delta_kbs_out",d),volatility:We(this._reports,P.VIDEO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,P.VIDEO,"delta_KBytes_out",!1,d),min:Ke(this._reports,P.VIDEO,"delta_KBytes_out",d),max:Ye(this._reports,P.VIDEO,"delta_KBytes_out",d),volatility:We(this._reports,P.VIDEO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={avg:wh(this._reports,P.VIDEO,d),min:Ke(this._reports,P.VIDEO,"delta_rtt_ms_out",d),max:Ye(this._reports,P.VIDEO,"delta_rtt_ms_out",d),volatility:We(this._reports,P.VIDEO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=At(this._reports,P.VIDEO,"total_packets_lost_out",d),A=At(this._reports,P.VIDEO,"total_packets_out",d),C={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].rtt=S,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}})),{version:pv,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:s,data:{rtt:{avg:mv(this._reports,"data"),min:Ke(this._reports,"data","delta_rtt_connectivity_ms"),max:Ye(this._reports,"data","delta_rtt_connectivity_ms"),volatility:We(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((t/(t+n)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+o)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Xe(this._reports,"data","delta_kbs_in"),min:Ke(this._reports,"data","delta_kbs_in"),max:Ye(this._reports,"data","delta_kbs_in"),volatility:We(this._reports,"data","delta_kbs_in")},out:{avg:Xe(this._reports,"data","delta_kbs_out"),min:Ke(this._reports,"data","delta_kbs_out"),max:Ye(this._reports,"data","delta_kbs_out"),volatility:We(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Xe(this._reports,"data","delta_KBytes_in"),min:Ke(this._reports,"data","delta_KBytes_in"),max:Ye(this._reports,"data","delta_KBytes_in"),volatility:We(this._reports,"data","delta_KBytes_in")},out:{avg:Xe(this._reports,"data","delta_KBytes_out"),min:Ke(this._reports,"data","delta_KBytes_out"),max:Ye(this._reports,"data","delta_KBytes_out"),volatility:We(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:gv(this._reports),remoteConnection:Tv(this._reports)}}}}updateConfig(t){this._cfg=t}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const t=this._reports.slice();return t.pop(),t.pop()||null}getReportsNumber(){return this._reports.length}}const Ls="extractor ",Oh=(c,t,n,a)=>{let o=!1;const s=a[t].total_rtt_ms_out,r=a[t].total_rtt_measure_out,d=n?n[t].total_rtt_ms_out:0,h=n?n[t].total_rtt_measure_out:0,_={rtt:null,totalRTT:s,totalRTTMeasurements:r};if(c[j.TIMESTAMP]===a[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,j.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,j.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(o=!0,Number(c[j.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[j.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h===r))return _;const g=1e3*Number(c[j.ROUND_TRIP_TIME]);let T=s+g,S=r+1;return o&&(T=1e3*Number(c[j.TOTAL_ROUND_TRIP_TIME])-d,S=Number(c[j.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h),{rtt:g,totalRTT:T,totalRTTMeasurements:S}},Sv=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,j.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[t].total_rtt_connectivity_ms,totalRTTMeasurements:a[t].total_rtt_connectivity_measure};const o=1e3*Number(c[j.CURRENT_ROUND_TRIP_TIME]);let s=a[t].total_rtt_connectivity_ms+o,r=a[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,j.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(c[j.TOTAL_ROUND_TRIP_TIME])-(n?n[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,j.RESPONSES_RECEIVED)&&(r=Number(c[j.RESPONSES_RECEIVED])-(n?n[t].total_rtt_connectivity_measure:0)),{rtt:o,totalRTT:s,totalRTTMeasurements:r}},Ca=(c,t,n)=>c[j.TIMESTAMP]===n[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,j.JITTER)?null:1e3*(Number(c[j.JITTER])||0),Ev=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,j.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,j.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:t[P.VIDEO].delta_ms_decode_frame_in,frames_decoded:t[P.VIDEO].total_frames_decoded_in,total_decode_time:t[P.VIDEO].total_time_decoded_in};const n=c[j.FRAMES_DECODED],a=c[j.TOTAL_DECODE_TIME],o=a-t[P.VIDEO].total_time_decoded_in,s=n-t[P.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?o*1e3/s:0,frames_decoded:n,total_decode_time:a}},yv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,j.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,j.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:t[P.VIDEO].delta_ms_encode_frame_out,frames_encoded:t[P.VIDEO].total_frames_encoded_out,total_encode_time:t[P.VIDEO].total_time_encoded_out};const n=c[j.FRAMES_ENCODED],a=c[j.TOTAL_ENCODE_TIME],o=a-t[P.VIDEO].total_time_encoded_out,s=n-t[P.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&o?o*1e3/s:0,frames_encoded:n,total_encode_time:a}},Dh=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,j.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,j.BYTES_SENT))return{packetsSent:n[t].total_packets_out,packetsLost:n[t].total_packets_lost_out,bytesSent:n[t].total_KBytes_out};const o=Number(c[j.PACKETS_SENT])||0-(a?a[t].total_packets_out:0),s=o-n[t].total_packets_out,r=Number(c[j.BYTES_SENT])/1024-(a?a[t].total_KBytes_out:0),d=r-n[t].total_KBytes_out,h=c[j.TIMESTAMP]||Date.now(),_=a?a.timestamp:null;let g=n.timestamp;!g&&_&&(g=_);const T=g?h-g:0,S=T>0?d*.008*1024/T*1e3:0;return{packetsSent:o,deltaPacketsSent:s,KBytesSent:r,deltaKBytesSent:d,kbsSent:S}},Nh=(c,t,n,a)=>{let o=n[t].total_packets_lost_out,s=0,r=0;return Object.prototype.hasOwnProperty.call(c,j.PACKETS_LOST)&&(o=Number(c[j.PACKETS_LOST])||0-(a?a[t].total_packets_lost_out:0),s=o-n[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,j.FRACTION_LOST)&&(r=Number(100*c[j.FRACTION_LOST])),{packetsLost:o,deltaPacketsLost:s,fractionLost:r}},Uh=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,j.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,j.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,j.BYTES_RECEIVED))return{percent_packets_lost:n[t].percent_packets_lost_in,packetsReceived:n[t].total_packets_in,packetsLost:n[t].total_packets_lost_in,bytesReceived:n[t].total_KBytes_in};const o=Number(c[j.PACKETS_RECEIVED])||0-(a?a[t].total_packets_in:0),s=Number(c[j.PACKETS_LOST])||0-(a?a[t].total_packets_lost_in:0),r=s-n[t].total_packets_lost_in,d=o-n[t].total_packets_in,h=o!==n[t].total_packets_in?r*100/(r+d):0,_=Number(c[j.BYTES_RECEIVED])/1024-(a?a[t].total_KBytes_in:0),g=_-n[t].total_KBytes_in,T=c[j.TIMESTAMP]||Date.now(),S=a?a.timestamp:null;let E=n.timestamp;!E&&S&&(E=S);const A=E?T-E:0,C=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:h,packetsReceived:o,deltaPacketsReceived:d,packetsLost:s,deltaPacketsLost:r,KBytesReceived:_,deltaKBytesReceived:g,kbsReceived:C}},Av=c=>c[j.CANDIDATE_TYPE]!=="relay"?"":c[j.RELAY_PROTOCOL]||"",Cv=c=>{if(!Object.prototype.hasOwnProperty.call(c,j.NETWORK_TYPE))return ii.WIFI;switch(c[j.NETWORK_TYPE]){case bu.ETHERNET:return ii.ETHERNET;case bu.CELLULAR_4G:return ii.CELLULAR_4G;case bu.WIFI:return ii.WIFI;default:return ii.CELLULAR}},xh=c=>!Object.prototype.hasOwnProperty.call(c,j.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,j.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[j.FRAME_WIDTH]||null,height:c[j.FRAME_HEIGHT]||null,framerate:c[j.FRAMES_PER_SECOND]},Rv=c=>{const t=Object.prototype.hasOwnProperty.call(c,j.QUALITY_LIMITATION_REASON)?c[j.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,j.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[j.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(c,j.QUALITY_LIMITATION_DURATIONS)?c[j.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(o=>{a[o]>1e3&&(a[o]=Number(a[o]/1e3))}),{reason:t,durations:a,resolutionChanges:n}},Iv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,j.PLI)||!Object.prototype.hasOwnProperty.call(c,j.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(c[j.PLI]||0)-(n?n[P.VIDEO].total_pli_sent_in:0),o=(c[j.NACK]||0)-(n?n[P.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[P.VIDEO].total_pli_sent_in,deltaNackCount:o-t[P.VIDEO].total_nack_sent_in}},bv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,j.PLI)||!Object.prototype.hasOwnProperty.call(c,j.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(c[j.PLI]||0)-(n?n[P.VIDEO].total_pli_received_out:0),o=(c[j.NACK]||0)-(n?n[P.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[P.VIDEO].total_pli_received_out,deltaNackCount:o-t[P.VIDEO].total_nack_received_out}},wv=c=>({channels:c[j.CHANNELS]||null,clock_rate:c[j.CLOCK_RATE]||null,mime_type:c[j.MIME_TYPE]||null,sdp_fmtp_line:c[j.SDP_FMTP_LINE]||null}),Ov=c=>({clock_rate:c[j.CLOCK_RATE]||null,mime_type:c[j.MIME_TYPE]||null}),Dv=(c,t,n)=>{const a=(c[j.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),o=(c[j.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),s=c[j.TIMESTAMP]||Date.now(),r=a-t.data.total_KBytes_in,d=o-t.data.total_KBytes_out,h=n?n.timestamp:null;let _=t.timestamp;!_&&h&&(_=h);const g=_?s-_:0,T=g>0?r*.008*1024/g*1e3:0,S=g>0?d*.008*1024/g*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:o,delta_KBytes_received:r,delta_KBytes_sent:d,kbs_speed_received:T,kbs_speed_sent:S}},Nv=c=>{const t=c[j.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[j.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:n}},Uv=(c,t,n,a)=>{if(!c)return[];switch(c[j.TYPE]){case Qt.CANDIDATE_PAIR:let o=!1;if(c[j.NOMINATED]&&c[j.STATE]===P.SUCCEEDED&&(o=!0,xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c),j.SELECTED in c&&!c[j.SELECTED]&&(o=!1)),o){const r=c[j.LOCAL_CANDIDATE_ID],d=c[j.REMOTE_CANDIDATE_ID],h=Dv(c,t,a),_=Nv(c),g=Sv(c,"data",a,t);return[{type:ne.NETWORK,value:{local_candidate_id:r}},{type:ne.NETWORK,value:{remote_candidate_id:d}},{type:ne.DATA,value:{total_KBytes_in:h.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:h.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:h.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:h.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:h.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:h.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:_.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:_.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case Qt.LOCAL_CANDIDATE:if(c[j.ID]===t.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:Cv(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[j.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[j.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:Av(c)}}];break;case Qt.REMOTE_CANDIDATE:if(c[j.ID]===t.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[j.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[j.PROTOCOL]||""}}];break;case Qt.INBOUND_RTP:{xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);const r=c[j.SSRC],d=ht(r,t,$e.INBOUND);d&&(d.timestamp=t.timestamp);const h=ht(r,a,$e.INBOUND);if(h&&(h.timestamp=a.timestamp),c[j.MEDIA_TYPE]===P.AUDIO){const _=Uh(c,P.AUDIO,d,h),g=Ca(c,P.AUDIO,d),T=c[j.CODEC_ID]||"";return[{ssrc:r,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:r,type:ne.AUDIO,value:{total_packets_in:_.packetsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_in:_.deltaPacketsReceived}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_in:_.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_in:_.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_in:_.percentPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_in:_.KBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_in:_.deltaKBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_in:_.kbsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[j.MEDIA_TYPE]===P.VIDEO){const _=Ev(c,d),g=Uh(c,P.VIDEO,d,h),T=Ca(c,P.VIDEO,d),S=c[j.DECODER_IMPLEMENTATION]||null,E=c[j.CODEC_ID]||null,A=xh(c),C=Iv(c,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_in:E}},{ssrc:r,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:r,type:ne.VIDEO,value:{decoder_in:S}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_decode_frame_in:_.delta_ms_decode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_decoded_in:_.frames_decoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_decoded_in:_.total_decode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_sent_in:C.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_sent_in:C.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_sent_in:C.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_sent_in:C.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_in:A}}]}break}case Qt.OUTBOUND_RTP:{xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);const r=c[j.SSRC],d=ht(r,t,$e.OUTBOUND);d&&(d.timestamp=t.timestamp);const h=ht(r,a,$e.OUTBOUND);if(h&&(h.timestamp=a.timestamp),c[j.MEDIA_TYPE]===P.AUDIO){const _=c[j.CODEC_ID]||null,g=Dh(c,P.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{codec_id_out:_}},{ssrc:r,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[j.MEDIA_TYPE]===P.VIDEO){const _=c[j.ENCODER_IMPLEMENTATION]||null,g=c[j.CODEC_ID]||null,T=yv(c,d),S=xh(c),E=Rv(c),A=bv(c,d,h),C=Dh(c,P.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:r,type:ne.VIDEO,value:{total_packets_out:C.packetsSent}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_out:C.deltaPacketsSent}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_out:C.KBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_out:C.deltaKBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_out:C.kbsSent}},{ssrc:r,type:ne.VIDEO,value:{encoder_out:_}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_out:S}},{ssrc:r,type:ne.VIDEO,value:{limitation_out:E}}]}break}case Qt.MEDIA_SOURCE:{xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);break}case Qt.TRACK:{xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);break}case Qt.CODEC:const s=[];return Object.keys(t[P.AUDIO]).forEach(r=>{const d=t[P.AUDIO][r];if(d.codec_id_in===c[j.ID]||d.codec_id_out===c[j.ID]){xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);const h=wv(c);c[j.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_out:h}})}}),Object.keys(t[P.VIDEO]).forEach(r=>{const d=t[P.VIDEO][r];if(d.codec_id_in===c[j.ID]||d.codec_id_out===c[j.ID]){xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);const h=Ov(c);c[j.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_out:h}})}}),s;case Qt.REMOTE_INBOUND_RTP:{xe(Ls,`analyze() - got stats ${c[j.TYPE]} for ${n}`,c);const r=c[j.SSRC],d=ht(r,t,$e.OUTBOUND),h=ht(r,a,$e.OUTBOUND);if(c[j.KIND]===P.AUDIO){const _=Oh(c,P.AUDIO,h,d),g=Ca(c,P.AUDIO,d),T=Nh(c,P.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.AUDIO,value:{timestamp_out:c[j.TIMESTAMP]}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[j.KIND]===P.VIDEO){const _=Oh(c,P.VIDEO,h,d),g=Ca(c,P.VIDEO,d),T=Nh(c,P.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.VIDEO,value:{timestamp_out:c[j.TIMESTAMP]}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Ra=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),xv=(c,t=P.AUDIO,n,a,o)=>{const s=ht(o,c,$e.INBOUND),r=ht(o,n,$e.INBOUND),d=ht(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in,T=s[t].delta_jitter_ms_in,S=r&&r[t].delta_jitter_ms_in||null,E=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,R=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),R&&h.push(R),T&&_.push(T),n&&S&&_.push(S),a&&E&&_.push(E);const k=h.length>0?Ms(h):100,M=_.length>0?Ms(_):10,ie=93.2-g,N=.18*ie*ie-27.9*ie+1126.62,V=(k+M)/2,Ee=V-177.3<0?0:1,ve=.024*V+.11*(V-177.3)*Ee,L=N-ve;return Ra(L)},Pv=(c,t=P.AUDIO,n,a,o)=>{const s=ht(o,c,$e.OUTBOUND),r=ht(o,n,$e.OUTBOUND),d=ht(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out,T=s[t].delta_rtt_ms_out,S=r&&r[t].delta_rtt_ms_out||null,E=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,R=d&&d[t].delta_jitter_ms_out||null,k=c.data.delta_rtt_connectivity_ms,M=n&&n.data.delta_rtt_connectivity_ms||null,ie=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):k&&h.push(k),S?h.push(S):M&&h.push(M),E?h.push(E):ie&&h.push(ie),A&&_.push(A),n&&C&&_.push(C),a&&R&&_.push(R);const N=h.length>0?Ms(h):100,V=_.length>0?Ms(_):10,Ee=93.2-g,ve=.18*Ee*Ee-27.9*Ee+1126.62,L=(N+V)/2,D=L-177.3<0?0:1,B=.024*L+.11*(L-177.3)*D,q=ve-B;return Ra(q)},kv=(c,t=P.AUDIO,n,a,o)=>{const s=ht(o,c,$e.INBOUND),r=ht(o,n,$e.INBOUND),d=ht(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in/100,T=s[t].delta_jitter_ms_in,S=r&&r[t].delta_jitter_ms_in||null,E=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,R=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),R&&h.push(R),T&&_.push(T),r&&S&&_.push(S),d&&E&&_.push(E);const k=h.length>0?Ms(h):100,M=_.length>0?Ms(_):10,ie=0,N=19.8,V=29.7,Ee=30,ve=(k+M)/2+Ee,L=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*L,q=93.2-(ie+N*Math.log(1+V*g)+D);return Ra(q)},Mv=(c,t=P.AUDIO,n,a,o)=>{const s=ht(o,c,$e.OUTBOUND),r=ht(o,n,$e.OUTBOUND),d=ht(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out/100,T=s[t].delta_rtt_ms_out,S=r&&r[t].delta_rtt_ms_out||null,E=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,R=d&&d[t].delta_jitter_ms_out||null,k=c.data.delta_rtt_connectivity_ms,M=n&&n.data.delta_rtt_connectivity_ms||null,ie=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):k&&h.push(k),S?h.push(S):M&&h.push(M),E?h.push(E):ie&&h.push(ie),A&&_.push(A),r&&C&&_.push(C),d&&R&&_.push(R);const N=h.length>0?Ms(h):100,V=_.length>0?Ms(_):10,Ee=0,ve=19.8,L=29.7,D=30,B=(N+V)/2+D,q=B-177.3<0?0:1,J=.024*B+.11*(B-177.3)*q,Z=93.2-(Ee+ve*Math.log(1+L*g)+J);return Ra(Z)};class Lv{constructor(t,n){this._callbacks={onreport:null,onticket:null},this._id=dv(),this._moduleName=this._id,this._probeId=n,this._config=t,this._exporter=new vv(t),this._state=ys.IDLE,this.registerToPCEvents(),an(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,n,a,o){const s=(h,_)=>h===P.AUDIO?_===Qt.INBOUND_RTP?{...Ah}:{...Ch}:_===Qt.INBOUND_RTP?{...Rh}:{...Ih},r=ov(n);r.pname=this._config.pname,r.call_id=this._config.cid,r.user_id=this._config.uid,r.count=n?n.count+1:1;let d=null;return t.forEach(h=>{!d&&h.timestamp&&(d=h.timestamp),Uv(h,r,r.pname,o).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=r[g.type][g.ssrc];T||(T=s(g.type,h.type),T.ssrc=g.ssrc,r[g.type][g.ssrc]=T),Object.keys(g.value).forEach(S=>{T[S]=g.value[S]})}else Object.keys(g.value).forEach(T=>{r[g.type][T]=g.value[T]})})}),r.timestamp=d,Object.keys(r[P.AUDIO]).forEach(h=>{const _=r[P.AUDIO][h];_.direction===$e.INBOUND?(_.mos_emodel_in=xv(r,P.AUDIO,n,a,_.ssrc),_.mos_in=kv(r,P.AUDIO,n,a,_.ssrc)):(_.mos_emodel_out=Pv(r,P.AUDIO,n,a,_.ssrc),_.mos_out=Mv(r,P.AUDIO,n,a,_.ssrc))}),r}async takeReferenceStats(){return new Promise((t,n)=>{const a=Date.now();setTimeout(async()=>{try{const o=Date.now()-a,s=Date.now(),r=await this._config.pc.getStats(),d=this.analyze(r,null,null,null),h=Date.now();d.experimental.time_to_measure_ms=h-s,d.experimental.time_to_wait_ms=o,this._exporter.saveReferenceReport(d),xe(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(o){n(o)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ys.RUNNING||!this._config.pc)return xe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const t=Date.now(),n=await this._config.pc.getStats(),a=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),o=Date.now();return a.experimental.time_to_measure_ms=o-t,this._exporter.addReport(a),xe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(t){return jn(this._moduleName,`got error ${t}`),null}}async start(){xe(this._moduleName,"starting"),this.state=ys.RUNNING,this._startedTime=this._exporter.start(),xe(this._moduleName,"started")}async mute(){this.state=ys.MUTED,xe(this._moduleName,"muted")}async unmute(){this.state=ys.RUNNING,xe(this._moduleName,"unmuted")}async stop(t){if(xe(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ys.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),xe(this._moduleName,"stopped")}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},xe(this._moduleName,`registered callback '${t}'`)):jn(this._moduleName,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],xe(this._moduleName,`unregistered callback '${t}'`)):jn(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReport(t){this._callbacks.onreport&&Ou(this._callbacks.onreport.callback,this._callbacks.onreport.context,t)}fireOnTicket(t){this._callbacks.onticket&&Ou(this._callbacks.onticket.callback,this._callbacks.onticket.context,t)}updateConfig(t){this._config=t,this._exporter.updateConfig(t)}get state(){return this._state}set state(t){this._state=t,xe(this._moduleName,`state changed to ${t}`)}addCustomEvent(t,n,a,o){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:n,name:a,description:o})}async registerToPCEvents(){const{pc:t}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const n=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${n.length} devices found`,"Media Devices state")}catch{jn(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const a=t.iceConnectionState;a===ri.CONNECTED||a===ri.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ri.DISCONNECTED||a===ri.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ri.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const a=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},t.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},t.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const n=t.getReceivers();if(n&&n.length>0){const a=n[0],{transport:o}=a;if(o){const{iceTransport:s}=o;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class $v{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||hv(),this._moduleName=this._id,an(this._moduleName,"probe created"),this._config=t,this._collector=new Lv(this._config,this._id)}set onreport(t){t?this._collector.registerCallback("onreport",t):this._collector.unregisterCallback("onreport")}set onticket(t){t?this._collector.registerCallback("onticket",t):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(t){this._collector.state=t}addCustomEvent(t,n,a,o=new Date().toJSON()){this._collector.addCustomEvent(o,n,t,a)}get isRunning(){return this._collector.state===ys.RUNNING}get isIdle(){return this._collector.state===ys.IDLE}updateUserId(t){this._config.uid=t,this._collector.updateConfig(this._config)}updateCallId(t){this._config.cid=t,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Aa(this._moduleName,"probe is already running");return}this._collector.start()}stop(t=!1){this.isRunning&&this._collector.stop(t)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const bt="engine ";class Hv{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},an(bt,`configured for probing every ${this._config.refreshEvery}ms`),an(bt,`configured for starting after ${this._config.startAfter}ms`),an(bt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),xe(bt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(t=>t.isRunning)}get isIdle(){return this._probes.every(t=>t.isIdle)}addNewProbe(t,n){if(!t)throw new Error("undefined peer connection");const a=cv(t,n,this._config),o=new $v(a);return this._probes.push(o),xe(bt,`${this._probes.length} probes registered`),o}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===ys.RUNNING&&t.stop(),this._probes=this._probes.filter(n=>t.id!==n.id)}async start(){const t=()=>{this._probes.forEach(s=>s.start())},n=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,o=async()=>{const s=av(),r=this._probes.filter(d=>d.isRunning);for(const d of r){const h=await d.collectStats();h&&s.probes.push(h),xe(bt,`got probe ${d.id}`),await bh(0)}return s.delta_time_to_measure_probes_ms=on(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=on(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=on(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=on(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=on(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=on(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=on(s.probes,"video","total_time_encoded_out"),s};for(xe(bt,"starting to collect"),t(),xe(bt,"generating reference reports..."),await n(),xe(bt,"reference reports generated"),this._startedTime=Date.now();a();)if(xe(bt,`wait ${this._config.refreshEvery}ms before collecting`),await bh(this._config.refreshEvery),a()){xe(bt,"collecting...");const s=Date.now(),r=await o(),d=Date.now();r.delta_time_consumed_to_measure_ms=d-s,this.fireOnReports(r),xe(bt,"collected")}xe(bt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const n=a=>{this._probes.forEach(o=>{o.stop(a)})};an(bt,"stop collecting"),n(t)}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},xe(bt,`registered callback '${t}'`)):jn(bt,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],xe(this._moduleName,`unregistered callback '${t}'`)):jn(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReports(t){this._callbacks.onresult&&t.probes.length>0&&Ou(this._callbacks.onresult.callback,this._callbacks.onresult.context,t)}}const Fv="interface ";class Vv{constructor(t){this._config=fv(t),an(Fv,`welcome to ${this._config.name} version ${this._config.version}`),ZT(this._config.verbose||!1),this._engine=new Hv(this._config)}setupLogLevel(t){ev(t)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(t,n){return this._engine.addNewProbe(t,n)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(t){this._engine.removeExistingProbe(t)}set onresult(t){t?this._engine.registerCallback("onresult",t):this._engine.unregisterCallback("onresult")}}function jv(c,t){return Object.keys(c).filter(n=>t.includes(n)).reduce((n,a)=>{const o=a;return{...n,[o]:c[o]}},{})}const qv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],Bv={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class Gv{constructor(t){this.intervals={},this.analysers={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}async start(t,n,a){n&&n.getTracks().length&&await this.beginCalculation(t,n,a)}stop(t){this.clearVolumeInterval(t),this.analysers[t]&&typeof this.analysers[t].disconnect=="function"&&(this.analysers[t].disconnect(),delete this.analysers[t])}clearVolumeInterval(t){this.intervals[t]&&(clearInterval(this.intervals[t]),delete this.intervals[t])}clearAllIntervals(){Object.keys(this.intervals).forEach(t=>{this.stop(t)}),this.intervals={},this.analysers={}}async beginCalculation(t,n,a){this.clearVolumeInterval(a);const o=t.createAnalyser(),s=t.createMediaStreamSource(n);o.smoothingTimeConstant=.8,o.fftSize=1024,s.connect(o),this.analysers[a]=o,this.intervals[a]=setInterval(()=>{const r=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(r);let d=0;const h=r.length;for(let g=0;g<h;g++)d+=r[g];const _=d/h;this.onChangeFunction(a,_)},this.emitInterval)}}class Wv{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(t=>{throw this.resumePromise=null,t})),await this.resumePromise),this.context}}const Ia={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},Kv=0;class Yv{constructor(t){var n;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 Wv,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new Gv({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices(),this.processVADConfiguration(((n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)||{}),this.setupVADInstance()}setVADConfiguration(t){if(!this.MicVAD)throw new Error("VAD module is not provided in the initial configuration");const n=Object.keys(t);for(const a of n)this.noiseReduction[a]=t[a];this.hasActiveCalls&&this.roomReconfigure(this.currentActiveRoomId)}setupVADInstance(){var n,a;const t=(a=(n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)==null?void 0:a.vadModule;t&&t.MicVAD?(this.MicVAD=t.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(t){this.noiseReduction={mode:t.mode||"disabled",checkEveryMs:t.checkEveryMs||500,noiseCheckInterval:t.noiseCheckInterval||2e3,noiseThreshold:t.noiseThreshold||.004,vadConfig:t.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(t){this.currentActiveRoomIdValue=t,this.context.emit("currentActiveRoomChanged",t)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(t){this.isCallAddingInProgress=t,this.context.emit("callAddingInProgressChanged",t)}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(a=>!a.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audiooutput")}get getUserMediaConstraints(){return vh()?{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(t){this.availableMediaDevices=t,this.context.emit("changeAvailableDeviceList",t)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}async initializeMediaDevices(){const t=localStorage.getItem(Ia.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(Ia.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),o=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(o),await this.setMicrophone(t),await this.setSpeaker(n),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),a.getTracks().forEach(s=>s.stop())}catch(a){console.error(a)}}async cleanupConferenceNodes(t){const n=this.conferenceNodes[t];if(!n)return;let a=0;n.sources.forEach((r,d)=>{try{r.disconnect(),a++}catch(h){console.error(`[cleanupConferenceNodes] Error disconnecting source ${d}:`,h)}});let o=0;n.destinations.forEach((r,d)=>{try{r.disconnect(),o++}catch(h){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${d}:`,h)}});let s=0;n.gains.forEach((r,d)=>{try{r.disconnect(),s++}catch(h){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${d}:`,h)}}),delete this.conferenceNodes[t]}setCallTime(t){const n={...t};delete n.callId,this.callTime={...this.callTime,[t.callId]:n},this.context.emit("changeCallTime",this.callTime)}removeCallTime(t){const n={...this.callTime};delete n[t],this.callTime={...n},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(t,n){this.timeIntervals={...this.timeIntervals,[t]:n}}removeTimeInterval(t){const n={...this.timeIntervals};n[t]&&(clearInterval(n[t]),delete n[t],this.timeIntervals={...n})}stopCallTimer(t){this.removeTimeInterval(t),this.removeCallTime(t)}emitVolumeChange(t,n){this.context.emit("changeCallVolume",{callId:t,volume:n})}setMetricsConfig(t){this.metricConfig={...this.metricConfig,...t}}sendDTMF(t,n){if(!/^[A-D0-9*#]+$/g.test(n))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[t].sendDTMF(n)}setIsMuted(t){this.muted=t,this.context.emit("changeIsMuted",t)}processMute(t){const n=this.currentActiveRoomId;this.setIsMuted(t),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!t),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:n,automatic:a}){const o=this.extendedCalls[t];if(!o)return;o._automaticHold=a??!1;const s=new Promise((r,d)=>{const h=setTimeout(()=>{d(new Error("Hold operation timeout"))},5e3),_=()=>{clearTimeout(h),o.putOnHoldTimestamp=n?Date.now():void 0,r()},g=T=>{clearTimeout(h),d(T)};try{n?(this.stopSessionVad(o._id),o.hold({},_)):o.unhold({},_)}catch(T){g(T)}});try{await s,this.updateCall(o);const r=Object.values(this.extendedCalls).filter(d=>d.roomId===o.roomId&&(n?t!==d._id:!0));r.length>1&&await this.doConference(r)}catch(r){throw console.error("Hold operation failed:",r),r}}holdCall(t,n=!1){return this.processHold({callId:t,automatic:n,toHold:!0})}unholdCall(t){return this.processHold({callId:t,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(t=>t.direction==="outgoing"&&t.status===Kv).forEach(t=>this.terminateCall(t._id))}answerCall(t){const n=this.extendedCalls[t];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setActiveRoom(n.roomId),n.connection.addEventListener("track",a=>{this.triggerAddStream(a,n)})}async moveCall(t,n){this.updateCallStatus({callId:t,isMoving:!0}),await this.processRoomChange({callId:t,roomId:n}),this.updateCallStatus({callId:t,isMoving:!1})}updateCall(t){this.activeCalls[t._id]=gh(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const a={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...a}},this.context.emit("updateRoom",{room:a,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const n=/answer-after=0/,o=t.request.getHeader("Call-Info");return o&&n.test(o)}addCall(t,n=!0){this.activeCalls={...this.activeCalls,[t._id]:gh(t)},this.extendedCalls[t._id]=t,n&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(t){this.callStatus={...this.callStatus,[t]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(t){const a={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(a.isMoving=t.isMoving),t.isTransferring!==void 0&&(a.isTransferring=t.isTransferring),t.isMerging!==void 0&&(a.isMerging=t.isMerging),t.isTransferred!==void 0&&(a.isTransferred=t.isTransferred),this.callStatus={...this.callStatus,[t.callId]:{...a}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(t){const n={...this.callStatus};delete n[t],this.callStatus={...n},this.context.emit("changeCallStatus",this.callStatus)}addRoom(t){this.activeRooms={...this.activeRooms,[t.roomId]:t},this.context.emit("addRoom",{room:t,roomList:this.activeRooms})}async setupActiveStream(){const t=await Au(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);t.getTracks().forEach(n=>n.enabled=!this.isMuted),await this.setActiveStream(t)}async getActiveStream(){const t=await Au(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return t.getTracks().forEach(n=>n.enabled=!this.isMuted),await this.setActiveStream(t),t}async setMicrophone(t){if(!this.getInputDeviceList.find(({deviceId:a})=>a===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async a=>{await this.setupActiveStream();const o=this.activeStream;a.connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.updateCall(a)}):await this.doConference(n)}async setActiveStream(t){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(t,"origin"),this.activeStreamValue=t,this.context.emit("changeActiveStream",t)}async setSpeaker(t){if(!this.getOutputDeviceList.find(({deviceId:o})=>o===t))return;this.setSelectedOutputDevice(t);const n=Object.values(this.extendedCalls);if(n.length===0)return;const a=n.filter(o=>o.roomId===this.currentActiveRoomId);a.length===1?n.forEach(o=>{var s;(s=o.audioTag)==null||s.setSinkId(t),this.updateCall(o)}):await this.doConference(a)}removeRoom(t){const n={...this.activeRooms},a={...n[t]};delete n[t],this.activeRooms={...n},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(t){t!==void 0&&Object.values(this.extendedCalls).filter(n=>n.roomId===t).length===0&&(this.removeRoom(t),this.currentActiveRoomId===t&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(t){this.muted?t.mute({audio:!0}):t.unmute({audio:!0})}startNoiseMonitor({sessionId:t,stream:n,onNoiseDetected:a,onNoiseStop:o}){const s=new AudioContext,r=s.createMediaStreamSource(n.clone()),d=s.createAnalyser();d.fftSize=1024;const h=new Float32Array(d.fftSize);r.connect(d);const _=[];this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),this.vadIntervals[t]=null),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),this.vadMrsIntervals[t]=null),this.vadMrsIntervals[t]=setInterval(()=>{d.getFloatTimeDomainData(h);const g=YT(h);_.push(g);const T=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);_.length>T&&_.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[t]=setInterval(()=>{if(_.length===0)return;const g=_.reduce((E,A)=>E+A,0)/_.length,T=this.vadSessionsState[t],S=g>this.noiseReduction.noiseThreshold;T.isSpeaking||(S&&T.currentMode==="clean"?(T.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!0}),a()):!S&&T.currentMode==="noisy"&&(T.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!1}),o()))},this.noiseReduction.noiseCheckInterval)}async processVAD(t,n){const a=n.clone();this.stopSessionVad(t._id),this.vadSessionsState[t._id]={currentMode:"clean",isSpeaking:!1};const o=await this.managedAudioContext.getContext(),s=await JT(a,o,150);let r=!1;const d=await this.MicVAD.new({getStream:()=>new Promise(h=>h(a)),...Bv,...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(!r){if(r=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){t.connection.getSenders()[0]&&t.connection.getSenders()[0].replaceTrack(s.stream.getAudioTracks()[0]);return}this.startNoiseMonitor({sessionId:t._id,stream:a,onNoiseDetected:async()=>{var h;console.log("Replace track with Vad Controlled"),await((h=t.connection.getSenders()[0])==null?void 0:h.replaceTrack(s.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const h=t.connection.getSenders()[0];h&&h.track&&h.transport&&h.transport.state!=="closed"&&h.transport.state!=="failed"&&(console.log("Replace track with Original"),await h.replaceTrack(a.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var h;console.log("🎤 Speech started"),s.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((h=t.connection.getSenders()[0])==null||h.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!0},onSpeechEnd:()=>{var h;console.log("🛑 Speech end"),s.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((h=t.connection.getSenders()[0])==null||h.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!1}});this.vadSessions[t._id]&&(this.vadSessions[t._id].pause(),delete this.vadSessions[t._id]),this.vadSessions[t._id]=d,d.start()}stopSessionVad(t){this.vadSessions[t]&&(this.vadSessions[t].pause(),delete this.vadSessions[t]),this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),delete this.vadIntervals[t]),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),delete this.vadMrsIntervals[t]),this.vadSessionsState[t]&&delete this.vadSessionsState[t]}async roomReconfigure(t){var o;if(t===void 0)return;const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t),a=this.currentActiveRoomId===t;if(n.forEach((s,r)=>{if(s.audioTag){s.connection.getReceivers().forEach(h=>{h.track.enabled=!s.localMuted}),a&&this.muteReconfigure(s);const d=!a;s.audioTag.muted=d,this.updateCall(s)}}),n.length===0){!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t),this.deleteRoomIfEmpty(t);return}if(n.length===1&&!a){const s=n[0];s.isOnHold().local||await this.holdCall(s._id,!0),!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}if(n.length===1&&a){const s=n[0];s.isOnHold().local&&s._automaticHold&&await this.unholdCall(s._id);const h=(((o=s.connection)==null?void 0:o.getSenders())||[])[0];if(s.connection&&h)try{await this.setupActiveStream();const g=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(n[0],g);const T=g.getTracks();await h.replaceTrack(T[0]),this.muteReconfigure(s)}catch(g){console.error(g)}!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}n.length>1&&await this.doConference(n)}async doConference(t){if(t.length===0)return;const n=t[0].roomId,a=this.currentActiveRoomId===n;if(t.find(h=>h.roomId!==n))return;const s=await this.managedAudioContext.getContext();if(s.state!=="running"){console.error(`[doConference] ERROR: AudioContext is not running! State: ${s.state}`);return}await this.cleanupConferenceNodes(n),this.conferenceNodes[n]={sources:new Map,destinations:new Map,gains:new Map};const r=this.conferenceNodes[n],d=new Map;t.forEach((h,_)=>{h&&h.connection&&h.connection.getReceivers().forEach((T,S)=>{var C,R,k;T.track.enabled=!h.localMuted;const E=(C=T.track)==null?void 0:C.id;(R=T.track)==null||R.readyState,(k=T.track)==null||k.kind;const A=`${h._id}-${E}`;T.track&&T.track.readyState==="live"&&d.set(A,T.track)})}),await this.setupActiveStream(),await zT.forEach(t,async(h,_)=>{if(!h||!h.connection)return;const g=s.createMediaStreamDestination();r.destinations.set(h._id,g);let T=0;if(d.forEach((C,R)=>{if(!R.startsWith(h._id))try{const k=s.createMediaStreamSource(new MediaStream([C])),M=s.createGain(),ie=`${h._id}-${R}`;k.connect(M),M.connect(g),r.sources.set(ie,k),r.gains.set(ie,M),T++}catch(k){console.error(k)}}),a&&this.activeStreamValue)try{const C=this.activeStream,R=s.createMediaStreamSource(C),k=s.createGain(),M=`${h._id}-local`;R.connect(k),k.connect(g),r.sources.set(M,R),r.gains.set(M,k)}catch(C){console.error(C)}else a&&console.error(`Host room but no activeStreamValue - skipping host microphone for session ${h._id}`);const E=h.connection.getSenders()[0],A=g.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(h,g.stream),E&&A[0])try{await E.replaceTrack(A[0]),this.muteReconfigure(h)}catch(C){console.error(C)}})}processCallerMute(t,n){const a=this.extendedCalls[t];a&&a.connection.getReceivers().length&&(a.localMuted=n,a.connection.getReceivers().forEach(o=>{o.track.enabled=!n}),this.updateCall(a))}muteCaller(t){this.processCallerMute(t,!0)}unmuteCaller(t){this.processCallerMute(t,!1)}terminateCall(t){const n=this.extendedCalls[t];n._status===4?n.terminate({status_code:603,reason_phrase:"Decline"}):n._status!==8&&n.terminate()}transferCall(t,n){if(n.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[t];if(!a._is_confirmed&&!a._is_canceled){const o=`sip:${n}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${o}`]});return}this.updateCallStatus({callId:t,isTransferring:!0,isTransferred:!1}),a.refer(`sip:${n}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(a)}mergeCall(t){const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(n.length!==2)return;const a=n[0],o=n[1];!a||!o||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:o._id,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a))}mergeCallByIds(t,n){const a=Object.values(this.extendedCalls).find(s=>s._id===t),o=Object.values(this.extendedCalls).find(s=>s._id===n);if(!a||!o)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:n,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a)}setDND(t){this.isDNDEnabled=t,this.context.emit("changeIsDND",t)}setCallWaiting(t){this.isCallWaitingEnabled=t,this.context.emit("changeIsCallWaiting",t)}startCallTimer(t){this.removeTimeInterval(t);const n={callId:t,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(n);const a=setInterval(()=>{const o={...this.callTime[t]},s=KT(o);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,a)}async setActiveRoom(t){const n=this.currentActiveRoomId;t!==n&&(this.currentActiveRoomId=t,await this.roomReconfigure(n),await this.roomReconfigure(t))}getNewRoomId(){const t=Object.keys(this.activeRooms);return t.length===0?1:parseInt(t.sort()[t.length-1])+1}async setupCall(t){var _,g;const n=t.session;if(this.getActiveCalls[n.id]!==void 0)return;const o=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:o};if(n.direction==="incoming")this.context.logger.log("New incoming call from",(g=(_=n._remote_identity)==null?void 0:_._uri)==null?void 0:g._user),s.incomingInProgress=!0,this.context.subscribe(Xt.CALL_CONFIRMED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.startCallTimer(n.id))}),this.context.subscribe(Xt.CALL_FAILED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.deleteRoomIfEmpty(o))});else if(n.direction==="outgoing"){const T=S=>{S.response&&S.response.status_code===XT.SESSION_PROGRESS&&(this.startCallTimer(n.id),n.off("progress",T))};n.on("progress",T),n.once("confirmed",()=>{this.startCallTimer(n.id)})}const r=n,d=this.hasAutoAnswerHeaders(t),h=r.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);r.roomId=o,r.localMuted=!1,r.autoAnswer=h,h?this.addCall(r,!1):this.addCall(r),this.addCallStatus(n.id),this.addRoom(s),h&&this.answerCall(r._id)}removeCall(t){const n={...this.activeCalls};delete n[t],this.activeCalls={...n};const a={...this.extendedCalls};delete a[t],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(t){const n=this.extendedCalls[t._id];if(!n)return;this.stopVUMeter("origin"),this.stopVUMeter(t._id);const a=n.roomId;this.removeCall(t._id),this.roomReconfigure(a).then(()=>{}).catch(o=>{console.error("Error reconfiguring room after call removal:",o)})}shouldTerminateNewSession(t){if(t.session.direction==="outgoing")return!1;const a=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||a}async newRTCSessionCallback(t){const n=t.session;if(this.shouldTerminateNewSession(t)){n.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Xt.NEW_CALL,session:n,event:t}),n.on("ended",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session ended for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:n,event:a}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(n._id);const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("progress",a=>{var o,s;this.context.logger.log("Session in progress for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:n,event:a})}),n.on("failed",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session failed for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:n,event:a}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(n._id),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("confirmed",a=>{var o,s;this.context.logger.log("Session confirmed for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(t),n.direction==="outgoing"){const a=this.getActiveCalls[n.id].roomId;await this.setActiveRoom(a)}}setMuteWhenJoin(t){this.muteWhenJoinEnabled=t,this.context.emit("changeMuteWhenJoin",t)}setMicrophoneSensitivity(t){if(t<0||t>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=t,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(t){this.speakerVolumeValue=t,Object.values(this.extendedCalls).forEach(n=>{n.audioTag&&(n.audioTag.volume=t,this.updateCall(n))})}setAutoAnswer(t){this.isAutoAnswer=t}setSelectedInputDevice(t){localStorage.setItem(Ia.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(Ia.SELECTED_OUTPUT_DEVICE,t),this.selectedMediaDevices.output=t,this.context.emit("changeActiveOutputMediaDevice",t)}setCallMetrics(t){const n={...t};delete n.callId,this.callMetrics={...this.callMetrics,[t.callId]:n},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(t){const n={...this.callMetrics};delete n[t],this.callMetrics={...n},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(t){const n=new Vv(this.metricConfig),a=n.createProbe(t.connection,{cid:t._id}),o=[];let s;a.onreport=r=>{Object.entries(r.audio).forEach(([_,g])=>{g.direction==="inbound"&&!o.includes(_)&&(o.push(_),s=_)});const d=r.audio[s];if(!d)return;const h=jv(d,qv);h.callId=t._id,this.setCallMetrics(h)},this.context.subscribe(Xt.CALL_ENDED,r=>{r._id===t._id&&n.stopAllProbes()}),n.startAllProbes()}async setupVUMeter(t,n){await this.VUMeter.start(await this.managedAudioContext.getContext(),t,n)}stopVUMeter(t){this.VUMeter.stop(t)}async setupStream(){try{const t=Date.now(),n=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((o,s)=>{o.stop()}),this.initialStreamValue=null),this.initialStreamValue=n}catch(t){throw t}}async triggerAddStream(t,n){const a=this.muteWhenJoin||this.isMuted;this.setIsMuted(a),this.initialStreamValue||await this.setupStream();const o=await this.managedAudioContext.getContext(),s=await Au(o,this.initialStreamValue,this.microphoneInputLevel*2),r=this.isMuted||this.muteWhenJoin;s.getTracks().forEach(S=>{S.enabled=!r}),await this.setActiveStream(s),await n.connection.getSenders()[0].replaceTrack(s.getTracks()[0]);const _=new MediaStream([t.track]);!Object.values(this.extendedCalls).find(S=>S.audioTag&&S.audioTag.id===n._id)&&UT(_,n,this.selectedOutputDevice,this.speakerVolume);const T=n.roomId===this.currentActiveRoomId;n.audioTag&&(n.audioTag.muted=!T),await this.setupVUMeter(_,n._id),this.getCallQuality(n),this.updateCall(n),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(n,s)}initCall(t,n,a=!1){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${t}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=o.id,n&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),a)){const s=Object.values(this.extendedCalls).filter(r=>r.roomId===this.currentActiveRoomId&&r._id!==o.id);for(const r of s)this.holdCall(r._id,!0)}o.connection.addEventListener("track",s=>{this.triggerAddStream(s,o)})}async processRoomChange({callId:t,roomId:n}){const a=this.extendedCalls[t];if(!a)return;const o=a.roomId;a.roomId=n,this.updateCall(a),await this.roomReconfigure(o),await this.roomReconfigure(n)}}class Jv{constructor(t){this.context=t}get sipOptions(){return{...this.context.options.sipOptions}}initCall(t,n){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${t}@${this.context.sipDomain}`,n,this.sipOptions)}stop(t={}){this.context.terminateJanusSessions(t)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(t){this.context.changeMediaConstraints(t)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class zv{constructor(t){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=t,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(t){const n=this.extendedMessages[t];this.updateMSRPSession(n)}updateMSRPSession(t){this.activeMessages[t._id]=Th(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:Th(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,n){const a=this.msrpHistory[n.id]||[];a.push(t),this.msrpHistory={...this.msrpHistory,[n.id]:[...a]},this.context.emit("newMSRPMessage",{message:t,session:n})}messageTerminate(t){const n=this.extendedMessages[t];n._status!==8&&n.terminate()}addMessageSession(t){if(!t._id||this.getActiveMessages[t._id]!==void 0)return;const a=t;this.addMMSRPSession(a)}triggerMSRPListener({listenerType:t,session:n,event:a}){const o=this.context.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}removeMMSRPSession(t){const n={...this.activeMessages};delete n[t],this.activeMessages={...n};const a={...this.extendedMessages};delete a[t],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(t){this.removeMMSRPSession(t._id)}newMSRPSessionCallback(t){t.session._id||(t.session._id=t.request.call_id+t.request.from._parameters.tag);const n=t.session;n.on("ended",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("failed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateMSRPSession(n)}),n.on("newMessage",a=>{this.addMSRPMessage(a,n)}),this.addMessageSession(n)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,n,a){if(t.length===0)return console.error("Target must be a valid string");const o=this.context.startMSRP(t,a);o.on("active",()=>{this.addMessageSession(o),o.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,n){const a=this.extendedMessages[t];if(!a)throw new Error(`MSRP session with id ${t} doesn't exist!`);a.sendMSRP(n)}}const ba={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Ph{constructor(t){this.opensips=null,this.session=null,this.name=null,this.name=t}setOpensips(t){this.opensips=t}setSession(t){this.session=t}kill(){this.opensips.kill(this.name)}}class kh extends Ph{constructor(t,n){super(t),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=n}connect(t={}){this.opaqueId=this.session.generateOpaqueId();const n=Pe.cloneArray(t.extraHeaders),a={from_tag:this.session._from_tag};t.fromUserName&&(a.from_uri=new ln("sip",t.fromUserName,this.session._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(a.from_display_name=t.fromDisplayName),n.push(`Contact: ${this.session._contact}`),n.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&n.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Tt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,n),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 t;this._connection.onicecandidate=n=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||n.candidate&&(this._candidates.push(n.candidate),clearTimeout(t),t=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(t){t.forEach(n=>{this._connection.addTrack(n)})}async _sendInitialRequest(){const t=new Wr(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const n={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(n),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},o=JSON.stringify(a);this._request.body=o,t.send()}_receiveInviteResponse(t){if(this._publisherSubscribeSent||!t.body)return;const n=JSON.parse(t.body);this.handleId=n.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},o=[this.session.getPTypeHeader(Pt.PUBLISHER)];this.session.sendRequest(H.SUBSCRIBE,{extraHeaders:o,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async s=>{var r,d,h,_;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((d=(r=g.plugindata)==null?void 0:r.data)==null?void 0:d.videoroom)==="joined"&&this.session.myFeedList.push(g.plugindata.data.id),(_=(h=g.plugindata)==null?void 0:h.data)!=null&&_.publishers&&this.session.receivePublishers(g)}catch(g){console.error(g)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(t){const n=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handleId,session_id:this.session.session_id})),o={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...t},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...n]},s=["Content-Type: application/json",this.session.getPTypeHeader(Pt.ICE)];this.session.sendRequest(H.INFO,{extraHeaders:s,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async r=>{this._configureSent=!0;const h=r.data.split(`\r
|
|
159
159
|
`),_=h[h.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(Pt.DETACH)];this.session.sendRequest(H.INFO,{extraHeaders:n,body:JSON.stringify(t)}),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 t=this._connection.getSenders();t.forEach(n=>{const a=n.track;a&&a.stop()}),t.forEach(n=>{this._connection.removeTrack(n)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Mh extends Ph{constructor(t,n,a={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=n}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const n=await this.start(t);return this.running=!0,n}return t}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 Xv extends RT{constructor(t,n){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const a={...t.configuration,sockets:t.socketInterfaces.map(o=>new WT.WebSocketInterface(o))};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=[],t.pnExtraHeaders&&Object.keys(t.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(t.pnExtraHeaders),this.options=t,this.modules=t.modules,t.configuration.reconnectionAttemptsLimit&&(this.reconnectionAttemptsLimit=t.configuration.reconnectionAttemptsLimit),n&&xT(n)&&(this.logger=n)}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(ba.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(t,n){return super.on(t,n)}off(t,n){return super.off(t,n)}emit(t,n){return super.emit(t,n)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(n=>n.name===t.name)||this.processStreamPlugins.find(n=>n.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof kh)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof Mh)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(n=>n.name===t)||this.processStreamPlugins.find(n=>n.name===t)}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(ba.AUDIO)&&(this.audio=new Yv(this)),this.modules.includes(ba.MSRP)&&(this.msrp=new zv(this)),this.modules.includes(ba.VIDEO)&&(this.video=new Jv(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(t,n){const o=!this.listenersList[t]||!this.listenersList[t].length?[n]:[...this.listenersList[t],n];this.listenersList={...this.listenersList,[t]:o}}removeIListener(t){const n={...this.listenersList};delete n[t],this.listenersList={...n}}triggerListener({listenerType:t,session:n,event:a}){const o=this.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}setInitialized(t){this.initialized=t,this.emit("ready",t)}setConnected(t){this.connected=t,this.emit("connection",t)}setReconnecting(t){this.isReconnecting=t,this.emit("reconnecting",t)}}return Wt.BaseNewStreamPlugin=kh,Wt.BaseProcessStreamPlugin=Mh,Wt.default=Xv,Object.defineProperties(Wt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),Wt}({});
|