opensips-js-vue 0.1.26 → 0.1.27

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.
@@ -155,7 +155,7 @@ a=accept-types:text/plain text/html
155
155
  a=path:${n.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization_user}.${this._ua._configuration.realm}:2856/${this.auth_id};ws
156
156
  `),this._newMSRPSession("local",this._request),this._from_tag||(this._from_tag=this._request.from._parameters.tag),this._id=this._request.call_id+this._from_tag,new sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:c=>{this.onTransportError(),console.log(c)},onAuthenticated:c=>{this._request=c},onReceiveResponse:c=>{this._receiveInviteResponse(c),c.status_code===200&&(c.parseSDP(!0),this._status=dt.STATUS_CONFIRMED,this.target_addr=c.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=dt.STATUS_INVITE_SENT}terminate(n={}){const r=n.cause||ue.causes.BYE,a=kt.cloneArray(n.extraHeaders),c=n.body;let e,_=n.status_code,v=n.reason_phrase;if(this._status===dt.STATUS_TERMINATED)throw new di.InvalidStateError(this._status);switch(this.status="terminated",this._status){case dt.STATUS_NULL:case dt.STATUS_INVITE_SENT:case dt.STATUS_1XX_RECEIVED:if(_&&(_<200||_>=700))throw new TypeError(`Invalid status_code: ${_}`);_&&(v=v||ue.REASON_PHRASE[_]||"",e=`SIP ;cause=${_} ;text="${v}"`),this._status===dt.STATUS_NULL||this._status===dt.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=e):this._status===dt.STATUS_1XX_RECEIVED&&this._request.cancel(e),this._status=dt.STATUS_CANCELED,this._failed("local",null,ue.causes.CANCELED);break;case dt.STATUS_WAITING_FOR_ANSWER:case dt.STATUS_ANSWERED:if(_=_||480,_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);this._request.reply(_,v,a,c),this._failed("local",null,ue.causes.REJECTED);break;case dt.STATUS_WAITING_FOR_ACK:case dt.STATUS_CONFIRMED:if(v=n.reason_phrase||ue.REASON_PHRASE[_]||"",_&&(_<200||_>=700))throw new TypeError(`Invalid status_code: ${_}`);if(_&&a.push(`Reason: SIP ;cause=${_}; text="${v}"`),this._status===dt.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ir.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:C})=>{C===ue.ACK&&(this.sendRequest(ue.BYE,{extraHeaders:a,body:c}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ir.C.STATUS_TERMINATED&&(this.sendRequest(ue.BYE,{extraHeaders:a,body:c}),d.terminate())}),this._ended("local",null,r),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest(ue.BYE,{extraHeaders:a,body:c}),this._ended("local",null,r)}}sendRequest(n,r){return this._dialog.sendRequest(n,r)}authenticate(n){this.status="auth";let r=new ro("");r.method="AUTH",r.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),r.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),n&&r.addHeader("Authorization",n.toString());let a=r.toString(),c=[];for(var e=0;e<a.length;e++)c.push(a.charCodeAt(e).toString(16));this._connection.send(r.toString())}onmessage(n){const r=new ro(n.data);if(this.status==="auth"&&r.code===401){const a=this.parseAuth(r.getHeader("WWW-Authenticate")),c=new $E(this.credentials);c.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},a,kt.createRandomToken(12)),this.authenticate(c)}this.status==="auth"&&r.code===200&&this._direction==="outgoing"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.inviteParty(r)):this.status==="auth"&&r.code===200&&this._direction==="incoming"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.acceptParty(r),this.emit("confirmed")):r.method==="SEND"&&(this._sendOk(r),this._sendReport(r),r.direction="incoming",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)),r.code===480&&this._close()}onclose(){console.log("close")}onopen(){const n=new RTCPeerConnection({iceServers:[]});n.createDataChannel(""),n.createOffer().then(n.setLocalDescription.bind(n)),n.onicecandidate=r=>{if(!r||!r.candidate||!r.candidate.candidate)return;const a=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,c=r.candidate.candidate.match(a);this.my_ip=c&&c[1],n.onicecandidate=()=>{},this.authenticate(null)}}onerror(n){console.log(n)}_receiveInviteResponse(n){if(console.log("resp0000000000000",n),this._dialog&&n.status_code>=200&&n.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){this.sendRequest(ue.ACK);return}else{const r=new Ru(this,n,"UAC");if(r.error!==void 0){console.log(r.error);return}this.sendRequest(ue.ACK),this.sendRequest(ue.BYE);return}if(this._is_canceled){n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&this._acceptAndTerminate(n);return}if(!(this._status!==dt.STATUS_INVITE_SENT&&this._status!==dt.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(n.status_code):this._status=dt.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(!n.to_tag){console.log("1xx response received without to tag");break}if(n.hasHeader("contact")&&!this._createDialog(n,"UAC",!0))break;if(this._status=dt.STATUS_1XX_RECEIVED,!n.body){this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",n)).catch(c=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(console.log("maybe here???"),this._status=dt.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,ue.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",n,ue.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(n,"UAC"))break;const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r),new RTCSessionDescription({type:"answer",sdp:r.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(a=>this._connection.setLocalDescription(a)).catch(a=>{this._acceptAndTerminate(n,500,a.toString()),console.log("failed 4"),this._failed("local",n,ue.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(n),this._accepted("remote",n),this.sendRequest(ue.ACK),this._confirmed("local",null)});break}default:{const r=kt.sipErrorCause(n.status_code);console.log("failed 5"),this._failed("remote",n,r)}}}sendMSRP(n){const r=new ro("");let a="";this.my_addr[1]&&(a=this.my_addr[1]),this.target_addr[1]&&(a+=" "+this.target_addr[1]),this.target_addr[0]&&(a+=" "+this.target_addr[0]),r.method="SEND",r.addHeader("To-Path",a),r.addHeader("From-Path",`${this.my_addr[0]}`),r.addHeader("Message-ID",kt.createRandomToken(10)),r.addHeader("Byte-Range","1-25/25"),r.addHeader("Content-Type","text/plain"),r.addHeader("Success-Report","yes"),r.addHeader("Failure-Report","yes"),r.body=n;let c=r.toString();console.log(c);let e=[];for(var _=0;_<c.length;_++)e.push(c.charCodeAt(_).toString(16));console.log(e),this._connection.send(r.toString()),r.direction="outgoing",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(n){let r=n.ident,a=n.getHeader("Message-ID"),c=new ro("");c.method="200 OK",c.addHeader("To-Path",`${this.my_addr[1]}`),c.addHeader("From-Path",`${this.my_addr[0]}`),c.addHeader("Message-ID",a),c.ident=r;let e=c.toString();console.log(e);let _=[];for(var v=0;v<e.length;v++)_.push(e.charCodeAt(v).toString(16));console.log(_),this._connection.send(c.toString())}_sendReport(n){let r=n.ident,a=n.getHeader("Message-ID"),c=new ro("");c.method="REPORT",c.addHeader("To-Path",`${n.getHeader("From-Path")}`),c.addHeader("From-Path",`${this.my_addr[0]}`),c.addHeader("Message-ID",a),c.addHeader("Byte-Range","1-25/25"),c.addHeader("Status","000 200 OK"),c.ident=r;let e=c.toString();console.log(e);let _=[];for(var v=0;v<e.length;v++)_.push(e.charCodeAt(v).toString(16));console.log(_),this._connection.send(c.toString())}parseAuth(n){const r={},a=n.replace("Digest","").split(",");for(const c of a){const e=c.trim().split("=");r[e[0]]=e[1].match('^"(.+)"$')[1]}return r}init_incoming(n,r){let a;const c=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&c!=="application/sdp"){n.reply(415);return}if(this._status=dt.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(a=n.getHeader("expires")*1e3),n.to_tag=kt.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=dt.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),console.log("failed 6"),this._failed("local",null,ue.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===dt.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),console.log("failed 7"),this._failed("system",null,ue.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),n.parseSDP(!0),this.target_addr=n.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",n),this._status!==dt.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(n,r,a){this.emit("_failed",{originator:n,message:r||null,cause:a}),this._close(),this.emit("failed",{originator:n,message:r||null,cause:a})}_close(){if(console.log("CLOSE SESSION"),this._status!==dt.STATUS_TERMINATED){if(this._status=dt.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){console.log("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyMSRPSession(this)}}_createDialog(n,r,a){const c=r==="UAS"?n.to_tag:n.from_tag,e=r==="UAS"?n.from_tag:n.to_tag,_=n.call_id+c+e;let v=this._earlyDialogs[_];if(a)return v?!0:(v=new Ru(this,n,r,Ru.C.STATUS_EARLY),v.error?(console.log("failed 8"),this._failed("remote",n,ue.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[_]=v,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,v)return v.update(n,r),this._dialog=v,delete this._earlyDialogs[_],!0;const d=new Ru(this,n,r);return d.error?(console.log("failed 9"),this._failed("remote",n,ue.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_newMSRPSession(n,r){this._ua.newMSRPSession(this,{originator:n,session:this,request:r})}_progress(n,r){this.emit("progress",{originator:n,response:r||null})}isEnded(){switch(this._status){case dt.STATUS_CANCELED:case dt.STATUS_TERMINATED:return!0;default:return!1}}_accepted(n,r){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,a){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:a})}_runKeepAliveTimer(){if(!this._sessionTimers||!this._sessionTimers.enabled||this._sessionTimers.running)return;if(this._sessionTimers.currentExpires||(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires||30),!this._sessionTimers.refresher){console.log("Not the refresher; waiting for remote keep-alive");return}const n=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.timer=setTimeout(()=>{if(this._connection.readyState===WebSocket.OPEN)try{this._sendKeepAlive(),console.log("Session timer: sending MSRP keep-alive")}catch(r){console.error("Failed to send keep-alive:",r)}this._sessionTimers.running=!1,this._runKeepAliveTimer()},n*1e3*.5)}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=ue.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runKeepAliveTimer()}receiveRequest(n){if(console.log("receiveRequest()"),n.method===ue.CANCEL)(this._status===dt.STATUS_WAITING_FOR_ANSWER||this._status===dt.STATUS_ANSWERED)&&(this._status=dt.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",n,ue.causes.CANCELED));else switch(n.method){case ue.ACK:if(this._status!==dt.STATUS_WAITING_FOR_ACK)return;if(this._status=dt.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:ue.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(c=>{this.terminate({cause:ue.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)})}else this._is_confirmed||this._confirmed("remote",n);break;case ue.BYE:this._status===dt.STATUS_CONFIRMED||this._status===dt.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,ue.causes.BYE)):this._status===dt.STATUS_INVITE_RECEIVED||this._status===dt.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,ue.causes.BYE)):n.reply(403,"Wrong Status");break;case ue.INVITE:this._status===dt.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case ue.INFO:this._status===dt.STATUS_1XX_RECEIVED||this._status===dt.STATUS_WAITING_FOR_ANSWER||this._status===dt.STATUS_ANSWERED||this._status===dt.STATUS_WAITING_FOR_ACK||this._status===dt.STATUS_CONFIRMED?(n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new _d(this).init_incoming(n):n.reply(415):n.reply(403,"Wrong Status");break;case ue.UPDATE:this._status===dt.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case ue.REFER:this._status===dt.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case ue.NOTIFY:this._status===dt.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ue.causes.CONNECTION_ERROR,cause:ue.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:ue.causes.REQUEST_TIMEOUT,cause:ue.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ue.causes.DIALOG_ERROR,cause:ue.causes.DIALOG_ERROR})}}var yA=Hr();const Dd=Qt(yA),Hu=new wu("Parser"),TA=(o,n)=>{let r,a,c=o.indexOf(`\r
157
157
  `);if(c===-1){Hu.warn("parseMessage() | no CRLF found, not a SIP message");return}const e=o.substring(0,c);let _=Dd.parse(e,"Request_Response");if(_===-1){Hu.warn(`parseMessage() | error parsing first line of SIP message: "${e}"`);return}else _.status_code?(r=new Za.IncomingResponse,r.status_code=_.status_code,r.reason_phrase=_.reason_phrase):(r=new Za.IncomingRequest(n),r.method=_.method,r.ruri=_.uri);r.data=o;let v=c+2;for(;;){if(c=bA(o,v),c===-2){a=v+2;break}else if(c===-1){Hu.warn("parseMessage() | malformed message");return}if(_=wA(r,o,v,c),_!==!0){Hu.warn("parseMessage() |",_.error);return}v=c+2}if(r.hasHeader("content-length")){const d=r.getHeader("content-length");r.body=o.substr(a,d)}else r.body=o.substring(a);return r};function bA(o,n){let r=n,a=0,c=0;if(o.substring(r,r+2).match(/(^\r\n)/))return-2;for(;a===0;){if(c=o.indexOf(`\r
158
- `,r),c===-1)return c;!o.substring(c+2,c+4).match(/(^\r\n)/)&&o.charAt(c+2).match(/(^\s+)/)?r=c+2:a=c}return a}function wA(o,n,r,a){let c;const e=n.indexOf(":",r),_=n.substring(r,e).trim(),v=n.substring(e+1,a).trim();switch(_.toLowerCase()){case"via":case"v":o.addHeader("via",v),o.getHeaders("via").length===1?(c=o.parseHeader("Via"),c&&(o.via=c,o.via_branch=c.branch)):c=0;break;case"from":case"f":o.setHeader("from",v),c=o.parseHeader("from"),c&&(o.from=c,o.from_tag=c.getParam("tag"));break;case"to":case"t":o.setHeader("to",v),c=o.parseHeader("to"),c&&(o.to=c,o.to_tag=c.getParam("tag"));break;case"record-route":if(c=Dd.parse(v,"Record_Route"),c===-1)c=void 0;else for(const d of c)o.addHeader("record-route",v.substring(d.possition,d.offset)),o.headers["Record-Route"][o.getHeaders("record-route").length-1].parsed=d.parsed;break;case"call-id":case"i":o.setHeader("call-id",v),c=o.parseHeader("call-id"),c&&(o.call_id=v);break;case"contact":case"m":if(c=Dd.parse(v,"Contact"),c===-1)c=void 0;else for(const d of c)o.addHeader("contact",v.substring(d.possition,d.offset)),o.headers.Contact[o.getHeaders("contact").length-1].parsed=d.parsed;break;case"content-length":case"l":o.setHeader("content-length",v),c=o.parseHeader("content-length");break;case"content-type":case"c":o.setHeader("content-type",v),c=o.parseHeader("content-type");break;case"cseq":o.setHeader("cseq",v),c=o.parseHeader("cseq"),c&&(o.cseq=c.value),o instanceof Za.IncomingResponse&&(o.method=c.method);break;case"max-forwards":o.setHeader("max-forwards",v),c=o.parseHeader("max-forwards");break;case"www-authenticate":o.setHeader("www-authenticate",v),c=o.parseHeader("www-authenticate");break;case"proxy-authenticate":o.setHeader("proxy-authenticate",v),c=o.parseHeader("proxy-authenticate");break;case"session-expires":case"x":o.setHeader("session-expires",v),c=o.parseHeader("session-expires"),c&&(o.session_expires=c.expires,o.session_expires_refresher=c.refresher);break;case"refer-to":case"r":o.setHeader("refer-to",v),c=o.parseHeader("refer-to"),c&&(o.refer_to=c);break;case"replaces":o.setHeader("replaces",v),c=o.parseHeader("replaces"),c&&(o.replaces=c);break;case"event":case"o":o.setHeader("event",v),c=o.parseHeader("event"),c&&(o.event=c);break;default:o.addHeader(_,v),c=0}return c===void 0?{error:`error parsing header "${_}"`}:!0}const SA={parseMessage:TA},_l=new wu("Registrator"),zu=10;class EA{constructor(n,r){this._reg_id=1,this._ua=n,this._transport=r,this._registrar=n.configuration.registrar_server,this._expires=n.configuration.register_expires,this._call_id=qs.createRandomToken(22),this._cseq=0,this._to_uri=n.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const a=this._contact.indexOf(">");if(a!==-1){const c=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=c}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(n){Array.isArray(n)||(n=[]),this._extraHeaders=n.slice()}setExtraContactParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){_l.debug("Register request in progress...");return}const n=this._extraHeaders.slice();n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),n.push(`Expires: ${this._expires}`);const r=new On.OutgoingRequest(ue.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n),a=new sl(this._ua,r,{onRequestTimeout:()=>{this._registrationFailure(null,ue.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,ue.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{if(c.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):{if(this._registering=!1,!c.hasHeader("Contact")){_l.debug("no Contact header in response to REGISTER, response ignored");break}const e=c.headers.Contact.reduce((C,S)=>C.concat(S.parsed),[]);let _=e.find(C=>this._sipInstance===C.getParam("+sip.instance")&&this._reg_id===parseInt(C.getParam("reg-id")));if(_||(_=e.find(C=>C.uri.user===this._ua.contact.uri.user)),!_){_l.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let v=_.getParam("expires");!v&&c.hasHeader("expires")&&(v=c.getHeader("expires")),v||(v=this._expires),v=Number(v),v<zu&&(v=zu);const d=v>64?v*1e3/2+Math.floor((v/2-32)*1e3*Math.random()):Math.floor(v*1e3/2);this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},d),_.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=_.getParam("temp-gruu").replace(/"/g,"")),_.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=_.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:c}));break}case/^423$/.test(c.status_code):{c.hasHeader("min-expires")?(this._expires=Number(c.getHeader("min-expires")),this._expires<zu&&(this._expires=zu),this.register()):(_l.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(c,ue.causes.SIP_FAILURE_CODE));break}default:{const e=qs.sipErrorCause(c.status_code);this._registrationFailure(c,e)}}}});this._registering=!0,a.send()}unregister(n={}){if(!this._registered){_l.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const r=this._extraHeaders.slice();n.all?r.push(`Contact: *${this._extraContactParams}`):r.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),r.push("Expires: 0");const a=new On.OutgoingRequest(ue.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r);new sl(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,ue.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,ue.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{switch(!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):this._unregistered(c);break;default:{const e=qs.sipErrorCause(c.status_code);this._unregistered(c,e)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(n,r){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:r}))}_unregistered(n,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:r||null})}}const un=console,fi={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},CA=dA;class AA extends CA{constructor(n){super(n),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this.optionsInterval=null,this.lastOptionsTimestamp=null,this.lastRegisterTimestamp=null,this._registrator=new EA(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(n,r){return super.call(n,r)}joinVideoCall(n,r,a){un.debug("call()");const c=new qu(this);return c.configureMedia({audio:!0,video:!0}),c.connect(n,r,a),c}startScreenShare(){un.debug("startScreenShare()");for(const n in this._janus_sessions)this._janus_sessions[n].connectScreenShare()}changeMediaConstraints(n){for(const r in this._janus_sessions)this._janus_sessions[r].changeMediaConstraints(n)}startBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].connectBlur()}stopBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].stopBlur()}_loadConfig(n){try{pl.load(this._configuration,n)}catch(e){throw e}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=qs.newUUID());let r;typeof window<"u"&&typeof window.document<"u"?r=window?.navigator.userAgent:typeof self<"u"&&self.navigator&&(r=self.navigator.userAgent),r+=" "+bt.USER_AGENT,this._configuration.user_agent=n.overrideUserAgent&&typeof n.overrideUserAgent=="function"?n.overrideUserAgent(r):r,n.onTransportCallback&&typeof n.onTransportCallback=="function"&&(this.onTransportCallback=n.onTransportCallback),this._configuration.jssip_id=qs.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new PC(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=IA.bind(this),this._transport.onconnect=RA.bind(this),this._transport.ondisconnect=xA.bind(this),this._transport.ondata=$A.bind(this)}catch(e){throw un.warn(e),new di.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ba("sip",qs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(e={}){const _=e.anonymous||null,v=e.outbound||null;let d="<";return _?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),v&&(_?!this.temp_gruu:!this.pub_gruu)&&(d+=";ob"),d+=">",d}};const c=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const e in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,e)&&(c.indexOf(e)!==-1?Object.defineProperty(this._configuration,e,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,e,{writable:!1,configurable:!1}));un.debug("configuration parameters after validation:");for(const e in this._configuration)if(Object.prototype.hasOwnProperty.call(pl.settings,e))switch(e){case"uri":case"registrar_server":un.debug(`- ${e}: ${this._configuration[e]}`);break;case"password":case"ha1":case"authorization_jwt":un.debug(`- ${e}: NOT SHOWN`);break;default:un.debug(`- ${e}: ${JSON.stringify(this._configuration[e])}`)}}newMSRPSession(n,r){n.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",r)}newJanusSession(n,r){this._janus_sessions[n.id]=n,this.newStreamPlugins.forEach(a=>{a.setSession(n)}),this.processStreamPlugins.forEach(a=>{a.setSession(n)}),this.emit("newJanusSession",r)}kill(){}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(n){var r,a,c,e;const _=n.method;if(n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){un.debug("Request-URI does not point to us"),n.method!==bt.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===bt.SIPS){n.reply_sl(416);return}if(Ir.checkTransaction(this,n))return;if(_===bt.INVITE?new Ir.InviteServerTransaction(this,this._transport,n):_!==bt.ACK&&_!==bt.CANCEL&&new Ir.NonInviteServerTransaction(this,this._transport,n),_===bt.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const C=Date.now(),S=this.lastOptionsTimestamp>C-35e3,R=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>C;S&&R&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){n.reply(200);return}new w_.Options(this).init_incoming(n)}else if(_===bt.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new w_.Message(this).init_incoming(n)}else if(_===bt.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let v,d;if(n.to_tag)if(v=this._findDialog(n.call_id,n.from_tag,n.to_tag),v)v.receiveRequest(n);else if(_===bt.NOTIFY)if(d=this._findSession(n),d)d.receiveRequest(n);else{if(n.body)try{const C=JSON.parse(n.body)||{};(a=(r=C.plugindata)==null?void 0:r.data)!=null&&a.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(C),(e=(c=C.plugindata)==null?void 0:c.data)!=null&&e.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(C.plugindata.data.unpublished)}catch(C){console.error(C)}n.reply(200)}else _!==bt.ACK&&n.reply(481);else switch(_){case bt.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const C=n.replaces;v=this._findDialog(C.call_id,C.from_tag,C.to_tag),v?(d=v.owner,d.isEnded()?n.reply(603):d.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(d=new kd(this),d.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(d=new bC(this),d.init_incoming(n));else un.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case bt.BYE:n.reply(481);break;case bt.CANCEL:d=this._findSession(n),d?d.receiveRequest(n):un.debug("received CANCEL request for a non existent session");break;case bt.ACK:break;case bt.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,r){un.debug("startMSRP()",r);const a=new kd(this);return a.connect(n),a}startJanus(n,r){un.debug("startJanus()",r);const a=new kd(this);return a.connect(n),a}terminateMSRPSessions(n){un.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(n)}terminateJanusSessions(n){un.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(n)}enableJanusAudio(n){un.debug("enableJanusAudio()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startAudio():this._janus_sessions[r].stopAudio())}enableJanusVideo(n){un.debug("enableJanusVideo()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startVideo():this._janus_sessions[r].stopVideo())}terminateAllSessions(){for(const n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){un.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch(r){console.error(r)}}}stop(n=!0){if(un.debug("stop()"),this._dynConfiguration={},this._status===fi.STATUS_USER_CLOSED){un.debug("UA already closed");return}this._registrator.close();const r=Object.keys(this._sessions).length;n&&this.terminateAllSessions();for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){un.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){un.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(c){console.error(c)}this._status=fi.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&r===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function IA(o){this.emit("connecting",o)}function RA(o){this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_READY,this._error=null,this.emit("connected",o),this._dynConfiguration.register&&this._registrator.register())}function xA(o){const n=["nict","ict","nist","ist"];for(const r of n)for(const a in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],a)&&this._transactions[r][a].onTransportError();this.emit("disconnected",o),this._registrator.onTransportClosed(),this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_NOT_READY,this._error=fi.NETWORK_ERROR)}function $A(o){const n=o.transport;let r=o.message;const a=r;if(r=SA.parseMessage(r,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(r,a),!!r&&!(this._status===fi.STATUS_USER_CLOSED&&r instanceof Za.IncomingRequest)&&QC(r,this,n)){if(r instanceof Za.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof Za.IncomingResponse){let c;switch(r.method){case bt.INVITE:if(c=this._transactions.ict[r.via_branch],c){const e=r.status_code;if((e===100||e===180||e===183)&&this.audio&&typeof this.audio.handleSipResponseForRingback=="function"){let _=null;if(c._session&&c._session.id)_=c._session.id;else if(r.call_id&&this._sessions){const v=Object.values(this._sessions).find(d=>d._id&&d._id.includes(r.call_id)||d.id&&d.id.includes(r.call_id)||d.call_id===r.call_id);v&&(v.id||v._id)&&(_=v.id||v._id)}else r.call_id&&(_=r.call_id);_&&this.audio.handleSipResponseForRingback(_,e)}c.receiveResponse(r)}break;case bt.ACK:break;default:c=this._transactions.nict[r.via_branch],c&&c.receiveResponse(r);break}}}}const OA=["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"],kA=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function yf(o){const n={};return OA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n.localHold=o._localHold,n}function Tf(o){const n={};return kA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n}async function Nd(o,n,r){const a=o.createMediaStreamSource(n),c=o.createMediaStreamDestination(),e=o.createGain();return a.connect(e),e.connect(c),e.gain.value=r,c.stream}function DA(o,n,r,a){if(bf())return;const c=document.createElement("audio");c.id=n._id,c.className="audioTag",c.srcObject=o,c.setSinkId(r),c.volume=a,c.play(),n.audioTag=c}function NA(o){if(o&&typeof o.log=="function"&&typeof o.warn=="function"&&typeof o.error=="function")return!0}function bf(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const MA=mn,UA=Hr(),Jn=new MA("WebSocketInterface");var PA=class{constructor(o){Jn.debug('new() [url:"%s"]',o),this._url=o,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=UA.parse(o,"absoluteURI");if(n===-1)throw Jn.warn(`invalid WebSocket URI: ${o}`),new TypeError(`Invalid argument: ${o}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Jn.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${o}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(o){this._via_transport=o.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Jn.debug("connect()"),this.isConnected()){Jn.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Jn.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Jn.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(o){this._onError(o)}}disconnect(){Jn.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(o){return Jn.debug("send()"),this.isConnected()?(this._ws.send(o),!0):(Jn.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){Jn.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:o,code:n,reason:r}){Jn.debug(`WebSocket ${this._url} closed`),o===!1&&Jn.debug("WebSocket abrupt disconnection"),this.ondisconnect(!o,n,r)}_onMessage({data:o}){Jn.debug("received WebSocket message"),this.ondata(o)}_onError(o){Jn.warn(`WebSocket ${this._url} error: `,o)}};const Md=Pl,LA=bt,qA=Ls,HA=xn(),zA=mf,FA=Ms(),BA=td(),VA=Hr(),jA=PA;Wa("JsSIP")("version %s",Md.version);var GA={C:LA,Exceptions:qA,Utils:HA,UA:zA,URI:FA,NameAddrHeader:BA,WebSocketInterface:jA,Grammar:VA,debug:Wa,get name(){return Md.title},get version(){return Md.version}};const WA=Qt(GA);function Ud(o){return o<10?`0${o}`:`${o}`}function KA(o){let n=o.hours||0,r=o.minutes||0,a=o.seconds||0;a++,a===60&&(a=0,r++,r===60&&(r=0,n++));const c=`${Ud(n)}:${Ud(r)}:${Ud(a)}`;return{seconds:a,minutes:r,hours:n,formatted:c}}function YA(o){let n=0;for(let r=0;r<o.length;r++)n+=o[r]*o[r];return Math.sqrt(n/o.length)}async function XA(o,n,r=150){const a=n.createMediaStreamSource(o),c=n.createDelay();c.delayTime.value=r/1e3;const e=n.createGain();e.gain.value=0;const _=n.createMediaStreamDestination();return a.connect(c).connect(e).connect(_),{stream:_.stream,setSpeaking:v=>{e.gain.value=v?1:0}}}var Mn={};Mn.forEach=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)if(c in o){const e=Promise.resolve(o[c]).then(_=>n.call(r||globalThis,_,c,o));a.push(e)}await Promise.all(a)},Mn.forEachSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)a in o&&await n.call(r||globalThis,await o[a],a,o)},Mn.map=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=Promise.resolve(o[c]).then(e=>n.call(r||globalThis,e,c,o)));return Promise.all(a)},Mn.mapSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=await n.call(r||globalThis,await o[c],c,o));return a},Mn.find=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a();let e=1;for(let _=0;_<o.length;_++){const v=d=>{d?a(o[_]):e===o.length&&a(),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(v).catch(c)}}),Mn.findSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return o[a]},Mn.findIndex=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(-1);let e=1;for(let _=0;_<o.length;_++){const v=d=>{d?a(_):e===o.length&&a(-1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(v).catch(c)}}),Mn.findIndexSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return a},Mn.some=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!1);let e=1;for(let _=0;_<o.length;_++){if(!(_ in o)){e++;continue}const v=d=>{d?a(!0):e===o.length&&a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(v).catch(c)}}),Mn.someSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&await n.call(r||globalThis,await o[a],a,o))return!0;return!1},Mn.every=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!0);let e=1;for(let _=0;_<o.length;_++){if(!(_ in o)){e++;continue}const v=d=>{d?e===o.length&&a(!0):a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(v).catch(c)}}),Mn.everySeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&!await n.call(r||globalThis,await o[a],a,o))return!1;return!0},Mn.filter=(o,n,r)=>new Promise(async(a,c)=>{const e=[];for(let v=0;v<o.length;v++)v in o&&(e[v]=Promise.resolve(o[v]).then(d=>n.call(r||globalThis,d,v,o)).catch(c));const _=[];for(let v=0;v<e.length;v++)await e[v]&&_.push(await o[v]);a(_)}),Mn.filterSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&await n.call(r||globalThis,await o[c],c,o)&&a.push(await o[c]);return a},Mn.reduce=async(o,n,r)=>{if(o.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let a,c;for(r!==void 0?(c=r,a=0):(c=o[0],a=1),a;a<o.length;a++)a in o&&(c=await n(await c,await o[a],a,o));return c};var wf={};(function(o){const n=Mn;Object.keys(n).forEach(r=>{const a=r.charAt(0).toUpperCase()+r.slice(1);o[`async${a}`]=async function(...c){return n[r](this,...c)}})})(wf);var JA=Object.assign(Mn,{instanceMethods:wf});const Br={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},Fu={TRYING:100,RINGING:180,SESSION_PROGRESS:183,OK:200,MOVED_TEMPORARILY:302,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,REQUEST_TIMEOUT:408,BUSY_HERE:486,REQUEST_TERMINATED:487,INTERNAL_SERVER_ERROR:500,SERVICE_UNAVAILABLE:503,BUSY_EVERYWHERE:600,DECLINE:603};var QA={exports:{}};(function(o){var n=function(r){var a=Object.prototype,c=a.hasOwnProperty,e=Object.defineProperty||function(Ee,ge,ie){Ee[ge]=ie.value},_,v=typeof Symbol=="function"?Symbol:{},d=v.iterator||"@@iterator",C=v.asyncIterator||"@@asyncIterator",S=v.toStringTag||"@@toStringTag";function R(Ee,ge,ie){return Object.defineProperty(Ee,ge,{value:ie,enumerable:!0,configurable:!0,writable:!0}),Ee[ge]}try{R({},"")}catch{R=function(Ee,ge,ie){return Ee[ge]=ie}}function D(Ee,ge,ie,st){var We=ge&&ge.prototype instanceof Re?ge:Re,ht=Object.create(We.prototype),It=new we(st||[]);return e(ht,"_invoke",{value:le(Ee,ie,It)}),ht}r.wrap=D;function H(Ee,ge,ie){try{return{type:"normal",arg:Ee.call(ge,ie)}}catch(st){return{type:"throw",arg:st}}}var K="suspendedStart",F="suspendedYield",W="executing",se="completed",Z={};function Re(){}function X(){}function te(){}var ye={};R(ye,d,function(){return this});var Oe=Object.getPrototypeOf,Q=Oe&&Oe(Oe(xe([])));Q&&Q!==a&&c.call(Q,d)&&(ye=Q);var oe=te.prototype=Re.prototype=Object.create(ye);X.prototype=te,e(oe,"constructor",{value:te,configurable:!0}),e(te,"constructor",{value:X,configurable:!0}),X.displayName=R(te,S,"GeneratorFunction");function me(Ee){["next","throw","return"].forEach(function(ge){R(Ee,ge,function(ie){return this._invoke(ge,ie)})})}r.isGeneratorFunction=function(Ee){var ge=typeof Ee=="function"&&Ee.constructor;return ge?ge===X||(ge.displayName||ge.name)==="GeneratorFunction":!1},r.mark=function(Ee){return Object.setPrototypeOf?Object.setPrototypeOf(Ee,te):(Ee.__proto__=te,R(Ee,S,"GeneratorFunction")),Ee.prototype=Object.create(oe),Ee},r.awrap=function(Ee){return{__await:Ee}};function _e(Ee,ge){function ie(ht,It,qe,Ue){var wt=H(Ee[ht],Ee,It);if(wt.type==="throw")Ue(wt.arg);else{var Yt=wt.arg,Xe=Yt.value;return Xe&&typeof Xe=="object"&&c.call(Xe,"__await")?ge.resolve(Xe.__await).then(function(Je){ie("next",Je,qe,Ue)},function(Je){ie("throw",Je,qe,Ue)}):ge.resolve(Xe).then(function(Je){Yt.value=Je,qe(Yt)},function(Je){return ie("throw",Je,qe,Ue)})}}var st;function We(ht,It){function qe(){return new ge(function(Ue,wt){ie(ht,It,Ue,wt)})}return st=st?st.then(qe,qe):qe()}e(this,"_invoke",{value:We})}me(_e.prototype),R(_e.prototype,C,function(){return this}),r.AsyncIterator=_e,r.async=function(Ee,ge,ie,st,We){We===void 0&&(We=Promise);var ht=new _e(D(Ee,ge,ie,st),We);return r.isGeneratorFunction(ge)?ht:ht.next().then(function(It){return It.done?It.value:ht.next()})};function le(Ee,ge,ie){var st=K;return function(We,ht){if(st===W)throw new Error("Generator is already running");if(st===se){if(We==="throw")throw ht;return Dt()}for(ie.method=We,ie.arg=ht;;){var It=ie.delegate;if(It){var qe=de(It,ie);if(qe){if(qe===Z)continue;return qe}}if(ie.method==="next")ie.sent=ie._sent=ie.arg;else if(ie.method==="throw"){if(st===K)throw st=se,ie.arg;ie.dispatchException(ie.arg)}else ie.method==="return"&&ie.abrupt("return",ie.arg);st=W;var Ue=H(Ee,ge,ie);if(Ue.type==="normal"){if(st=ie.done?se:F,Ue.arg===Z)continue;return{value:Ue.arg,done:ie.done}}else Ue.type==="throw"&&(st=se,ie.method="throw",ie.arg=Ue.arg)}}}function de(Ee,ge){var ie=ge.method,st=Ee.iterator[ie];if(st===_)return ge.delegate=null,ie==="throw"&&Ee.iterator.return&&(ge.method="return",ge.arg=_,de(Ee,ge),ge.method==="throw")||ie!=="return"&&(ge.method="throw",ge.arg=new TypeError("The iterator does not provide a '"+ie+"' method")),Z;var We=H(st,Ee.iterator,ge.arg);if(We.type==="throw")return ge.method="throw",ge.arg=We.arg,ge.delegate=null,Z;var ht=We.arg;if(!ht)return ge.method="throw",ge.arg=new TypeError("iterator result is not an object"),ge.delegate=null,Z;if(ht.done)ge[Ee.resultName]=ht.value,ge.next=Ee.nextLoc,ge.method!=="return"&&(ge.method="next",ge.arg=_);else return ht;return ge.delegate=null,Z}me(oe),R(oe,S,"Generator"),R(oe,d,function(){return this}),R(oe,"toString",function(){return"[object Generator]"});function Se(Ee){var ge={tryLoc:Ee[0]};1 in Ee&&(ge.catchLoc=Ee[1]),2 in Ee&&(ge.finallyLoc=Ee[2],ge.afterLoc=Ee[3]),this.tryEntries.push(ge)}function J(Ee){var ge=Ee.completion||{};ge.type="normal",delete ge.arg,Ee.completion=ge}function we(Ee){this.tryEntries=[{tryLoc:"root"}],Ee.forEach(Se,this),this.reset(!0)}r.keys=function(Ee){var ge=Object(Ee),ie=[];for(var st in ge)ie.push(st);return ie.reverse(),function We(){for(;ie.length;){var ht=ie.pop();if(ht in ge)return We.value=ht,We.done=!1,We}return We.done=!0,We}};function xe(Ee){if(Ee){var ge=Ee[d];if(ge)return ge.call(Ee);if(typeof Ee.next=="function")return Ee;if(!isNaN(Ee.length)){var ie=-1,st=function We(){for(;++ie<Ee.length;)if(c.call(Ee,ie))return We.value=Ee[ie],We.done=!1,We;return We.value=_,We.done=!0,We};return st.next=st}}return{next:Dt}}r.values=xe;function Dt(){return{value:_,done:!0}}return we.prototype={constructor:we,reset:function(Ee){if(this.prev=0,this.next=0,this.sent=this._sent=_,this.done=!1,this.delegate=null,this.method="next",this.arg=_,this.tryEntries.forEach(J),!Ee)for(var ge in this)ge.charAt(0)==="t"&&c.call(this,ge)&&!isNaN(+ge.slice(1))&&(this[ge]=_)},stop:function(){this.done=!0;var Ee=this.tryEntries[0],ge=Ee.completion;if(ge.type==="throw")throw ge.arg;return this.rval},dispatchException:function(Ee){if(this.done)throw Ee;var ge=this;function ie(Ue,wt){return ht.type="throw",ht.arg=Ee,ge.next=Ue,wt&&(ge.method="next",ge.arg=_),!!wt}for(var st=this.tryEntries.length-1;st>=0;--st){var We=this.tryEntries[st],ht=We.completion;if(We.tryLoc==="root")return ie("end");if(We.tryLoc<=this.prev){var It=c.call(We,"catchLoc"),qe=c.call(We,"finallyLoc");if(It&&qe){if(this.prev<We.catchLoc)return ie(We.catchLoc,!0);if(this.prev<We.finallyLoc)return ie(We.finallyLoc)}else if(It){if(this.prev<We.catchLoc)return ie(We.catchLoc,!0)}else if(qe){if(this.prev<We.finallyLoc)return ie(We.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Ee,ge){for(var ie=this.tryEntries.length-1;ie>=0;--ie){var st=this.tryEntries[ie];if(st.tryLoc<=this.prev&&c.call(st,"finallyLoc")&&this.prev<st.finallyLoc){var We=st;break}}We&&(Ee==="break"||Ee==="continue")&&We.tryLoc<=ge&&ge<=We.finallyLoc&&(We=null);var ht=We?We.completion:{};return ht.type=Ee,ht.arg=ge,We?(this.method="next",this.next=We.finallyLoc,Z):this.complete(ht)},complete:function(Ee,ge){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"&&ge&&(this.next=ge),Z},finish:function(Ee){for(var ge=this.tryEntries.length-1;ge>=0;--ge){var ie=this.tryEntries[ge];if(ie.finallyLoc===Ee)return this.complete(ie.completion,ie.afterLoc),J(ie),Z}},catch:function(Ee){for(var ge=this.tryEntries.length-1;ge>=0;--ge){var ie=this.tryEntries[ge];if(ie.tryLoc===Ee){var st=ie.completion;if(st.type==="throw"){var We=st.arg;J(ie)}return We}}throw new Error("illegal catch attempt")},delegateYield:function(Ee,ge,ie){return this.delegate={iterator:xe(Ee),resultName:ge,nextLoc:ie},this.method==="next"&&(this.arg=_),Z}},r}(o.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})(QA);var Sf={exports:{}};(function(o){(function(n,r){o.exports?o.exports=r():n.log=r()})(Eb,function(){var n=function(){},r="undefined",a=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),c=["trace","debug","info","warn","error"];function e(F,W){var se=F[W];if(typeof se.bind=="function")return se.bind(F);try{return Function.prototype.bind.call(se,F)}catch{return function(){return Function.prototype.apply.apply(se,[F,arguments])}}}function _(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function v(F){return F==="debug"&&(F="log"),typeof console===r?!1:F==="trace"&&a?_:console[F]!==void 0?e(console,F):console.log!==void 0?e(console,"log"):n}function d(F,W){for(var se=0;se<c.length;se++){var Z=c[se];this[Z]=se<F?n:this.methodFactory(Z,F,W)}this.log=this.debug}function C(F,W,se){return function(){typeof console!==r&&(d.call(this,W,se),this[F].apply(this,arguments))}}function S(F,W,se){return v(F)||C.apply(this,arguments)}function R(F,W,se){var Z=this,Re;W=W??"WARN";var X="loglevel";typeof F=="string"?X+=":"+F:typeof F=="symbol"&&(X=void 0);function te(oe){var me=(c[oe]||"silent").toUpperCase();if(!(typeof window===r||!X)){try{window.localStorage[X]=me;return}catch{}try{window.document.cookie=encodeURIComponent(X)+"="+me+";"}catch{}}}function ye(){var oe;if(!(typeof window===r||!X)){try{oe=window.localStorage[X]}catch{}if(typeof oe===r)try{var me=window.document.cookie,_e=me.indexOf(encodeURIComponent(X)+"=");_e!==-1&&(oe=/^([^;]+)/.exec(me.slice(_e))[1])}catch{}return Z.levels[oe]===void 0&&(oe=void 0),oe}}function Oe(){if(!(typeof window===r||!X)){try{window.localStorage.removeItem(X);return}catch{}try{window.document.cookie=encodeURIComponent(X)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}Z.name=F,Z.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},Z.methodFactory=se||S,Z.getLevel=function(){return Re},Z.setLevel=function(oe,me){if(typeof oe=="string"&&Z.levels[oe.toUpperCase()]!==void 0&&(oe=Z.levels[oe.toUpperCase()]),typeof oe=="number"&&oe>=0&&oe<=Z.levels.SILENT){if(Re=oe,me!==!1&&te(oe),d.call(Z,oe,F),typeof console===r&&oe<Z.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+oe},Z.setDefaultLevel=function(oe){W=oe,ye()||Z.setLevel(oe,!1)},Z.resetLevel=function(){Z.setLevel(W,!1),Oe()},Z.enableAll=function(oe){Z.setLevel(Z.levels.TRACE,oe)},Z.disableAll=function(oe){Z.setLevel(Z.levels.SILENT,oe)};var Q=ye();Q==null&&(Q=W),Z.setLevel(Q,!1)}var D=new R,H={};D.getLogger=function(F){if(typeof F!="symbol"&&typeof F!="string"||F==="")throw new TypeError("You must supply a name when creating a logger.");var W=H[F];return W||(W=H[F]=new R(F,D.getLevel(),D.methodFactory)),W};var K=typeof window!==r?window.log:void 0;return D.noConflict=function(){return typeof window!==r&&window.log===D&&(window.log=K),D},D.getLoggers=function(){return H},D.default=D,D})})(Sf);var Vn=Sf.exports;const Hs=()=>`${new Date().toISOString()} | metrics`,zs=(o,n,r)=>`${o} | ${n} | ${r}`;Vn.setDefaultLevel(Vn.levels.TRACE);const ZA=o=>{Vn.info(zs(Hs(),"log ",`set log level to ${o?"verbose":"info"}`)),Vn.setLevel(o?Vn.levels.TRACE:Vn.levels.INFO)},e1=o=>{const n=[...Object.keys(Vn.levels)];n.includes(o)?(Vn.info(zs(Hs(),"log ",`update log level to ${o.toLowerCase()}`)),Vn.setLevel(o)):Vn.warn(zs(Hs(),"log ","Incorrect log level please choose one of "),n)},Rt=(o,n,r)=>{r?Vn.debug(zs(Hs(),o,n),r):Vn.debug(zs(Hs(),o,n))},Pd=(o,n)=>{Vn.info(zs(Hs(),o,n))},wa=(o,n)=>{Vn.info(zs(Hs(),o,n))},Bu=(o,n)=>{Vn.warn(zs(Hs(),o,n))},so=(o,n)=>{Vn.error(zs(Hs(),o,n))};function t1(o){return Math.floor(Math.random()*o).toString()}function Ef(o,n){let r=n;return o.forEach(a=>{r=r.replace(a,"")}),r}function n1(o,n){let r="";for(let a=0;a<n;a+=1)r+=o[t1(o.length)];return r}function r1({length:o=20,useLetters:n=!0,useNumbers:r=!0,includeSymbols:a=[],excludeSymbols:c=[]}={}){let e="abcdefghijklmnopqrstuvwxyz",_="0123456789",v=[],d=[],C=[];return n&&(c.length&&(e=Ef(c,e)),d=e.split("")),r&&(c.length&&(_=Ef(c,_)),C=_.split("")),v=[...d,...C,...a],n1(v,o)}var s1=r1;const fl=Qt(s1),i1=()=>"WebRTCMetrics",a1=()=>"5.0.3",zt={INBOUND:"inbound",OUTBOUND:"outbound"},Fs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ml={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},o1=()=>({delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}),Cf={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:zt.INBOUND},Af={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:zt.OUTBOUND},If={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:zt.INBOUND},Rf={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:zt.OUTBOUND},l1=o=>{const n={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(o){const r={...o,audio:{},video:{},data:{...o.data},network:{...o.network},experimental:{...o.experimental}};return Object.keys(o.audio).forEach(a=>{r.audio[a]={...o.audio[a]}}),Object.keys(o.video).forEach(a=>{r.video[a]={...o.video[a]}}),r}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},u1={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${fl()}`,cid:`c-${fl()}`,uid:`u-${fl()}`,record:!1,ticket:!0},Vr={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},ve={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"},ae={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},gl={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Ld={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},Me={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},qd="config ",c1=(o,n={},r)=>{const a={...r,...n};return n.pname||Bu(qd,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),n.cid||Bu(qd,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),n.uid||Bu(qd,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),a.pc=o,a},d1=(o={})=>{const n={...u1,...o};return n.name=i1(),n.version=a1(),n},vl=(o,n,r,a=!1,c)=>{let e=o.map(_=>{if(!r)return _[n];if(!c)return _[n][r];const v=_[n][c];return v?v[r]:null});return e=e.filter(_=>a?Number.isFinite(_)&&_>0:Number.isFinite(_)),e.length===0?[]:e},mi=o=>o.reduce((n,r)=>n+r,0)/o.length,h1=()=>`probe-${fl()}`,p1=()=>`coltr-${fl()}`,xf=o=>new Promise(n=>setTimeout(n,o)),Hd=(o,n,r)=>{n?o.call(n,r):o(r)},Zt=(o,n,r,a)=>{const c=vl(o,n,r,!0,a);if(c.length===0)return null;const e=c.reduce((_,v)=>_+v,0)/c.length;return e===0?null:c.map(_=>Math.abs(e-_)).reduce((_,v)=>_+v,0)/c.length*100/e},nn=(o,n,r,a=!1,c)=>{const e=vl(o,n,r,a,c);return e.length===0?null:e.reduce((_,v)=>_+v,0)/e.length},Sa=(o,n,r)=>vl(o,n,r).reduce((a,c)=>a+c,0),en=(o,n,r,a)=>{const c=vl(o,n,r,!0,a);return c.length===0?null:Math.min(...c)},tn=(o,n,r,a)=>{const c=vl(o,n,r,!1,a);return c.length===0?null:Math.max(...c)},Un=(o,n,r,a)=>{const c=o.slice().pop();if(!c)return null;if(!r)return c[n];if(!a)return c[n][r];const e=c[n][a];return e?e[r]:null},_1=o=>o.slice().pop(),wn=(o,n,r)=>{if(!n)return null;const a={};let c=n[ae.AUDIO][o];c||(c=r===zt.INBOUND?{...Cf}:{...Af}),a[ae.AUDIO]=c;let e=n[ae.VIDEO][o];return e||(e=r===zt.INBOUND?{...If}:{...Rf}),a[ae.VIDEO]=e,a},yl="exporter ",f1="2.0",$f=(o,n,r)=>{if(!o||o.length===0)return 0;const a=o[o.length-1];if(!a)return 0;const c=a[n][r];if(c){const e=c.total_rtt_ms_out,_=c.total_rtt_measure_out;return!_||!e?nn(o,n,"delta_rtt_ms_out",!1,r):Number(e/_)}return null},m1=(o,n)=>{if(!o||o.length===0)return 0;const r=o[o.length-1];if(!r)return 0;const a=r[n].total_rtt_connectivity_ms,c=r[n].total_rtt_connectivity_measure;return!c||!a?nn(o,n,"delta_rtt_connectivity_ms"):Number(a/c)},g1=o=>Un(o,"network","local_candidate_type")!=="relay"?`direct/${Un(o,"network","local_candidate_protocol")}`:`turn/${Un(o,"network","local_candidate_relay_protocol")}`,v1=o=>{const n=Un(o,"network","remote_candidate_type"),r=Un(o,"network","remote_candidate_protocol");return n!=="relay"?`direct/${r}`:`turn/${r}`};class y1{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){Pd(yl,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){Pd(yl,"stop() - stop exporter...");const n=new Date;return this._end=n.toJSON(),n}saveReferenceReport(n){this._referenceReport=n}getReferenceReport(){return this._referenceReport}addReport(n){this._cfg.ticket&&(Rt(yl,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){Pd(yl,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Rt(yl,"ticket() - generate ticket");const n=Un(this._reports,"audio","total_packets_lost_in"),r=Un(this._reports,"audio","total_packets_in"),a=Un(this._reports,"video","total_packets_lost_in"),c=Un(this._reports,"video","total_packets_in"),e={},_=_1(this._reports);return _&&(Object.keys(_[ae.AUDIO]).forEach(v=>{const d=_[ae.AUDIO][v];if(e[d.ssrc]={type:ae.AUDIO,direction:d.direction},d.direction===zt.INBOUND){const C={avg:nn(this._reports,ae.AUDIO,"delta_jitter_ms_in",!1,v),min:en(this._reports,ae.AUDIO,"delta_jitter_ms_in",v),max:tn(this._reports,ae.AUDIO,"delta_jitter_ms_in",v),volatility:Zt(this._reports,ae.AUDIO,"delta_jitter_ms_in",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ae.AUDIO,"delta_kbs_in",!1,v),min:en(this._reports,ae.AUDIO,"delta_kbs_in",v),max:tn(this._reports,ae.AUDIO,"delta_kbs_in",v),volatility:Zt(this._reports,ae.AUDIO,"delta_kbs_in",v),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ae.AUDIO,"delta_KBytes_in",!1,v),min:en(this._reports,ae.AUDIO,"delta_KBytes_in",v),max:tn(this._reports,ae.AUDIO,"delta_KBytes_in",v),volatility:Zt(this._reports,ae.AUDIO,"delta_KBytes_in",v),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D={emodel:{avg:nn(this._reports,ae.AUDIO,"mos_emodel_in",!1,v),min:en(this._reports,ae.AUDIO,"mos_emodel_in",v),max:tn(this._reports,ae.AUDIO,"mos_emodel_in",v),volatility:Zt(this._reports,ae.AUDIO,"mos_emodel_in",v)},effective:{avg:nn(this._reports,ae.AUDIO,"mos_in",!1,v),min:en(this._reports,ae.AUDIO,"mos_in",v),max:tn(this._reports,ae.AUDIO,"mos_in",v),volatility:Zt(this._reports,ae.AUDIO,"mos_in",v)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},H=Un(this._reports,ae.AUDIO,"total_packets_lost_in",v),K=Un(this._reports,ae.AUDIO,"total_packets_in",v),F={lost:H,avg:Math.round((H/(H+K)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[v].jitter=C,e[v].mos=D,e[v].traffic=R,e[v].bitrate=S,e[v].loss=F}else{const C={avg:nn(this._reports,ae.AUDIO,"delta_jitter_ms_out",!1,v),min:en(this._reports,ae.AUDIO,"delta_jitter_ms_out",v),max:tn(this._reports,ae.AUDIO,"delta_jitter_ms_out",v),volatility:Zt(this._reports,ae.AUDIO,"delta_jitter_ms_out",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ae.AUDIO,"delta_kbs_out",!1,v),min:en(this._reports,ae.AUDIO,"delta_kbs_out",v),max:tn(this._reports,ae.AUDIO,"delta_kbs_out",v),volatility:Zt(this._reports,ae.AUDIO,"delta_kbs_out",v),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ae.AUDIO,"delta_KBytes_out",!1,v),min:en(this._reports,ae.AUDIO,"delta_KBytes_out",v),max:tn(this._reports,ae.AUDIO,"delta_KBytes_out",v),volatility:Zt(this._reports,ae.AUDIO,"delta_KBytes_out",v),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},D={avg:$f(this._reports,ae.AUDIO,v),min:en(this._reports,ae.AUDIO,"delta_rtt_ms_out",v),max:tn(this._reports,ae.AUDIO,"delta_rtt_ms_out",v),volatility:Zt(this._reports,ae.AUDIO,"delta_rtt_ms_out",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ae.AUDIO,"total_packets_lost_out",v),K=Un(this._reports,ae.AUDIO,"total_packets_out",v),F={lost:H,avg:Math.round((H/(H+K)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},W={emodel:{avg:nn(this._reports,ae.AUDIO,"mos_emodel_out",!1,v),min:en(this._reports,ae.AUDIO,"mos_emodel_out",v),max:tn(this._reports,ae.AUDIO,"mos_emodel_out",v),volatility:Zt(this._reports,ae.AUDIO,"mos_emodel_out",v)},effective:{avg:nn(this._reports,ae.AUDIO,"mos_out",!1,v),min:en(this._reports,ae.AUDIO,"mos_out",v),max:tn(this._reports,ae.AUDIO,"mos_out",v),volatility:Zt(this._reports,ae.AUDIO,"mos_out",v)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};e[v].jitter=C,e[v].rtt=D,e[v].traffic=R,e[v].bitrate=S,e[v].loss=F,e[v].mos=W}}),Object.keys(_[ae.VIDEO]).forEach(v=>{const d=_[ae.VIDEO][v];if(e[v]={type:ae.VIDEO,direction:d.direction},d.direction===zt.INBOUND){const C={avg:nn(this._reports,ae.VIDEO,"delta_jitter_ms_in",!1,v),min:en(this._reports,ae.VIDEO,"delta_jitter_ms_in",v),max:tn(this._reports,ae.VIDEO,"delta_jitter_ms_in",v),volatility:Zt(this._reports,ae.VIDEO,"delta_jitter_ms_in",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ae.VIDEO,"delta_kbs_in",!1,v),min:en(this._reports,ae.VIDEO,"delta_kbs_in",v),max:tn(this._reports,ae.VIDEO,"delta_kbs_in",v),volatility:Zt(this._reports,ae.VIDEO,"delta_kbs_in",v),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ae.VIDEO,"delta_KBytes_in",!1,v),min:en(this._reports,ae.VIDEO,"delta_KBytes_in",v),max:tn(this._reports,ae.VIDEO,"delta_KBytes_in",v),volatility:Zt(this._reports,ae.VIDEO,"delta_KBytes_in",v),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D=Un(this._reports,ae.VIDEO,"total_packets_lost_in",v),H=Un(this._reports,ae.VIDEO,"total_packets_in",v),K={lost:D,avg:Math.round((D/(D+H)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[v].jitter=C,e[v].traffic=R,e[v].bitrate=S,e[v].loss=K}else{const C={avg:nn(this._reports,ae.VIDEO,"delta_jitter_ms_out",!1,v),min:en(this._reports,ae.VIDEO,"delta_jitter_ms_out",v),max:tn(this._reports,ae.VIDEO,"delta_jitter_ms_out",v),volatility:Zt(this._reports,ae.VIDEO,"delta_jitter_ms_out",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ae.VIDEO,"delta_kbs_out",!1,v),min:en(this._reports,ae.VIDEO,"delta_kbs_out",v),max:tn(this._reports,ae.VIDEO,"delta_kbs_out",v),volatility:Zt(this._reports,ae.VIDEO,"delta_kbs_out",v),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ae.VIDEO,"delta_KBytes_out",!1,v),min:en(this._reports,ae.VIDEO,"delta_KBytes_out",v),max:tn(this._reports,ae.VIDEO,"delta_KBytes_out",v),volatility:Zt(this._reports,ae.VIDEO,"delta_KBytes_out",v),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D={avg:$f(this._reports,ae.VIDEO,v),min:en(this._reports,ae.VIDEO,"delta_rtt_ms_out",v),max:tn(this._reports,ae.VIDEO,"delta_rtt_ms_out",v),volatility:Zt(this._reports,ae.VIDEO,"delta_rtt_ms_out",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ae.VIDEO,"total_packets_lost_out",v),K=Un(this._reports,ae.VIDEO,"total_packets_out",v),F={lost:H,avg:Math.round((H/(H+K)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[v].jitter=C,e[v].rtt=D,e[v].traffic=R,e[v].bitrate=S,e[v].loss=F}})),{version:f1,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:e,data:{rtt:{avg:m1(this._reports,"data"),min:en(this._reports,"data","delta_rtt_connectivity_ms"),max:tn(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Zt(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((n/(n+r)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+c)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:nn(this._reports,"data","delta_kbs_in"),min:en(this._reports,"data","delta_kbs_in"),max:tn(this._reports,"data","delta_kbs_in"),volatility:Zt(this._reports,"data","delta_kbs_in")},out:{avg:nn(this._reports,"data","delta_kbs_out"),min:en(this._reports,"data","delta_kbs_out"),max:tn(this._reports,"data","delta_kbs_out"),volatility:Zt(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:nn(this._reports,"data","delta_KBytes_in"),min:en(this._reports,"data","delta_KBytes_in"),max:tn(this._reports,"data","delta_KBytes_in"),volatility:Zt(this._reports,"data","delta_KBytes_in")},out:{avg:nn(this._reports,"data","delta_KBytes_out"),min:en(this._reports,"data","delta_KBytes_out"),max:tn(this._reports,"data","delta_KBytes_out"),volatility:Zt(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:g1(this._reports),remoteConnection:v1(this._reports)}}}}updateConfig(n){this._cfg=n}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const n=this._reports.slice();return n.pop(),n.pop()||null}getReportsNumber(){return this._reports.length}}const gi="extractor ",Of=(o,n,r,a)=>{let c=!1;const e=a[n].total_rtt_ms_out,_=a[n].total_rtt_measure_out,v=r?r[n].total_rtt_ms_out:0,d=r?r[n].total_rtt_measure_out:0,C={rtt:null,totalRTT:e,totalRTTMeasurements:_};if(o[ve.TIMESTAMP]===a[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ve.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(o,ve.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(c=!0,Number(o[ve.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(o[ve.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d===_))return C;const S=1e3*Number(o[ve.ROUND_TRIP_TIME]);let R=e+S,D=_+1;return c&&(R=1e3*Number(o[ve.TOTAL_ROUND_TRIP_TIME])-v,D=Number(o[ve.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d),{rtt:S,totalRTT:R,totalRTTMeasurements:D}},T1=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[n].total_rtt_connectivity_ms,totalRTTMeasurements:a[n].total_rtt_connectivity_measure};const c=1e3*Number(o[ve.CURRENT_ROUND_TRIP_TIME]);let e=a[n].total_rtt_connectivity_ms+c,_=a[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(o,ve.TOTAL_ROUND_TRIP_TIME)&&(e=1e3*Number(o[ve.TOTAL_ROUND_TRIP_TIME])-(r?r[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(o,ve.RESPONSES_RECEIVED)&&(_=Number(o[ve.RESPONSES_RECEIVED])-(r?r[n].total_rtt_connectivity_measure:0)),{rtt:c,totalRTT:e,totalRTTMeasurements:_}},Vu=(o,n,r)=>o[ve.TIMESTAMP]===r[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ve.JITTER)?null:1e3*(Number(o[ve.JITTER])||0),b1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(o,ve.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[ae.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[ae.VIDEO].total_frames_decoded_in,total_decode_time:n[ae.VIDEO].total_time_decoded_in};const r=o[ve.FRAMES_DECODED],a=o[ve.TOTAL_DECODE_TIME],c=a-n[ae.VIDEO].total_time_decoded_in,e=r-n[ae.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:e>0?c*1e3/e:0,frames_decoded:r,total_decode_time:a}},w1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(o,ve.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[ae.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[ae.VIDEO].total_frames_encoded_out,total_encode_time:n[ae.VIDEO].total_time_encoded_out};const r=o[ve.FRAMES_ENCODED],a=o[ve.TOTAL_ENCODE_TIME],c=a-n[ae.VIDEO].total_time_encoded_out,e=r-n[ae.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:e>0&&c?c*1e3/e:0,frames_encoded:r,total_encode_time:a}},kf=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(o,ve.BYTES_SENT))return{packetsSent:r[n].total_packets_out,packetsLost:r[n].total_packets_lost_out,bytesSent:r[n].total_KBytes_out};const c=Number(o[ve.PACKETS_SENT])||0-(a?a[n].total_packets_out:0),e=c-r[n].total_packets_out,_=Number(o[ve.BYTES_SENT])/1024-(a?a[n].total_KBytes_out:0),v=_-r[n].total_KBytes_out,d=o[ve.TIMESTAMP]||Date.now(),C=a?a.timestamp:null;let S=r.timestamp;!S&&C&&(S=C);const R=S?d-S:0,D=R>0?v*.008*1024/R*1e3:0;return{packetsSent:c,deltaPacketsSent:e,KBytesSent:_,deltaKBytesSent:v,kbsSent:D}},Df=(o,n,r,a)=>{let c=r[n].total_packets_lost_out,e=0,_=0;return Object.prototype.hasOwnProperty.call(o,ve.PACKETS_LOST)&&(c=Number(o[ve.PACKETS_LOST])||0-(a?a[n].total_packets_lost_out:0),e=c-r[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(o,ve.FRACTION_LOST)&&(_=Number(100*o[ve.FRACTION_LOST])),{packetsLost:c,deltaPacketsLost:e,fractionLost:_}},Nf=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(o,ve.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(o,ve.BYTES_RECEIVED))return{percent_packets_lost:r[n].percent_packets_lost_in,packetsReceived:r[n].total_packets_in,packetsLost:r[n].total_packets_lost_in,bytesReceived:r[n].total_KBytes_in};const c=Number(o[ve.PACKETS_RECEIVED])||0-(a?a[n].total_packets_in:0),e=Number(o[ve.PACKETS_LOST])||0-(a?a[n].total_packets_lost_in:0),_=e-r[n].total_packets_lost_in,v=c-r[n].total_packets_in,d=c!==r[n].total_packets_in?_*100/(_+v):0,C=Number(o[ve.BYTES_RECEIVED])/1024-(a?a[n].total_KBytes_in:0),S=C-r[n].total_KBytes_in,R=o[ve.TIMESTAMP]||Date.now(),D=a?a.timestamp:null;let H=r.timestamp;!H&&D&&(H=D);const K=H?R-H:0,F=K>0?S*.008*1024/K*1e3:0;return{percentPacketsLost:d,packetsReceived:c,deltaPacketsReceived:v,packetsLost:e,deltaPacketsLost:_,KBytesReceived:C,deltaKBytesReceived:S,kbsReceived:F}},S1=o=>o[ve.CANDIDATE_TYPE]!=="relay"?"":o[ve.RELAY_PROTOCOL]||"",E1=o=>{if(!Object.prototype.hasOwnProperty.call(o,ve.NETWORK_TYPE))return gl.WIFI;switch(o[ve.NETWORK_TYPE]){case Ld.ETHERNET:return gl.ETHERNET;case Ld.CELLULAR_4G:return gl.CELLULAR_4G;case Ld.WIFI:return gl.WIFI;default:return gl.CELLULAR}},Mf=o=>!Object.prototype.hasOwnProperty.call(o,ve.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(o,ve.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:o[ve.FRAME_WIDTH]||null,height:o[ve.FRAME_HEIGHT]||null,framerate:o[ve.FRAMES_PER_SECOND]},C1=o=>{const n=Object.prototype.hasOwnProperty.call(o,ve.QUALITY_LIMITATION_REASON)?o[ve.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(o,ve.QUALITY_LIMITATION_RESOLUTION_CHANGES)?o[ve.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(o,ve.QUALITY_LIMITATION_DURATIONS)?o[ve.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(c=>{a[c]>1e3&&(a[c]=Number(a[c]/1e3))}),{reason:n,durations:a,resolutionChanges:r}},A1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.PLI)||!Object.prototype.hasOwnProperty.call(o,ve.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(o[ve.PLI]||0)-(r?r[ae.VIDEO].total_pli_sent_in:0),c=(o[ve.NACK]||0)-(r?r[ae.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ae.VIDEO].total_pli_sent_in,deltaNackCount:c-n[ae.VIDEO].total_nack_sent_in}},I1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.PLI)||!Object.prototype.hasOwnProperty.call(o,ve.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(o[ve.PLI]||0)-(r?r[ae.VIDEO].total_pli_received_out:0),c=(o[ve.NACK]||0)-(r?r[ae.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ae.VIDEO].total_pli_received_out,deltaNackCount:c-n[ae.VIDEO].total_nack_received_out}},R1=o=>({channels:o[ve.CHANNELS]||null,clock_rate:o[ve.CLOCK_RATE]||null,mime_type:o[ve.MIME_TYPE]||null,sdp_fmtp_line:o[ve.SDP_FMTP_LINE]||null}),x1=o=>({clock_rate:o[ve.CLOCK_RATE]||null,mime_type:o[ve.MIME_TYPE]||null}),$1=(o,n,r)=>{const a=(o[ve.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),c=(o[ve.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),e=o[ve.TIMESTAMP]||Date.now(),_=a-n.data.total_KBytes_in,v=c-n.data.total_KBytes_out,d=r?r.timestamp:null;let C=n.timestamp;!C&&d&&(C=d);const S=C?e-C:0,R=S>0?_*.008*1024/S*1e3:0,D=S>0?v*.008*1024/S*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:c,delta_KBytes_received:_,delta_KBytes_sent:v,kbs_speed_received:R,kbs_speed_sent:D}},O1=o=>{const n=o[ve.AVAILABLE_INCOMING_BITRATE]/1024||0,r=o[ve.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:r}},k1=(o,n,r,a)=>{if(!o)return[];switch(o[ve.TYPE]){case Vr.CANDIDATE_PAIR:let c=!1;if(o[ve.NOMINATED]&&o[ve.STATE]===ae.SUCCEEDED&&(c=!0,Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o),ve.SELECTED in o&&!o[ve.SELECTED]&&(c=!1)),c){const _=o[ve.LOCAL_CANDIDATE_ID],v=o[ve.REMOTE_CANDIDATE_ID],d=$1(o,n,a),C=O1(o),S=T1(o,"data",a,n);return[{type:Me.NETWORK,value:{local_candidate_id:_}},{type:Me.NETWORK,value:{remote_candidate_id:v}},{type:Me.DATA,value:{total_KBytes_in:d.total_KBytes_received}},{type:Me.DATA,value:{total_KBytes_out:d.total_KBytes_sent}},{type:Me.DATA,value:{delta_KBytes_in:d.delta_KBytes_received}},{type:Me.DATA,value:{delta_KBytes_out:d.delta_KBytes_sent}},{type:Me.DATA,value:{delta_kbs_in:d.kbs_speed_received}},{type:Me.DATA,value:{delta_kbs_out:d.kbs_speed_sent}},{type:Me.DATA,value:{delta_kbs_bandwidth_in:C.kbs_incoming_bandwidth}},{type:Me.DATA,value:{delta_kbs_bandwidth_out:C.kbs_outgoing_bandwidth}},{type:Me.DATA,value:{delta_rtt_connectivity_ms:S.rtt}},{type:Me.DATA,value:{total_rtt_connectivity_ms:S.totalRTT}},{type:Me.DATA,value:{total_rtt_connectivity_measure:S.totalRTTMeasurements}}]}break;case Vr.LOCAL_CANDIDATE:if(o[ve.ID]===n.network.local_candidate_id)return[{type:Me.NETWORK,value:{infrastructure:E1(o)}},{type:Me.NETWORK,value:{local_candidate_type:o[ve.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{local_candidate_protocol:o[ve.PROTOCOL]||""}},{type:Me.NETWORK,value:{local_candidate_relay_protocol:S1(o)}}];break;case Vr.REMOTE_CANDIDATE:if(o[ve.ID]===n.network.remote_candidate_id)return[{type:Me.NETWORK,value:{remote_candidate_type:o[ve.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{remote_candidate_protocol:o[ve.PROTOCOL]||""}}];break;case Vr.INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);const _=o[ve.SSRC],v=wn(_,n,zt.INBOUND);v&&(v.timestamp=n.timestamp);const d=wn(_,a,zt.INBOUND);if(d&&(d.timestamp=a.timestamp),o[ve.MEDIA_TYPE]===ae.AUDIO){const C=Nf(o,ae.AUDIO,v,d),S=Vu(o,ae.AUDIO,v),R=o[ve.CODEC_ID]||"";return[{ssrc:_,type:Me.AUDIO,value:{codec_id_in:R}},{ssrc:_,type:Me.AUDIO,value:{total_packets_in:C.packetsReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_in:C.deltaPacketsReceived}},{ssrc:_,type:Me.AUDIO,value:{total_packets_lost_in:C.packetsLost}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_lost_in:C.deltaPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{percent_packets_lost_in:C.percentPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{total_KBytes_in:C.KBytesReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_KBytes_in:C.deltaKBytesReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_kbs_in:C.kbsReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_jitter_ms_in:S}}]}if(o[ve.MEDIA_TYPE]===ae.VIDEO){const C=b1(o,v),S=Nf(o,ae.VIDEO,v,d),R=Vu(o,ae.VIDEO,v),D=o[ve.DECODER_IMPLEMENTATION]||null,H=o[ve.CODEC_ID]||null,K=Mf(o),F=A1(o,v,d);return[{ssrc:_,type:Me.VIDEO,value:{codec_id_in:H}},{ssrc:_,type:Me.VIDEO,value:{total_packets_in:S.packetsReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_in:S.deltaPacketsReceived}},{ssrc:_,type:Me.VIDEO,value:{total_packets_lost_in:S.packetsLost}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_lost_in:S.deltaPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{percent_packets_lost_in:S.percentPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{total_KBytes_in:S.KBytesReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_KBytes_in:S.deltaKBytesReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_kbs_in:S.kbsReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_jitter_ms_in:R}},{ssrc:_,type:Me.VIDEO,value:{decoder_in:D}},{ssrc:_,type:Me.VIDEO,value:{delta_ms_decode_frame_in:C.delta_ms_decode_frame}},{ssrc:_,type:Me.VIDEO,value:{total_frames_decoded_in:C.frames_decoded}},{ssrc:_,type:Me.VIDEO,value:{total_time_decoded_in:C.total_decode_time}},{ssrc:_,type:Me.VIDEO,value:{total_nack_sent_in:F.nackCount}},{ssrc:_,type:Me.VIDEO,value:{delta_nack_sent_in:F.deltaNackCount}},{ssrc:_,type:Me.VIDEO,value:{total_pli_sent_in:F.pliCount}},{ssrc:_,type:Me.VIDEO,value:{delta_pli_sent_in:F.deltaPliCount}},{ssrc:_,type:Me.VIDEO,value:{size_in:K}}]}break}case Vr.OUTBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);const _=o[ve.SSRC],v=wn(_,n,zt.OUTBOUND);v&&(v.timestamp=n.timestamp);const d=wn(_,a,zt.OUTBOUND);if(d&&(d.timestamp=a.timestamp),o[ve.MEDIA_TYPE]===ae.AUDIO){const C=o[ve.CODEC_ID]||null,S=kf(o,ae.AUDIO,v,d);return[{ssrc:_,type:Me.AUDIO,value:{codec_id_out:C}},{ssrc:_,type:Me.AUDIO,value:{total_packets_out:S.packetsSent}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_out:S.deltaPacketsSent}},{ssrc:_,type:Me.AUDIO,value:{total_KBytes_out:S.KBytesSent}},{ssrc:_,type:Me.AUDIO,value:{delta_KBytes_out:S.deltaKBytesSent}},{ssrc:_,type:Me.AUDIO,value:{delta_kbs_out:S.kbsSent}}]}if(o[ve.MEDIA_TYPE]===ae.VIDEO){const C=o[ve.ENCODER_IMPLEMENTATION]||null,S=o[ve.CODEC_ID]||null,R=w1(o,v),D=Mf(o),H=C1(o),K=I1(o,v,d),F=kf(o,ae.VIDEO,v,d);return[{ssrc:_,type:Me.VIDEO,value:{codec_id_out:S}},{ssrc:_,type:Me.VIDEO,value:{total_packets_out:F.packetsSent}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_out:F.deltaPacketsSent}},{ssrc:_,type:Me.VIDEO,value:{total_KBytes_out:F.KBytesSent}},{ssrc:_,type:Me.VIDEO,value:{delta_KBytes_out:F.deltaKBytesSent}},{ssrc:_,type:Me.VIDEO,value:{delta_kbs_out:F.kbsSent}},{ssrc:_,type:Me.VIDEO,value:{encoder_out:C}},{ssrc:_,type:Me.VIDEO,value:{delta_ms_encode_frame_out:R.delta_ms_encode_frame}},{ssrc:_,type:Me.VIDEO,value:{total_frames_encoded_out:R.frames_encoded}},{ssrc:_,type:Me.VIDEO,value:{total_time_encoded_out:R.total_encode_time}},{ssrc:_,type:Me.VIDEO,value:{total_nack_received_out:K.nackCount}},{ssrc:_,type:Me.VIDEO,value:{delta_nack_received_out:K.deltaNackCount}},{ssrc:_,type:Me.VIDEO,value:{total_pli_received_out:K.pliCount}},{ssrc:_,type:Me.VIDEO,value:{delta_pli_received_out:K.deltaPliCount}},{ssrc:_,type:Me.VIDEO,value:{size_out:D}},{ssrc:_,type:Me.VIDEO,value:{limitation_out:H}}]}break}case Vr.MEDIA_SOURCE:{Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);break}case Vr.TRACK:{Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);break}case Vr.CODEC:const e=[];return Object.keys(n[ae.AUDIO]).forEach(_=>{const v=n[ae.AUDIO][_];if(v.codec_id_in===o[ve.ID]||v.codec_id_out===o[ve.ID]){Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);const d=R1(o);o[ve.ID]===v.codec_id_in?e.push({ssrc:v.ssrc,type:Me.AUDIO,value:{codec_in:d}}):e.push({ssrc:v.ssrc,type:Me.AUDIO,value:{codec_out:d}})}}),Object.keys(n[ae.VIDEO]).forEach(_=>{const v=n[ae.VIDEO][_];if(v.codec_id_in===o[ve.ID]||v.codec_id_out===o[ve.ID]){Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);const d=x1(o);o[ve.ID]===v.codec_id_in?e.push({ssrc:v.ssrc,type:Me.VIDEO,value:{codec_in:d}}):e.push({ssrc:v.ssrc,type:Me.VIDEO,value:{codec_out:d}})}}),e;case Vr.REMOTE_INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);const _=o[ve.SSRC],v=wn(_,n,zt.OUTBOUND),d=wn(_,a,zt.OUTBOUND);if(o[ve.KIND]===ae.AUDIO){const C=Of(o,ae.AUDIO,d,v),S=Vu(o,ae.AUDIO,v),R=Df(o,ae.AUDIO,v,d);return[{ssrc:_,type:Me.AUDIO,value:{delta_rtt_ms_out:C.rtt}},{ssrc:_,type:Me.AUDIO,value:{total_rtt_ms_out:C.totalRTT}},{ssrc:_,type:Me.AUDIO,value:{total_rtt_measure_out:C.totalRTTMeasurements}},{ssrc:_,type:Me.AUDIO,value:{delta_jitter_ms_out:S}},{ssrc:_,type:Me.AUDIO,value:{timestamp_out:o[ve.TIMESTAMP]}},{ssrc:_,type:Me.AUDIO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{percent_packets_lost_out:R.fractionLost}}]}if(o[ve.KIND]===ae.VIDEO){const C=Of(o,ae.VIDEO,d,v),S=Vu(o,ae.VIDEO,v),R=Df(o,ae.VIDEO,v,d);return[{ssrc:_,type:Me.VIDEO,value:{delta_rtt_ms_out:C.rtt}},{ssrc:_,type:Me.VIDEO,value:{total_rtt_ms_out:C.totalRTT}},{ssrc:_,type:Me.VIDEO,value:{total_rtt_measure_out:C.totalRTTMeasurements}},{ssrc:_,type:Me.VIDEO,value:{delta_jitter_ms_out:S}},{ssrc:_,type:Me.VIDEO,value:{timestamp_out:o[ve.TIMESTAMP]}},{ssrc:_,type:Me.VIDEO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{percent_packets_lost_out:R.fractionLost}}]}break}}return[]},ju=o=>o<0?1:o>100?4.5:1+.035*o+7/1e6*o*(o-60)*(100-o),D1=(o,n=ae.AUDIO,r,a,c)=>{const e=wn(c,o,zt.INBOUND),_=wn(c,r,zt.INBOUND),v=wn(c,a,zt.INBOUND),d=[],C=[],S=e[n].percent_packets_lost_in,R=e[n].delta_jitter_ms_in,D=_&&_[n].delta_jitter_ms_in||null,H=v&&v[n].delta_jitter_ms_in||null,K=o.data.delta_rtt_connectivity_ms,F=r&&r.data.delta_rtt_connectivity_ms||null,W=a&&a.data.delta_rtt_connectivity_ms||null;K&&d.push(K),F&&d.push(F),W&&d.push(W),R&&C.push(R),r&&D&&C.push(D),a&&H&&C.push(H);const se=d.length>0?mi(d):100,Z=C.length>0?mi(C):10,Re=93.2-S,X=.18*Re*Re-27.9*Re+1126.62,te=(se+Z)/2,ye=te-177.3<0?0:1,Oe=.024*te+.11*(te-177.3)*ye,Q=X-Oe;return ju(Q)},N1=(o,n=ae.AUDIO,r,a,c)=>{const e=wn(c,o,zt.OUTBOUND),_=wn(c,r,zt.OUTBOUND),v=wn(c,a,zt.OUTBOUND),d=[],C=[],S=e[n].percent_packets_lost_out,R=e[n].delta_rtt_ms_out,D=_&&_[n].delta_rtt_ms_out||null,H=v&&v[n].delta_rtt_ms_out||null,K=e[n].delta_jitter_ms_out,F=_&&_[n].delta_jitter_ms_out||null,W=v&&v[n].delta_jitter_ms_out||null,se=o.data.delta_rtt_connectivity_ms,Z=r&&r.data.delta_rtt_connectivity_ms||null,Re=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):se&&d.push(se),D?d.push(D):Z&&d.push(Z),H?d.push(H):Re&&d.push(Re),K&&C.push(K),r&&F&&C.push(F),a&&W&&C.push(W);const X=d.length>0?mi(d):100,te=C.length>0?mi(C):10,ye=93.2-S,Oe=.18*ye*ye-27.9*ye+1126.62,Q=(X+te)/2,oe=Q-177.3<0?0:1,me=.024*Q+.11*(Q-177.3)*oe,_e=Oe-me;return ju(_e)},M1=(o,n=ae.AUDIO,r,a,c)=>{const e=wn(c,o,zt.INBOUND),_=wn(c,r,zt.INBOUND),v=wn(c,a,zt.INBOUND),d=[],C=[],S=e[n].percent_packets_lost_in/100,R=e[n].delta_jitter_ms_in,D=_&&_[n].delta_jitter_ms_in||null,H=v&&v[n].delta_jitter_ms_in||null,K=o.data.delta_rtt_connectivity_ms,F=r&&r.data.delta_rtt_connectivity_ms||null,W=a&&a.data.delta_rtt_connectivity_ms||null;K&&d.push(K),F&&d.push(F),W&&d.push(W),R&&C.push(R),_&&D&&C.push(D),v&&H&&C.push(H);const se=d.length>0?mi(d):100,Z=C.length>0?mi(C):10,Re=0,X=19.8,te=29.7,ye=30,Oe=(se+Z)/2+ye,Q=Oe-177.3<0?0:1,oe=.024*Oe+.11*(Oe-177.3)*Q,me=93.2-(Re+X*Math.log(1+te*S)+oe);return ju(me)},U1=(o,n=ae.AUDIO,r,a,c)=>{const e=wn(c,o,zt.OUTBOUND),_=wn(c,r,zt.OUTBOUND),v=wn(c,a,zt.OUTBOUND),d=[],C=[],S=e[n].percent_packets_lost_out/100,R=e[n].delta_rtt_ms_out,D=_&&_[n].delta_rtt_ms_out||null,H=v&&v[n].delta_rtt_ms_out||null,K=e[n].delta_jitter_ms_out,F=_&&_[n].delta_jitter_ms_out||null,W=v&&v[n].delta_jitter_ms_out||null,se=o.data.delta_rtt_connectivity_ms,Z=r&&r.data.delta_rtt_connectivity_ms||null,Re=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):se&&d.push(se),D?d.push(D):Z&&d.push(Z),H?d.push(H):Re&&d.push(Re),K&&C.push(K),_&&F&&C.push(F),v&&W&&C.push(W);const X=d.length>0?mi(d):100,te=C.length>0?mi(C):10,ye=0,Oe=19.8,Q=29.7,oe=30,me=(X+te)/2+oe,_e=me-177.3<0?0:1,le=.024*me+.11*(me-177.3)*_e,de=93.2-(ye+Oe*Math.log(1+Q*S)+le);return ju(de)};class P1{constructor(n,r){this._callbacks={onreport:null,onticket:null},this._id=p1(),this._moduleName=this._id,this._probeId=r,this._config=n,this._exporter=new y1(n),this._state=Fs.IDLE,this.registerToPCEvents(),wa(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,r,a,c){const e=(d,C)=>d===ae.AUDIO?C===Vr.INBOUND_RTP?{...Cf}:{...Af}:C===Vr.INBOUND_RTP?{...If}:{...Rf},_=l1(r);_.pname=this._config.pname,_.call_id=this._config.cid,_.user_id=this._config.uid,_.count=r?r.count+1:1;let v=null;return n.forEach(d=>{!v&&d.timestamp&&(v=d.timestamp),k1(d,_,_.pname,c).forEach(C=>{if(C.value&&C.type)if(C.ssrc){let S=_[C.type][C.ssrc];S||(S=e(C.type,d.type),S.ssrc=C.ssrc,_[C.type][C.ssrc]=S),Object.keys(C.value).forEach(R=>{S[R]=C.value[R]})}else Object.keys(C.value).forEach(S=>{_[C.type][S]=C.value[S]})})}),_.timestamp=v,Object.keys(_[ae.AUDIO]).forEach(d=>{const C=_[ae.AUDIO][d];C.direction===zt.INBOUND?(C.mos_emodel_in=D1(_,ae.AUDIO,r,a,C.ssrc),C.mos_in=M1(_,ae.AUDIO,r,a,C.ssrc)):(C.mos_emodel_out=N1(_,ae.AUDIO,r,a,C.ssrc),C.mos_out=U1(_,ae.AUDIO,r,a,C.ssrc))}),_}async takeReferenceStats(){return new Promise((n,r)=>{const a=Date.now();setTimeout(async()=>{try{const c=Date.now()-a,e=Date.now(),_=await this._config.pc.getStats(),v=this.analyze(_,null,null,null),d=Date.now();v.experimental.time_to_measure_ms=d-e,v.experimental.time_to_wait_ms=c,this._exporter.saveReferenceReport(v),Rt(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(c){r(c)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Fs.RUNNING||!this._config.pc)return Rt(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),r=await this._config.pc.getStats(),a=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),c=Date.now();return a.experimental.time_to_measure_ms=c-n,this._exporter.addReport(a),Rt(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(n){return so(this._moduleName,`got error ${n}`),null}}async start(){Rt(this._moduleName,"starting"),this.state=Fs.RUNNING,this._startedTime=this._exporter.start(),Rt(this._moduleName,"started")}async mute(){this.state=Fs.MUTED,Rt(this._moduleName,"muted")}async unmute(){this.state=Fs.RUNNING,Rt(this._moduleName,"unmuted")}async stop(n){if(Rt(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Fs.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Rt(this._moduleName,"stopped")}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(this._moduleName,`registered callback '${n}'`)):so(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&Hd(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&Hd(this._callbacks.onticket.callback,this._callbacks.onticket.context,n)}updateConfig(n){this._config=n,this._exporter.updateConfig(n)}get state(){return this._state}set state(n){this._state=n,Rt(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,r,a,c){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:r,name:a,description:c})}async registerToPCEvents(){const{pc:n}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const r=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${r.length} devices found`,"Media Devices state")}catch{so(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const a=n.iceConnectionState;a===ml.CONNECTED||a===ml.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.DISCONNECTED||a===ml.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const a=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},n.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},n.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=n.getReceivers();if(r&&r.length>0){const a=r[0],{transport:c}=a;if(c){const{iceTransport:e}=c;e&&(e.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class L1{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||h1(),this._moduleName=this._id,wa(this._moduleName,"probe created"),this._config=n,this._collector=new P1(this._config,this._id)}set onreport(n){n?this._collector.registerCallback("onreport",n):this._collector.unregisterCallback("onreport")}set onticket(n){n?this._collector.registerCallback("onticket",n):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(n){this._collector.state=n}addCustomEvent(n,r,a,c=new Date().toJSON()){this._collector.addCustomEvent(c,r,n,a)}get isRunning(){return this._collector.state===Fs.RUNNING}get isIdle(){return this._collector.state===Fs.IDLE}updateUserId(n){this._config.uid=n,this._collector.updateConfig(this._config)}updateCallId(n){this._config.cid=n,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Bu(this._moduleName,"probe is already running");return}this._collector.start()}stop(n=!1){this.isRunning&&this._collector.stop(n)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const jn="engine ";class q1{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},wa(jn,`configured for probing every ${this._config.refreshEvery}ms`),wa(jn,`configured for starting after ${this._config.startAfter}ms`),wa(jn,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Rt(jn,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(n=>n.isRunning)}get isIdle(){return this._probes.every(n=>n.isIdle)}addNewProbe(n,r){if(!n)throw new Error("undefined peer connection");const a=c1(n,r,this._config),c=new L1(a);return this._probes.push(c),Rt(jn,`${this._probes.length} probes registered`),c}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===Fs.RUNNING&&n.stop(),this._probes=this._probes.filter(r=>n.id!==r.id)}async start(){const n=()=>{this._probes.forEach(e=>e.start())},r=async()=>Promise.all(this._probes.map(e=>e.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,c=async()=>{const e=o1(),_=this._probes.filter(v=>v.isRunning);for(const v of _){const d=await v.collectStats();d&&e.probes.push(d),Rt(jn,`got probe ${v.id}`),await xf(0)}return e.delta_time_to_measure_probes_ms=Sa(e.probes,"experimental","time_to_measure_ms"),e.delta_KBytes_in=Sa(e.probes,"data","delta_KBytes_in"),e.delta_KBytes_out=Sa(e.probes,"data","delta_KBytes_out"),e.delta_kbs_in=Sa(e.probes,"data","delta_kbs_in"),e.delta_kbs_out=Sa(e.probes,"data","delta_kbs_out"),e.total_time_decoded_in=Sa(e.probes,"video","total_time_decoded_in"),e.total_time_encoded_out=Sa(e.probes,"video","total_time_encoded_out"),e};for(Rt(jn,"starting to collect"),n(),Rt(jn,"generating reference reports..."),await r(),Rt(jn,"reference reports generated"),this._startedTime=Date.now();a();)if(Rt(jn,`wait ${this._config.refreshEvery}ms before collecting`),await xf(this._config.refreshEvery),a()){Rt(jn,"collecting...");const e=Date.now(),_=await c(),v=Date.now();_.delta_time_consumed_to_measure_ms=v-e,this.fireOnReports(_),Rt(jn,"collected")}Rt(jn,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const r=a=>{this._probes.forEach(c=>{c.stop(a)})};wa(jn,"stop collecting"),r(n)}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(jn,`registered callback '${n}'`)):so(jn,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&Hd(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const H1="interface ";class z1{constructor(n){this._config=d1(n),wa(H1,`welcome to ${this._config.name} version ${this._config.version}`),ZA(this._config.verbose||!1),this._engine=new q1(this._config)}setupLogLevel(n){e1(n)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(n,r){return this._engine.addNewProbe(n,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(n){this._engine.removeExistingProbe(n)}set onresult(n){n?this._engine.registerCallback("onresult",n):this._engine.unregisterCallback("onresult")}}function F1(o,n){return Object.keys(o).filter(r=>n.includes(r)).reduce((r,a)=>{const c=a;return{...r,[c]:o[c]}},{})}const B1=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],V1={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class j1{constructor(n){this.intervals={},this.analysers={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}async start(n,r,a){r&&r.getTracks().length&&await this.beginCalculation(n,r,a)}stop(n){this.clearVolumeInterval(n),this.analysers[n]&&typeof this.analysers[n].disconnect=="function"&&(this.analysers[n].disconnect(),delete this.analysers[n])}clearVolumeInterval(n){this.intervals[n]&&(clearInterval(this.intervals[n]),delete this.intervals[n])}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{this.stop(n)}),this.intervals={},this.analysers={}}async beginCalculation(n,r,a){this.clearVolumeInterval(a);const c=n.createAnalyser(),e=n.createMediaStreamSource(r);c.smoothingTimeConstant=.8,c.fftSize=1024,e.connect(c),this.analysers[a]=c,this.intervals[a]=setInterval(()=>{const _=new Uint8Array(c.frequencyBinCount);c.getByteFrequencyData(_);let v=0;const d=_.length;for(let S=0;S<d;S++)v+=_[S];const C=v/d;this.onChangeFunction(a,C)},this.emitInterval)}}class G1{constructor(){this.resumePromise=null,this.context=new AudioContext,this.setupErrorHandling()}setupErrorHandling(){this.context.addEventListener("statechange",()=>{(this.context.state==="interrupted"||this.context.state==="closed")&&console.warn(`[ManagedAudioContext] AudioContext state changed to: ${this.context.state}`)})}createNewContext(){return console.log("[ManagedAudioContext] Creating new AudioContext instance"),this.context=new AudioContext,this.setupErrorHandling(),this.context}async getContext(){if(this.context.state==="closed")return console.warn("[ManagedAudioContext] AudioContext is closed, creating new instance"),this.createNewContext();if(this.context.state==="interrupted"){console.warn("[ManagedAudioContext] AudioContext is interrupted, attempting to resume");try{this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(n=>{console.error("[ManagedAudioContext] Failed to resume interrupted context:",n),this.resumePromise=null,this.createNewContext()})),await this.resumePromise}catch(n){return console.error("[ManagedAudioContext] Error resuming context, creating new one:",n),this.createNewContext()}}return this.context.state==="suspended"&&(this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(n=>{throw console.error("[ManagedAudioContext] Failed to resume suspended context:",n),this.resumePromise=null,n})),await this.resumePromise),this.context.state==="closed"?(console.warn("[ManagedAudioContext] Context closed after resume attempt, creating new instance"),this.createNewContext()):this.context}}const Gu={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},W1=0;class K1{constructor(n){var r;this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.isCallWaitingEnabled=!0,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.conferenceNodes={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.vadSessions={},this.vadSessionsState={},this.vadIntervals={},this.vadMrsIntervals={},this.ringbackTimers={},this.ringbackAudioContexts={},this.ringbackSessionProgressReceived={},this.managedAudioContext=new G1,this.context=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new j1({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices(),this.processVADConfiguration(((r=this.context.options.configuration)==null?void 0:r.noiseReductionOptions)||{}),this.setupVADInstance()}setVADConfiguration(n){if(!this.MicVAD)throw new Error("VAD module is not provided in the initial configuration");const r=Object.keys(n);for(const a of r)this.noiseReduction[a]=n[a];this.hasActiveCalls&&this.roomReconfigure(this.currentActiveRoomId)}setupVADInstance(){var n,r;const a=(r=(n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)==null?void 0:r.vadModule;a&&a.MicVAD?(this.MicVAD=a.MicVAD,console.log("✅ VAD module loaded successfully")):this.noiseReduction.mode!=="disabled"&&(console.warn("⚠️ Noise reduction is enabled but VAD module is not provided. To use VAD features, please install @ricky0123/vad-web and pass it via configuration.noiseReductionOptions.vadModule option."),this.noiseReduction.mode="disabled")}processVADConfiguration(n){this.noiseReduction={mode:n.mode||"disabled",checkEveryMs:n.checkEveryMs||500,noiseCheckInterval:n.noiseCheckInterval||2e3,noiseThreshold:n.noiseThreshold||.004,vadConfig:n.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(n){this.currentActiveRoomIdValue=n,this.context.emit("currentActiveRoomChanged",n)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(n){this.isCallAddingInProgress=n,this.context.emit("callAddingInProgressChanged",n)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get isCallWaiting(){return this.isCallWaitingEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get hasActiveAnsweredCalls(){return Object.values(this.activeRooms).filter(n=>!n.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return bf()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input},echoCancellation:!0,echoCancellationType:"system",noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,latency:.01},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(n){this.availableMediaDevices=n,this.context.emit("changeAvailableDeviceList",n)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n)}async initializeMediaDevices(){const n=localStorage.getItem(Gu.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(Gu.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),c=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(c),await this.setMicrophone(n),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const e=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(e)}),a.getTracks().forEach(e=>e.stop())}catch(a){console.error(a)}}async cleanupConferenceNodes(n){const r=this.conferenceNodes[n];if(!r)return;let a=0;r.sources.forEach((_,v)=>{var d;try{_.disconnect(),a++}catch(C){console.error(`[cleanupConferenceNodes] Error disconnecting source ${v}:`,C),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting source ${v}:`,C)}});let c=0;r.destinations.forEach((_,v)=>{var d;try{_.disconnect(),c++}catch(C){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${v}:`,C),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting destination ${v}:`,C)}});let e=0;r.gains.forEach((_,v)=>{var d;try{_.disconnect(),e++}catch(C){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${v}:`,C),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting gain ${v}:`,C)}}),delete this.conferenceNodes[n]}setCallTime(n){const r={...n};delete r.callId,this.callTime={...this.callTime,[n.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(n){const r={...this.callTime};delete r[n],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(n,r){this.timeIntervals={...this.timeIntervals,[n]:r}}removeTimeInterval(n){const r={...this.timeIntervals};r[n]&&(clearInterval(r[n]),delete r[n],this.timeIntervals={...r})}stopCallTimer(n){this.removeTimeInterval(n),this.removeCallTime(n)}emitVolumeChange(n,r){this.context.emit("changeCallVolume",{callId:n,volume:r})}getNoiseReductionMode(){return this.noiseReduction.mode}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,r){if(!/^[A-D0-9*#]+$/g.test(r))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[n].sendDTMF(r)}setIsMuted(n){this.muted=n,this.context.emit("changeIsMuted",n)}processMute(n){const r=this.currentActiveRoomId;this.setIsMuted(n),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!n),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:r,automatic:a}){const c=this.extendedCalls[n];if(!c)return;c._automaticHold=a??!1;const e=new Promise((_,v)=>{const d=setTimeout(()=>{v(new Error("Hold operation timeout"))},5e3),C=()=>{clearTimeout(d),c.putOnHoldTimestamp=r?Date.now():void 0,_()},S=R=>{clearTimeout(d),v(R)};try{r?(this.stopSessionVad(c._id),c.hold({},C)):c.unhold({},C)}catch(R){S(R)}});try{await e,this.updateCall(c);const _=Object.values(this.extendedCalls).filter(v=>v.roomId===c.roomId&&(r?n!==v._id:!0));_.length>1&&await this.doConference(_)}catch(_){throw console.error("Hold operation failed:",_),_}}holdCall(n,r=!1){return this.processHold({callId:n,automatic:r,toHold:!0})}unholdCall(n){return this.processHold({callId:n,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(n=>n.direction==="outgoing"&&n.status===W1).forEach(n=>this.terminateCall(n._id))}answerCall(n){const r=this.extendedCalls[n];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",a=>{this.triggerAddStream(a,r)})}async moveCall(n,r){this.updateCallStatus({callId:n,isMoving:!0}),await this.processRoomChange({callId:n,roomId:r}),this.updateCallStatus({callId:n,isMoving:!1})}updateCall(n){this.activeCalls[n._id]=yf(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const r={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...r}},this.context.emit("updateRoom",{room:r,roomList:this.activeRooms})}hasAutoAnswerHeaders(n){const r=/answer-after=0/,a=n.request.getHeader("Call-Info");return a&&r.test(a)}addCall(n,r=!0){this.activeCalls={...this.activeCalls,[n._id]:yf(n)},this.extendedCalls[n._id]=n,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(n){this.callStatus={...this.callStatus,[n]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const r={...this.callStatus[n.callId]};n.isMoving!==void 0&&(r.isMoving=n.isMoving),n.isTransferring!==void 0&&(r.isTransferring=n.isTransferring),n.isMerging!==void 0&&(r.isMerging=n.isMerging),n.isTransferred!==void 0&&(r.isTransferred=n.isTransferred),this.callStatus={...this.callStatus,[n.callId]:{...r}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(n){const r={...this.callStatus};delete r[n],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(n){this.activeRooms={...this.activeRooms,[n.roomId]:n},this.context.emit("addRoom",{room:n,roomList:this.activeRooms})}async setupActiveStream(){const n=await Nd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n)}async getActiveStream(){const n=await Nd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:a})=>a===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async a=>{await this.setupActiveStream();const c=this.activeStream;a.connection.getSenders()[0].replaceTrack(c.getTracks()[0]),this.updateCall(a)}):await this.doConference(r)}async setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:c})=>c===n))return;this.setSelectedOutputDevice(n);const r=Object.values(this.extendedCalls);if(r.length===0)return;const a=r.filter(c=>c.roomId===this.currentActiveRoomId);a.length===1?r.forEach(c=>{var e;(e=c.audioTag)==null||e.setSinkId(n),this.updateCall(c)}):await this.doConference(a)}removeRoom(n){const r={...this.activeRooms},a={...r[n]};delete r[n],this.activeRooms={...r},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(n){n!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===n).length===0&&(this.removeRoom(n),this.currentActiveRoomId===n&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(n){this.muted?n.mute({audio:!0}):n.unmute({audio:!0})}async startNoiseMonitor({sessionId:n,stream:r,onNoiseDetected:a,onNoiseStop:c}){var e,_,v;let d;try{d=await this.managedAudioContext.getContext()}catch(H){console.error("[startNoiseMonitor] Failed to get AudioContext:",H),(e=this.context.logger)==null||e.error("[startNoiseMonitor] Failed to get AudioContext:",H);return}let C,S;try{C=d.createMediaStreamSource(r.clone()),S=d.createAnalyser()}catch(H){console.error("[startNoiseMonitor] Failed to create audio nodes:",H),console.error("[startNoiseMonitor] AudioContext state:",d.state),(_=this.context.logger)==null||_.error("[startNoiseMonitor] Failed to create audio nodes:",H),(v=this.context.logger)==null||v.error("[startNoiseMonitor] AudioContext state:",d.state);return}S.fftSize=1024;const R=new Float32Array(S.fftSize);C.connect(S);const D=[];this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),this.vadIntervals[n]=null),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),this.vadMrsIntervals[n]=null),this.vadMrsIntervals[n]=setInterval(()=>{S.getFloatTimeDomainData(R);const H=YA(R);D.push(H);const K=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);D.length>K&&D.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[n]=setInterval(()=>{var H;if(D.length===0)return;const K=D.reduce((se,Z)=>se+Z,0)/D.length,F=this.vadSessionsState[n];if(!F){console.warn(`[startNoiseMonitor] State not found for sessionId ${n}, stopping interval`),(H=this.context.logger)==null||H.warn(`[startNoiseMonitor] State not found for sessionId ${n}, stopping interval`),this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),delete this.vadIntervals[n]),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),delete this.vadMrsIntervals[n]);return}const W=K>this.noiseReduction.noiseThreshold;F.isSpeaking||(W&&F.currentMode==="clean"?(F.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!0}),a()):!W&&F.currentMode==="noisy"&&(F.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!1}),c()))},this.noiseReduction.noiseCheckInterval)}async processVAD(n,r){var a;const c=r.clone();this.stopSessionVad(n._id),this.vadSessionsState[n._id]={currentMode:"clean",isSpeaking:!1},console.log("[processVAD] Process for",n._id),(a=this.context.logger)==null||a.log("[processVAD] Process for",n._id);const e=await this.managedAudioContext.getContext(),_=await XA(c,e,150);let v=!1;const d=await this.MicVAD.new({getStream:()=>new Promise(C=>C(c)),...V1,...this.noiseReduction.vadConfig,baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.28/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",onFrameProcessed:()=>{var C;if(!v){if(v=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){n.connection.getSenders()[0]&&n.connection.getSenders()[0].replaceTrack(_.stream.getAudioTracks()[0]);return}if(!this.vadSessionsState[n._id]){console.error(`[processVAD] CRITICAL: State not found for session ${n._id} after being set at line 988! This should not happen.`),(C=this.context.logger)==null||C.error(`[processVAD] CRITICAL: State not found for session ${n._id} after being set at line 988! This should not happen.`);return}this.startNoiseMonitor({sessionId:n._id,stream:c,onNoiseDetected:async()=>{var S,R;console.log("[processVad] - Replace track with Vad Controlled"),(S=this.context.logger)==null||S.log("[processVad] - Replace track with Vad Controlled"),await((R=n.connection.getSenders()[0])==null?void 0:R.replaceTrack(_.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const S=n.connection.getSenders()[0];S&&S.track&&S.transport&&S.transport.state!=="closed"&&S.transport.state!=="failed"&&(console.log("Replace track with Original"),await S.replaceTrack(c.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var C;console.log("🎤 Speech started"),_.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((C=n.connection.getSenders()[0])==null||C.replaceTrack(_.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!0},onSpeechEnd:()=>{var C;console.log("🛑 Speech end"),_.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((C=n.connection.getSenders()[0])==null||C.replaceTrack(_.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!1}});this.vadSessions[n._id]&&(this.vadSessions[n._id].pause(),delete this.vadSessions[n._id]),this.vadSessions[n._id]=d,d.start()}stopSessionVad(n){this.vadSessions[n]&&(this.vadSessions[n].pause(),delete this.vadSessions[n]),this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),delete this.vadIntervals[n]),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),delete this.vadMrsIntervals[n]),this.vadSessionsState[n]&&delete this.vadSessionsState[n]}async roomReconfigure(n){var r,a,c,e;if(n===void 0)return;const _=Object.values(this.extendedCalls).filter(d=>d.roomId===n),v=this.currentActiveRoomId===n;if(console.log("[roomReconfigure] - Calls In Room:",_),(r=this.context.logger)==null||r.log("[roomReconfigure] - Calls In Room:",_),_.forEach((d,C)=>{if(d.audioTag){d.connection.getReceivers().forEach(R=>{R.track.enabled=!d.localMuted}),v&&this.muteReconfigure(d);const S=!v;d.audioTag.muted=S,this.updateCall(d)}}),_.length===0){this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n),console.log("[roomReconfigure] - Delete empty room",n),(a=this.context.logger)==null||a.log("[roomReconfigure] - Delete empty room",n),this.deleteRoomIfEmpty(n);return}if(_.length===1&&!v){const d=_[0];d.isOnHold().local||await this.holdCall(d._id,!0),this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}if(_.length===1&&v){const d=_[0];d.isOnHold().local&&d._automaticHold&&await this.unholdCall(d._id);const C=(((c=d.connection)==null?void 0:c.getSenders())||[])[0];if(d.connection&&C)try{await this.setupActiveStream();const S=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&(console.log("[roomReconfigure] - Call processVAD from roomReconfigure"),(e=this.context.logger)==null||e.log("[roomReconfigure] - Call processVAD from roomReconfigure"),this.processVAD(_[0],S));const R=S.getTracks();await C.replaceTrack(R[0]),this.muteReconfigure(d)}catch(S){console.error(S)}this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}_.length>1&&await this.doConference(_)}async doConference(n){var r,a,c,e,_,v,d;if(console.log("[doConference] - In doConference, sessions:",n),(r=this.context.logger)==null||r.log("[doConference] - In doConference, sessions:",n),n.length===0)return;const C=n[0].roomId,S=this.currentActiveRoomId===C;if(n.find(F=>F.roomId!==C))return;let R;try{R=await this.managedAudioContext.getContext()}catch(F){console.error("[doConference] Failed to get AudioContext:",F),(a=this.context.logger)==null||a.error("[doConference] Failed to get AudioContext:",F);return}const D=R.state;if(D!=="running")if(console.error(`[doConference] ERROR: AudioContext is not running! State: ${D}`),(c=this.context.logger)==null||c.error(`[doConference] ERROR: AudioContext is not running! State: ${D}`),D==="suspended"||D==="interrupted")try{await R.resume();const F=R.state;if(F!=="running"){console.error(`[doConference] Failed to resume AudioContext, state: ${F}`),(e=this.context.logger)==null||e.error(`[doConference] Failed to resume AudioContext, state: ${F}`);return}}catch(F){console.error("[doConference] Error resuming AudioContext:",F),(_=this.context.logger)==null||_.error("[doConference] Error resuming AudioContext:",F);return}else if(D==="closed"){console.error("[doConference] AudioContext is closed, cannot proceed"),(v=this.context.logger)==null||v.error("[doConference] AudioContext is closed, cannot proceed");return}else return;await this.cleanupConferenceNodes(C),this.conferenceNodes[C]={sources:new Map,destinations:new Map,gains:new Map};const H=this.conferenceNodes[C],K=new Map;console.log("[doConference] - Before sessions forEach, sessions:",n),(d=this.context.logger)==null||d.log("[doConference] - Before sessions forEach, sessions:",n),n.forEach((F,W)=>{var se,Z,Re;if(console.log("[doConference] - In sessions forEach, iteration for",F._id),(se=this.context.logger)==null||se.log("[doConference] - In sessions forEach, iteration for",F._id),F&&F.connection){const X=F.connection.getReceivers();console.log("[doConference] - Receivers list length for",F._id,X.length),(Z=this.context.logger)==null||Z.log("[doConference] - Receivers list length for",F._id,X.length),X.forEach((te,ye)=>{var Oe,Q,oe,me,_e,le;te.track.enabled=!F.localMuted;const de=(Oe=te.track)==null?void 0:Oe.id;(Q=te.track)==null||Q.readyState,(oe=te.track)==null||oe.kind;const Se=`${F._id}-${de}`;console.log("[doConference] - Gathering receiver tracks",F._id),console.log("[doConference] - Receiver track readyState",te.track.readyState),(me=this.context.logger)==null||me.log("[doConference] - Gathering receiver tracks",F._id),(_e=this.context.logger)==null||_e.log("[doConference] - Receiver track readyState",te.track.readyState),te.track&&te.track.readyState==="live"&&(console.log("[doConference] - Gathered receiver track",F._id),(le=this.context.logger)==null||le.log("[doConference] - Gathered receiver track",F._id),K.set(Se,te.track))})}else console.log("[doConference] - No session or RTC connection, session:",F),(Re=this.context.logger)==null||Re.log("[doConference] - No session or RTC connection, session:",F)}),await this.setupActiveStream(),await JA.forEach(n,async(F,W)=>{var se,Z,Re,X,te,ye;if(!F||!F.connection){console.log("[doConference] - Return because of no session or connection, session:",F),(se=this.context.logger)==null||se.log("[doConference] - Return because of no session or connection, session:",F);return}const Oe=R.createMediaStreamDestination();H.destinations.set(F._id,Oe);let Q=0;const oe=F.connection.getReceivers(),me=oe.length>0;if(console.log(`[doConference] Session ${F._id} has ${oe.length} receivers`),(Z=this.context.logger)==null||Z.log(`[doConference] Session ${F._id} has ${oe.length} receivers`),me||(console.warn(`[doConference] Session ${F._id} has no receivers yet. Will re-configure when track arrives.`),(Re=this.context.logger)==null||Re.warn(`[doConference] Session ${F._id} has no receivers yet. Will re-configure when track arrives.`)),K.forEach((de,Se)=>{var J,we,xe;if(console.log("[doConference] - In forEach receiverTracks for",F._id),(J=this.context.logger)==null||J.log("[doConference] - In forEach receiverTracks for",F._id),!Se.startsWith(F._id)){if(!de||de.readyState!=="live"){console.warn(`[doConference] Skipping invalid track ${de?.id||"unknown"} for session ${F._id}`),(we=this.context.logger)==null||we.warn(`[doConference] Skipping invalid track ${de?.id||"unknown"} for session ${F._id}`);return}try{const Dt=R.createMediaStreamSource(new MediaStream([de])),Ee=R.createGain(),ge=`${F._id}-${Se}`;Dt.connect(Ee),Ee.connect(Oe),console.log("[doConference] - In forEach connect track for",F._id),(xe=this.context.logger)==null||xe.log("[doConference] - In forEach connect track for",F._id),H.sources.set(ge,Dt),H.gains.set(ge,Ee),Q++}catch(Dt){console.error(Dt)}}}),S&&this.activeStreamValue)try{const de=this.activeStream,Se=R.createMediaStreamSource(de),J=R.createGain(),we=`${F._id}-local`;Se.connect(J),J.connect(Oe),H.sources.set(we,Se),H.gains.set(we,J)}catch(de){console.error(de)}else S&&(console.error(`Host room but no activeStreamValue - skipping host microphone for session ${F._id}`),(X=this.context.logger)==null||X.error(`Host room but no activeStreamValue - skipping host microphone for session ${F._id}`));const _e=F.connection.getSenders()[0],le=Oe.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&(console.log("[doConference] - Call processVAD from doConference"),(te=this.context.logger)==null||te.log("[doConference] - Call processVAD from doConference"),this.processVAD(F,Oe.stream)),_e&&le[0])try{console.log("[doConference] - Final replaceTrack for",F._id),(ye=this.context.logger)==null||ye.log("[doConference] - Final replaceTrack for",F._id),await _e.replaceTrack(le[0]),this.muteReconfigure(F)}catch(de){console.error(de)}})}processCallerMute(n,r){const a=this.extendedCalls[n];a&&a.connection.getReceivers().length&&(a.localMuted=r,a.connection.getReceivers().forEach(c=>{c.track.enabled=!r}),this.updateCall(a))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const r=this.extendedCalls[n];r._status===4?r.terminate({status_code:603,reason_phrase:"Decline"}):r._status!==8&&r.terminate()}handleSipResponseForRingback(n,r){var a,c,e,_,v;let d=null;if(this.extendedCalls[n])d=n;else{const S=Object.values(this.extendedCalls).find(R=>R.id===n||R._id===n||R.id&&R.id.includes(n)||R._id&&R._id.includes(n));S&&(d=S.id)}if(!d){(a=this.context.logger)==null||a.warn(`[handleSipResponseForRingback] Could not find session for identifier ${n}, status ${r}`);return}const C=this.extendedCalls[d];if(!C){(c=this.context.logger)==null||c.warn(`[handleSipResponseForRingback] Call not found in extendedCalls for ${d}`);return}if(C.direction==="outgoing"){if(r===Fu.TRYING||r===Fu.RINGING){if(this.ringbackTimers[d])return;this.ringbackSessionProgressReceived[d]=!1,this.ringbackTimers[d]=setTimeout(()=>{var S;this.ringbackSessionProgressReceived[d]||(this.startLocalRingbackTone(d),(S=this.context.logger)==null||S.log(`[handleSipResponseForRingback] Started local ringback tone for call ${d} after 2 seconds without 183`)),delete this.ringbackTimers[d]},2e3),(e=this.context.logger)==null||e.log(`[handleSipResponseForRingback] Started 2-second timer for call ${d} after receiving ${r}`)}r===Fu.SESSION_PROGRESS&&(this.ringbackSessionProgressReceived[d]=!0,this.ringbackTimers[d]&&(clearTimeout(this.ringbackTimers[d]),delete this.ringbackTimers[d],(_=this.context.logger)==null||_.log(`[handleSipResponseForRingback] Cancelled ringback timer for call ${d} - 183 received`)),this.stopLocalRingbackTone(d),(v=this.context.logger)==null||v.log(`[handleSipResponseForRingback] Stopped local ringback tone for call ${d} - 183 received with SDP`))}}async startLocalRingbackTone(n){var r,a;if(!this.ringbackAudioContexts[n])try{const c=await this.managedAudioContext.getContext(),e=c.createOscillator(),_=c.createOscillator(),v=c.createGain();e.frequency.value=440,_.frequency.value=480,e.type="sine",_.type="sine",v.gain.value=0,e.connect(v),_.connect(v),v.connect(c.destination),e.start(),_.start();const d={context:c,oscillator1:e,oscillator2:_,gainNode:v,intervalId:null};this.ringbackAudioContexts[n]=d;const C=()=>{if(!this.ringbackAudioContexts[n])return;const R=c.currentTime;v.gain.cancelScheduledValues(R),v.gain.setValueAtTime(0,R),v.gain.linearRampToValueAtTime(.3,R+.05),v.gain.linearRampToValueAtTime(0,R+1)};C();const S=setInterval(()=>{if(!this.ringbackAudioContexts[n]){clearInterval(S);return}C()},4e3);d.intervalId=S,this.ringbackAudioContexts[n]=d,(r=this.context.logger)==null||r.log(`[startLocalRingbackTone] Started ringback tone for session ${n}`)}catch(c){(a=this.context.logger)==null||a.error(`[startLocalRingbackTone] Error starting ringback tone for session ${n}:`,c),console.error(`[startLocalRingbackTone] Error starting ringback tone for session ${n}:`,c)}}stopLocalRingbackTone(n){var r,a;const c=this.ringbackAudioContexts[n];if(c)try{c.intervalId&&clearInterval(c.intervalId),c.oscillator1&&c.oscillator1.stop(),c.oscillator2&&c.oscillator2.stop(),c.gainNode&&c.gainNode.disconnect(),delete this.ringbackAudioContexts[n],(r=this.context.logger)==null||r.log(`[stopLocalRingbackTone] Stopped ringback tone for session ${n}`)}catch(e){(a=this.context.logger)==null||a.error(`[stopLocalRingbackTone] Error stopping ringback tone for session ${n}:`,e),console.error(`[stopLocalRingbackTone] Error stopping ringback tone for session ${n}:`,e),delete this.ringbackAudioContexts[n]}}cleanupRingbackTone(n){this.ringbackTimers[n]&&(clearTimeout(this.ringbackTimers[n]),delete this.ringbackTimers[n]),this.stopLocalRingbackTone(n),delete this.ringbackSessionProgressReceived[n]}transferCall(n,r){if(r.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[n];if(!a._is_confirmed&&!a._is_canceled){const c=`sip:${r}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${c}`]});return}this.updateCallStatus({callId:n,isTransferring:!0,isTransferred:!1}),a.refer(`sip:${r}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(a)}mergeCall(n){const r=Object.values(this.extendedCalls).filter(e=>e.roomId===n);if(r.length!==2)return;const a=r[0],c=r[1];!a||!c||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:c._id,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a))}mergeCallByIds(n,r){const a=Object.values(this.extendedCalls).find(e=>e._id===n),c=Object.values(this.extendedCalls).find(e=>e._id===r);if(!a||!c)throw new Error("Call ID is not provided");this.updateCallStatus({callId:n,isMerging:!0}),this.updateCallStatus({callId:r,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a)}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}setCallWaiting(n){this.isCallWaitingEnabled=n,this.context.emit("changeIsCallWaiting",n)}startCallTimer(n){this.removeTimeInterval(n);const r={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const a=setInterval(()=>{const c={...this.callTime[n]},e=KA(c);this.setCallTime({callId:n,...e})},1e3);this.setTimeInterval(n,a)}async setActiveRoom(n){const r=this.currentActiveRoomId;n!==r&&(this.currentActiveRoomId=n,await this.roomReconfigure(r),await this.roomReconfigure(n))}getNewRoomId(){const n=Object.keys(this.activeRooms);return n.length===0?1:parseInt(n.sort()[n.length-1])+1}async setupCall(n){var r,a;const c=n.session;if(this.getActiveCalls[c.id]!==void 0)return;const e=this.getNewRoomId(),_={started:new Date,incomingInProgress:!1,roomId:e};if(c.direction==="incoming")this.context.logger.log("New incoming call from",(a=(r=c._remote_identity)==null?void 0:r._uri)==null?void 0:a._user),_.incomingInProgress=!0,this.context.subscribe(Br.CALL_CONFIRMED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.startCallTimer(c.id))}),this.context.subscribe(Br.CALL_FAILED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.deleteRoomIfEmpty(e))});else if(c.direction==="outgoing"){const S=R=>{var D,H,K,F,W,se,Z,Re,X;const te=!!((D=R?.response)!=null&&D.body),ye=(K=(H=R?.response)==null?void 0:H.getHeader)==null?void 0:K.call(H,"Content-Type"),Oe=(W=(F=R?.response)==null?void 0:F.getHeader)==null?void 0:W.call(F,"Content-Length");console.log("PPP SDP Check:",{hasBody:te,contentType:ye,contentLength:Oe,bodyLength:((Z=(se=R?.response)==null?void 0:se.body)==null?void 0:Z.length)||0,bodyPreview:((X=(Re=R?.response)==null?void 0:Re.body)==null?void 0:X.substring(0,100))||"N/A"}),R.response&&R.response.status_code===Fu.SESSION_PROGRESS&&(this.startCallTimer(c.id),c.off("progress",S))};c.on("progress",S),c.once("confirmed",()=>{this.startCallTimer(c.id)})}const v=c,d=this.hasAutoAnswerHeaders(n),C=v.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);v.roomId=e,v.localMuted=!1,v.autoAnswer=C,C?this.addCall(v,!1):this.addCall(v),this.addCallStatus(c.id),this.addRoom(_),C&&this.answerCall(v._id)}removeCall(n){const r={...this.activeCalls};delete r[n],this.activeCalls={...r};const a={...this.extendedCalls};delete a[n],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const r=this.extendedCalls[n._id];if(!r)return;this.stopVUMeter("origin"),this.stopVUMeter(n._id);const a=r.roomId;this.removeCall(n._id),this.roomReconfigure(a).then(()=>{}).catch(c=>{console.error("Error reconfiguring room after call removal:",c)})}shouldTerminateNewSession(n){if(n.session.direction==="outgoing")return!1;const r=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||r}async newRTCSessionCallback(n){const r=n.session;if(this.shouldTerminateNewSession(n)){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}this.context.triggerListener({listenerType:Br.NEW_CALL,session:r,event:n}),r.on("ended",c=>{var e,_,v;if(this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_ENDED,session:r,event:c}),r.connection){const C=r.connection.connectionState;(C==="closed"||C==="disconnected")&&this.context.emit("connectionStateChange",{session:r,connectionState:C})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id),this.cleanupRingbackTone(r.id);const d=this.getActiveCalls[r.id];d&&this.activeCallListRemove(d),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(v=this.initialStreamValue)==null||v.getTracks().forEach(C=>C.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("progress",c=>{var e,_;this.context.logger.log("Session in progress for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_PROGRESS,session:r,event:c})}),r.on("failed",c=>{var e,_,v;if(this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_FAILED,session:r,event:c}),r.connection){const C=r.connection.connectionState;(C==="closed"||C==="disconnected")&&this.context.emit("connectionStateChange",{session:r,connectionState:C})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id),this.cleanupRingbackTone(r.id),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const d=this.getActiveCalls[r.id];d&&this.activeCallListRemove(d),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(v=this.initialStreamValue)==null||v.getTracks().forEach(C=>C.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("confirmed",c=>{var e,_;this.context.logger.log("Session confirmed for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_CONFIRMED,session:r,event:c}),this.updateCall(r),this.cleanupRingbackTone(r.id),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)});const a=c=>{c&&c.addEventListener("connectionstatechange",e=>{this.context.emit("connectionStateChange",{session:r,connectionState:c.connectionState})})};if(r.connection&&a(r.connection),r.on("peerconnection",({peerconnection:c})=>{a(c)}),await this.setupCall(n),r.direction==="outgoing"){const c=this.getActiveCalls[r.id].roomId;await this.setActiveRoom(c)}}setMuteWhenJoin(n){this.muteWhenJoinEnabled=n,this.context.emit("changeMuteWhenJoin",n)}setMicrophoneSensitivity(n){if(n<0||n>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=n,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(n){this.speakerVolumeValue=n,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=n,this.updateCall(r))})}setAutoAnswer(n){this.isAutoAnswer=n}setSelectedInputDevice(n){localStorage.setItem(Gu.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(Gu.SELECTED_OUTPUT_DEVICE,n),this.selectedMediaDevices.output=n,this.context.emit("changeActiveOutputMediaDevice",n)}setCallMetrics(n){const r={...n};delete r.callId,this.callMetrics={...this.callMetrics,[n.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(n){const r={...this.callMetrics};delete r[n],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(n){const r=new z1(this.metricConfig),a=r.createProbe(n.connection,{cid:n._id}),c=[];let e;a.onreport=_=>{Object.entries(_.audio).forEach(([C,S])=>{S.direction==="inbound"&&!c.includes(C)&&(c.push(C),e=C)});const v=_.audio[e];if(!v)return;const d=F1(v,B1);d.callId=n._id,this.setCallMetrics(d)},this.context.subscribe(Br.CALL_ENDED,_=>{_._id===n._id&&r.stopAllProbes()}),r.startAllProbes()}async setupVUMeter(n,r){await this.VUMeter.start(await this.managedAudioContext.getContext(),n,r)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){try{const n=Date.now(),r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((a,c)=>{a.stop()}),this.initialStreamValue=null),this.initialStreamValue=r}catch(n){throw n}}async triggerAddStream(n,r){var a,c;console.log(`[triggerAddStream] - For ${r._id}`),(a=this.context.logger)==null||a.log(`[triggerAddStream] - For ${r._id}`);const e=this.muteWhenJoin||this.isMuted;this.setIsMuted(e),this.initialStreamValue||await this.setupStream();const _=await this.managedAudioContext.getContext(),v=await Nd(_,this.initialStreamValue,this.microphoneInputLevel*2),d=this.isMuted||this.muteWhenJoin;v.getTracks().forEach(R=>{R.enabled=!d}),await this.setActiveStream(v),await r.connection.getSenders()[0].replaceTrack(v.getTracks()[0]);const C=new MediaStream([n.track]);!Object.values(this.extendedCalls).find(R=>R.audioTag&&R.audioTag.id===r._id)&&DA(C,r,this.selectedOutputDevice,this.speakerVolume);const S=r.roomId===this.currentActiveRoomId;r.audioTag&&(r.audioTag.muted=!S),await this.setupVUMeter(C,r._id),this.getCallQuality(r),this.updateCall(r),r.roomId!==void 0&&Object.values(this.extendedCalls).filter(R=>R.roomId===r.roomId).length>1&&(console.log(`[triggerAddStream] Re-configuring conference for room ${r.roomId} - track received for call ${r._id}`),(c=this.context.logger)==null||c.log(`[triggerAddStream] Re-configuring conference for room ${r.roomId} - track received for call ${r._id}`),setTimeout(()=>{this.roomReconfigure(r.roomId)},100)),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(r,v)}initCall(n,r,a=!1){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const c=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=c.id,r&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:c.id,roomId:this.currentActiveRoomId}),a)){const e=Object.values(this.extendedCalls).filter(_=>_.roomId===this.currentActiveRoomId&&_._id!==c.id);for(const _ of e)this.holdCall(_._id,!0)}c.connection.addEventListener("track",e=>{this.triggerAddStream(e,c)})}async processRoomChange({callId:n,roomId:r}){const a=this.extendedCalls[n];if(!a)return;const c=a.roomId;a.roomId=r,this.updateCall(a),await this.roomReconfigure(c),await this.roomReconfigure(r)}}class Y1{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n,r){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${n}@${this.context.sipDomain}`,r,this.sipOptions)}stop(n={}){this.context.terminateJanusSessions(n)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(n){this.context.changeMediaConstraints(n)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class X1{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(n){const r=this.extendedMessages[n];this.updateMSRPSession(r)}updateMSRPSession(n){this.activeMessages[n._id]=Tf(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:Tf(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,r){const a=this.msrpHistory[r.id]||[];a.push(n),this.msrpHistory={...this.msrpHistory,[r.id]:[...a]},this.context.emit("newMSRPMessage",{message:n,session:r})}messageTerminate(n){const r=this.extendedMessages[n];r._status!==8&&r.terminate()}addMessageSession(n){if(!n._id||this.getActiveMessages[n._id]!==void 0)return;const r=n;this.addMMSRPSession(r)}triggerMSRPListener({listenerType:n,session:r,event:a}){const c=this.context.listenersList[n];!c||!c.length||c.forEach(e=>{e(r,a)})}removeMMSRPSession(n){const r={...this.activeMessages};delete r[n],this.activeMessages={...r};const a={...this.extendedMessages};delete a[n],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){n.session._id||(n.session._id=n.request.call_id+n.request.from._parameters.tag);const r=n.session;r.on("ended",a=>{this.triggerMSRPListener({listenerType:Br.CALL_ENDED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("failed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_FAILED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_CONFIRMED,session:r,event:a}),this.updateMSRPSession(r)}),r.on("newMessage",a=>{this.addMSRPMessage(a,r)}),this.addMessageSession(r)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,r,a){if(n.length===0)return console.error("Target must be a valid string");const c=this.context.startMSRP(n,a);c.on("active",()=>{this.addMessageSession(c),c.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,r){const a=this.extendedMessages[n];if(!a)throw new Error(`MSRP session with id ${n} doesn't exist!`);a.sendMSRP(r)}}const Wu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Uf{constructor(n){this.opensips=null,this.session=null,this.name=null,this.name=n}setOpensips(n){this.opensips=n}setSession(n){this.session=n}kill(){this.opensips.kill(this.name)}}class J1 extends Uf{constructor(n,r){super(n),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=r}connect(n={}){this.opaqueId=this.session.generateOpaqueId();const r=kt.cloneArray(n.extraHeaders),a={from_tag:this.session._from_tag};n.fromUserName&&(a.from_uri=new ba("sip",n.fromUserName,this.session._ua.configuration.uri.host),r.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(a.from_display_name=n.fromDisplayName),r.push(`Contact: ${this.session._contact}`),r.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&r.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new On.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,r),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let n;this._connection.onicecandidate=r=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||r.candidate&&(this._candidates.push(r.candidate),clearTimeout(n),n=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(n){n.forEach(r=>{this._connection.addTrack(r)})}async _sendInitialRequest(){const n=new sl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const r={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(r),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},c=JSON.stringify(a);this._request.body=c,n.send()}_receiveInviteResponse(n){if(this._publisherSubscribeSent||!n.body)return;const r=JSON.parse(n.body);this.handleId=r.data.id;const a={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},c=[this.session.getPTypeHeader(ir.PUBLISHER)];this.session.sendRequest(ue.SUBSCRIBE,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{var _,v,d,C;if(e.status_code===200){if(this._subscribeSent=!0,e.body)try{const S=JSON.parse(e.body)||{};((v=(_=S.plugindata)==null?void 0:_.data)==null?void 0:v.videoroom)==="joined"&&this.session.myFeedList.push(S.plugindata.data.id),(C=(d=S.plugindata)==null?void 0:d.data)!=null&&C.publishers&&this.session.receivePublishers(S)}catch(S){console.error(S)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(n){const r=this._candidates.map(e=>({janus:"trickle",candidate:e,handle_id:this.handleId,session_id:this.session.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...n},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...r]},c=["Content-Type: application/json",this.session.getPTypeHeader(ir.ICE)];this.session.sendRequest(ue.INFO,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{this._configureSent=!0;const _=e.data.split(`\r
158
+ `,r),c===-1)return c;!o.substring(c+2,c+4).match(/(^\r\n)/)&&o.charAt(c+2).match(/(^\s+)/)?r=c+2:a=c}return a}function wA(o,n,r,a){let c;const e=n.indexOf(":",r),_=n.substring(r,e).trim(),v=n.substring(e+1,a).trim();switch(_.toLowerCase()){case"via":case"v":o.addHeader("via",v),o.getHeaders("via").length===1?(c=o.parseHeader("Via"),c&&(o.via=c,o.via_branch=c.branch)):c=0;break;case"from":case"f":o.setHeader("from",v),c=o.parseHeader("from"),c&&(o.from=c,o.from_tag=c.getParam("tag"));break;case"to":case"t":o.setHeader("to",v),c=o.parseHeader("to"),c&&(o.to=c,o.to_tag=c.getParam("tag"));break;case"record-route":if(c=Dd.parse(v,"Record_Route"),c===-1)c=void 0;else for(const d of c)o.addHeader("record-route",v.substring(d.possition,d.offset)),o.headers["Record-Route"][o.getHeaders("record-route").length-1].parsed=d.parsed;break;case"call-id":case"i":o.setHeader("call-id",v),c=o.parseHeader("call-id"),c&&(o.call_id=v);break;case"contact":case"m":if(c=Dd.parse(v,"Contact"),c===-1)c=void 0;else for(const d of c)o.addHeader("contact",v.substring(d.possition,d.offset)),o.headers.Contact[o.getHeaders("contact").length-1].parsed=d.parsed;break;case"content-length":case"l":o.setHeader("content-length",v),c=o.parseHeader("content-length");break;case"content-type":case"c":o.setHeader("content-type",v),c=o.parseHeader("content-type");break;case"cseq":o.setHeader("cseq",v),c=o.parseHeader("cseq"),c&&(o.cseq=c.value),o instanceof Za.IncomingResponse&&(o.method=c.method);break;case"max-forwards":o.setHeader("max-forwards",v),c=o.parseHeader("max-forwards");break;case"www-authenticate":o.setHeader("www-authenticate",v),c=o.parseHeader("www-authenticate");break;case"proxy-authenticate":o.setHeader("proxy-authenticate",v),c=o.parseHeader("proxy-authenticate");break;case"session-expires":case"x":o.setHeader("session-expires",v),c=o.parseHeader("session-expires"),c&&(o.session_expires=c.expires,o.session_expires_refresher=c.refresher);break;case"refer-to":case"r":o.setHeader("refer-to",v),c=o.parseHeader("refer-to"),c&&(o.refer_to=c);break;case"replaces":o.setHeader("replaces",v),c=o.parseHeader("replaces"),c&&(o.replaces=c);break;case"event":case"o":o.setHeader("event",v),c=o.parseHeader("event"),c&&(o.event=c);break;default:o.addHeader(_,v),c=0}return c===void 0?{error:`error parsing header "${_}"`}:!0}const SA={parseMessage:TA},_l=new wu("Registrator"),zu=10;class EA{constructor(n,r){this._reg_id=1,this._ua=n,this._transport=r,this._registrar=n.configuration.registrar_server,this._expires=n.configuration.register_expires,this._call_id=qs.createRandomToken(22),this._cseq=0,this._to_uri=n.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const a=this._contact.indexOf(">");if(a!==-1){const c=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=c}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(n){Array.isArray(n)||(n=[]),this._extraHeaders=n.slice()}setExtraContactParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){_l.debug("Register request in progress...");return}const n=this._extraHeaders.slice();n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),n.push(`Expires: ${this._expires}`);const r=new On.OutgoingRequest(ue.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n),a=new sl(this._ua,r,{onRequestTimeout:()=>{this._registrationFailure(null,ue.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,ue.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{if(c.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):{if(this._registering=!1,!c.hasHeader("Contact")){_l.debug("no Contact header in response to REGISTER, response ignored");break}const e=c.headers.Contact.reduce((C,S)=>C.concat(S.parsed),[]);let _=e.find(C=>this._sipInstance===C.getParam("+sip.instance")&&this._reg_id===parseInt(C.getParam("reg-id")));if(_||(_=e.find(C=>C.uri.user===this._ua.contact.uri.user)),!_){_l.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let v=_.getParam("expires");!v&&c.hasHeader("expires")&&(v=c.getHeader("expires")),v||(v=this._expires),v=Number(v),v<zu&&(v=zu);const d=v>64?v*1e3/2+Math.floor((v/2-32)*1e3*Math.random()):Math.floor(v*1e3/2);this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},d),_.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=_.getParam("temp-gruu").replace(/"/g,"")),_.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=_.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:c}));break}case/^423$/.test(c.status_code):{c.hasHeader("min-expires")?(this._expires=Number(c.getHeader("min-expires")),this._expires<zu&&(this._expires=zu),this.register()):(_l.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(c,ue.causes.SIP_FAILURE_CODE));break}default:{const e=qs.sipErrorCause(c.status_code);this._registrationFailure(c,e)}}}});this._registering=!0,a.send()}unregister(n={}){if(!this._registered){_l.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const r=this._extraHeaders.slice();n.all?r.push(`Contact: *${this._extraContactParams}`):r.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),r.push("Expires: 0");const a=new On.OutgoingRequest(ue.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r);new sl(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,ue.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,ue.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{switch(!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):this._unregistered(c);break;default:{const e=qs.sipErrorCause(c.status_code);this._unregistered(c,e)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(n,r){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:r}))}_unregistered(n,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:r||null})}}const un=console,fi={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},CA=dA;class AA extends CA{constructor(n){super(n),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this.optionsInterval=null,this.lastOptionsTimestamp=null,this.lastRegisterTimestamp=null,this._registrator=new EA(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(n,r){return super.call(n,r)}joinVideoCall(n,r,a){un.debug("call()");const c=new qu(this);return c.configureMedia({audio:!0,video:!0}),c.connect(n,r,a),c}startScreenShare(){un.debug("startScreenShare()");for(const n in this._janus_sessions)this._janus_sessions[n].connectScreenShare()}changeMediaConstraints(n){for(const r in this._janus_sessions)this._janus_sessions[r].changeMediaConstraints(n)}startBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].connectBlur()}stopBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].stopBlur()}_loadConfig(n){try{pl.load(this._configuration,n)}catch(e){throw e}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=qs.newUUID());let r;typeof window<"u"&&typeof window.document<"u"?r=window?.navigator.userAgent:typeof self<"u"&&self.navigator&&(r=self.navigator.userAgent),r+=" "+bt.USER_AGENT,this._configuration.user_agent=n.overrideUserAgent&&typeof n.overrideUserAgent=="function"?n.overrideUserAgent(r):r,n.onTransportCallback&&typeof n.onTransportCallback=="function"&&(this.onTransportCallback=n.onTransportCallback),this._configuration.jssip_id=qs.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new PC(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=IA.bind(this),this._transport.onconnect=RA.bind(this),this._transport.ondisconnect=xA.bind(this),this._transport.ondata=$A.bind(this)}catch(e){throw un.warn(e),new di.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ba("sip",qs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(e={}){const _=e.anonymous||null,v=e.outbound||null;let d="<";return _?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),v&&(_?!this.temp_gruu:!this.pub_gruu)&&(d+=";ob"),d+=">",d}};const c=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const e in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,e)&&(c.indexOf(e)!==-1?Object.defineProperty(this._configuration,e,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,e,{writable:!1,configurable:!1}));un.debug("configuration parameters after validation:");for(const e in this._configuration)if(Object.prototype.hasOwnProperty.call(pl.settings,e))switch(e){case"uri":case"registrar_server":un.debug(`- ${e}: ${this._configuration[e]}`);break;case"password":case"ha1":case"authorization_jwt":un.debug(`- ${e}: NOT SHOWN`);break;default:un.debug(`- ${e}: ${JSON.stringify(this._configuration[e])}`)}}newMSRPSession(n,r){n.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",r)}newJanusSession(n,r){this._janus_sessions[n.id]=n,this.newStreamPlugins.forEach(a=>{a.setSession(n)}),this.processStreamPlugins.forEach(a=>{a.setSession(n)}),this.emit("newJanusSession",r)}kill(){}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(n){var r,a,c,e;const _=n.method;if(n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){un.debug("Request-URI does not point to us"),n.method!==bt.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===bt.SIPS){n.reply_sl(416);return}if(Ir.checkTransaction(this,n))return;if(_===bt.INVITE?new Ir.InviteServerTransaction(this,this._transport,n):_!==bt.ACK&&_!==bt.CANCEL&&new Ir.NonInviteServerTransaction(this,this._transport,n),_===bt.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const C=Date.now(),S=this.lastOptionsTimestamp>C-35e3,R=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>C;S&&R&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){n.reply(200);return}new w_.Options(this).init_incoming(n)}else if(_===bt.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new w_.Message(this).init_incoming(n)}else if(_===bt.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let v,d;if(n.to_tag)if(v=this._findDialog(n.call_id,n.from_tag,n.to_tag),v)v.receiveRequest(n);else if(_===bt.NOTIFY)if(d=this._findSession(n),d)d.receiveRequest(n);else{if(n.body)try{const C=JSON.parse(n.body)||{};(a=(r=C.plugindata)==null?void 0:r.data)!=null&&a.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(C),(e=(c=C.plugindata)==null?void 0:c.data)!=null&&e.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(C.plugindata.data.unpublished)}catch(C){console.error(C)}n.reply(200)}else _!==bt.ACK&&n.reply(481);else switch(_){case bt.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const C=n.replaces;v=this._findDialog(C.call_id,C.from_tag,C.to_tag),v?(d=v.owner,d.isEnded()?n.reply(603):d.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(d=new kd(this),d.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(d=new bC(this),d.init_incoming(n));else un.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case bt.BYE:n.reply(481);break;case bt.CANCEL:d=this._findSession(n),d?d.receiveRequest(n):un.debug("received CANCEL request for a non existent session");break;case bt.ACK:break;case bt.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,r){un.debug("startMSRP()",r);const a=new kd(this);return a.connect(n),a}startJanus(n,r){un.debug("startJanus()",r);const a=new kd(this);return a.connect(n),a}terminateMSRPSessions(n){un.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(n)}terminateJanusSessions(n){un.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(n)}enableJanusAudio(n){un.debug("enableJanusAudio()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startAudio():this._janus_sessions[r].stopAudio())}enableJanusVideo(n){un.debug("enableJanusVideo()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startVideo():this._janus_sessions[r].stopVideo())}terminateAllSessions(){for(const n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){un.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch(r){console.error(r)}}}stop(n=!0){if(un.debug("stop()"),this._dynConfiguration={},this._status===fi.STATUS_USER_CLOSED){un.debug("UA already closed");return}this._registrator.close();const r=Object.keys(this._sessions).length;n&&this.terminateAllSessions();for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){un.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){un.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(c){console.error(c)}this._status=fi.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&r===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function IA(o){this.emit("connecting",o)}function RA(o){this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_READY,this._error=null,this.emit("connected",o),this._dynConfiguration.register&&this._registrator.register())}function xA(o){const n=["nict","ict","nist","ist"];for(const r of n)for(const a in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],a)&&this._transactions[r][a].onTransportError();this.emit("disconnected",o),this._registrator.onTransportClosed(),this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_NOT_READY,this._error=fi.NETWORK_ERROR)}function $A(o){const n=o.transport;let r=o.message;const a=r;if(r=SA.parseMessage(r,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(r,a),!!r&&!(this._status===fi.STATUS_USER_CLOSED&&r instanceof Za.IncomingRequest)&&QC(r,this,n)){if(r instanceof Za.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof Za.IncomingResponse){let c;switch(r.method){case bt.INVITE:if(c=this._transactions.ict[r.via_branch],c){const e=r.status_code;if((e===100||e===180||e===183)&&this.audio&&typeof this.audio.handleSipResponseForRingback=="function"){let _=null;if(c._session&&c._session.id)_=c._session.id;else if(r.call_id&&this._sessions){const v=Object.values(this._sessions).find(d=>d._id&&d._id.includes(r.call_id)||d.id&&d.id.includes(r.call_id)||d.call_id===r.call_id);v&&(v.id||v._id)&&(_=v.id||v._id)}else r.call_id&&(_=r.call_id);_&&this.audio.handleSipResponseForRingback(_,e)}c.receiveResponse(r)}break;case bt.ACK:break;default:c=this._transactions.nict[r.via_branch],c&&c.receiveResponse(r);break}}}}const OA=["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"],kA=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function yf(o){const n={};return OA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n.localHold=o._localHold,n}function Tf(o){const n={};return kA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n}async function Nd(o,n,r){const a=o.createMediaStreamSource(n),c=o.createMediaStreamDestination(),e=o.createGain();return a.connect(e),e.connect(c),e.gain.value=r,c.stream}function DA(o,n,r,a){if(bf())return;const c=document.createElement("audio");c.id=n._id,c.className="audioTag",c.srcObject=o,c.setSinkId(r),c.volume=a,c.play(),n.audioTag=c}function NA(o){if(o&&typeof o.log=="function"&&typeof o.warn=="function"&&typeof o.error=="function")return!0}function bf(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const MA=mn,UA=Hr(),Jn=new MA("WebSocketInterface");var PA=class{constructor(o){Jn.debug('new() [url:"%s"]',o),this._url=o,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=UA.parse(o,"absoluteURI");if(n===-1)throw Jn.warn(`invalid WebSocket URI: ${o}`),new TypeError(`Invalid argument: ${o}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Jn.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${o}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(o){this._via_transport=o.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Jn.debug("connect()"),this.isConnected()){Jn.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Jn.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Jn.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(o){this._onError(o)}}disconnect(){Jn.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(o){return Jn.debug("send()"),this.isConnected()?(this._ws.send(o),!0):(Jn.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){Jn.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:o,code:n,reason:r}){Jn.debug(`WebSocket ${this._url} closed`),o===!1&&Jn.debug("WebSocket abrupt disconnection"),this.ondisconnect(!o,n,r)}_onMessage({data:o}){Jn.debug("received WebSocket message"),this.ondata(o)}_onError(o){Jn.warn(`WebSocket ${this._url} error: `,o)}};const Md=Pl,LA=bt,qA=Ls,HA=xn(),zA=mf,FA=Ms(),BA=td(),VA=Hr(),jA=PA;Wa("JsSIP")("version %s",Md.version);var GA={C:LA,Exceptions:qA,Utils:HA,UA:zA,URI:FA,NameAddrHeader:BA,WebSocketInterface:jA,Grammar:VA,debug:Wa,get name(){return Md.title},get version(){return Md.version}};const WA=Qt(GA);function Ud(o){return o<10?`0${o}`:`${o}`}function KA(o){let n=o.hours||0,r=o.minutes||0,a=o.seconds||0;a++,a===60&&(a=0,r++,r===60&&(r=0,n++));const c=`${Ud(n)}:${Ud(r)}:${Ud(a)}`;return{seconds:a,minutes:r,hours:n,formatted:c}}function YA(o){let n=0;for(let r=0;r<o.length;r++)n+=o[r]*o[r];return Math.sqrt(n/o.length)}async function XA(o,n,r=150){const a=n.createMediaStreamSource(o),c=n.createDelay();c.delayTime.value=r/1e3;const e=n.createGain();e.gain.value=0;const _=n.createMediaStreamDestination();return a.connect(c).connect(e).connect(_),{stream:_.stream,setSpeaking:v=>{e.gain.value=v?1:0}}}var Mn={};Mn.forEach=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)if(c in o){const e=Promise.resolve(o[c]).then(_=>n.call(r||globalThis,_,c,o));a.push(e)}await Promise.all(a)},Mn.forEachSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)a in o&&await n.call(r||globalThis,await o[a],a,o)},Mn.map=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=Promise.resolve(o[c]).then(e=>n.call(r||globalThis,e,c,o)));return Promise.all(a)},Mn.mapSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=await n.call(r||globalThis,await o[c],c,o));return a},Mn.find=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a();let e=1;for(let _=0;_<o.length;_++){const v=d=>{d?a(o[_]):e===o.length&&a(),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(v).catch(c)}}),Mn.findSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return o[a]},Mn.findIndex=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(-1);let e=1;for(let _=0;_<o.length;_++){const v=d=>{d?a(_):e===o.length&&a(-1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(v).catch(c)}}),Mn.findIndexSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return a},Mn.some=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!1);let e=1;for(let _=0;_<o.length;_++){if(!(_ in o)){e++;continue}const v=d=>{d?a(!0):e===o.length&&a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(v).catch(c)}}),Mn.someSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&await n.call(r||globalThis,await o[a],a,o))return!0;return!1},Mn.every=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!0);let e=1;for(let _=0;_<o.length;_++){if(!(_ in o)){e++;continue}const v=d=>{d?e===o.length&&a(!0):a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(v).catch(c)}}),Mn.everySeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&!await n.call(r||globalThis,await o[a],a,o))return!1;return!0},Mn.filter=(o,n,r)=>new Promise(async(a,c)=>{const e=[];for(let v=0;v<o.length;v++)v in o&&(e[v]=Promise.resolve(o[v]).then(d=>n.call(r||globalThis,d,v,o)).catch(c));const _=[];for(let v=0;v<e.length;v++)await e[v]&&_.push(await o[v]);a(_)}),Mn.filterSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&await n.call(r||globalThis,await o[c],c,o)&&a.push(await o[c]);return a},Mn.reduce=async(o,n,r)=>{if(o.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let a,c;for(r!==void 0?(c=r,a=0):(c=o[0],a=1),a;a<o.length;a++)a in o&&(c=await n(await c,await o[a],a,o));return c};var wf={};(function(o){const n=Mn;Object.keys(n).forEach(r=>{const a=r.charAt(0).toUpperCase()+r.slice(1);o[`async${a}`]=async function(...c){return n[r](this,...c)}})})(wf);var JA=Object.assign(Mn,{instanceMethods:wf});const Br={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},Fu={TRYING:100,RINGING:180,SESSION_PROGRESS:183,OK:200,MOVED_TEMPORARILY:302,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,REQUEST_TIMEOUT:408,BUSY_HERE:486,REQUEST_TERMINATED:487,INTERNAL_SERVER_ERROR:500,SERVICE_UNAVAILABLE:503,BUSY_EVERYWHERE:600,DECLINE:603};var QA={exports:{}};(function(o){var n=function(r){var a=Object.prototype,c=a.hasOwnProperty,e=Object.defineProperty||function(Ee,ge,ie){Ee[ge]=ie.value},_,v=typeof Symbol=="function"?Symbol:{},d=v.iterator||"@@iterator",C=v.asyncIterator||"@@asyncIterator",S=v.toStringTag||"@@toStringTag";function R(Ee,ge,ie){return Object.defineProperty(Ee,ge,{value:ie,enumerable:!0,configurable:!0,writable:!0}),Ee[ge]}try{R({},"")}catch{R=function(Ee,ge,ie){return Ee[ge]=ie}}function D(Ee,ge,ie,st){var We=ge&&ge.prototype instanceof Re?ge:Re,ht=Object.create(We.prototype),It=new we(st||[]);return e(ht,"_invoke",{value:le(Ee,ie,It)}),ht}r.wrap=D;function H(Ee,ge,ie){try{return{type:"normal",arg:Ee.call(ge,ie)}}catch(st){return{type:"throw",arg:st}}}var K="suspendedStart",F="suspendedYield",W="executing",se="completed",Z={};function Re(){}function X(){}function te(){}var ye={};R(ye,d,function(){return this});var Oe=Object.getPrototypeOf,Q=Oe&&Oe(Oe(xe([])));Q&&Q!==a&&c.call(Q,d)&&(ye=Q);var oe=te.prototype=Re.prototype=Object.create(ye);X.prototype=te,e(oe,"constructor",{value:te,configurable:!0}),e(te,"constructor",{value:X,configurable:!0}),X.displayName=R(te,S,"GeneratorFunction");function me(Ee){["next","throw","return"].forEach(function(ge){R(Ee,ge,function(ie){return this._invoke(ge,ie)})})}r.isGeneratorFunction=function(Ee){var ge=typeof Ee=="function"&&Ee.constructor;return ge?ge===X||(ge.displayName||ge.name)==="GeneratorFunction":!1},r.mark=function(Ee){return Object.setPrototypeOf?Object.setPrototypeOf(Ee,te):(Ee.__proto__=te,R(Ee,S,"GeneratorFunction")),Ee.prototype=Object.create(oe),Ee},r.awrap=function(Ee){return{__await:Ee}};function _e(Ee,ge){function ie(ht,It,qe,Ue){var wt=H(Ee[ht],Ee,It);if(wt.type==="throw")Ue(wt.arg);else{var Yt=wt.arg,Xe=Yt.value;return Xe&&typeof Xe=="object"&&c.call(Xe,"__await")?ge.resolve(Xe.__await).then(function(Je){ie("next",Je,qe,Ue)},function(Je){ie("throw",Je,qe,Ue)}):ge.resolve(Xe).then(function(Je){Yt.value=Je,qe(Yt)},function(Je){return ie("throw",Je,qe,Ue)})}}var st;function We(ht,It){function qe(){return new ge(function(Ue,wt){ie(ht,It,Ue,wt)})}return st=st?st.then(qe,qe):qe()}e(this,"_invoke",{value:We})}me(_e.prototype),R(_e.prototype,C,function(){return this}),r.AsyncIterator=_e,r.async=function(Ee,ge,ie,st,We){We===void 0&&(We=Promise);var ht=new _e(D(Ee,ge,ie,st),We);return r.isGeneratorFunction(ge)?ht:ht.next().then(function(It){return It.done?It.value:ht.next()})};function le(Ee,ge,ie){var st=K;return function(We,ht){if(st===W)throw new Error("Generator is already running");if(st===se){if(We==="throw")throw ht;return Dt()}for(ie.method=We,ie.arg=ht;;){var It=ie.delegate;if(It){var qe=de(It,ie);if(qe){if(qe===Z)continue;return qe}}if(ie.method==="next")ie.sent=ie._sent=ie.arg;else if(ie.method==="throw"){if(st===K)throw st=se,ie.arg;ie.dispatchException(ie.arg)}else ie.method==="return"&&ie.abrupt("return",ie.arg);st=W;var Ue=H(Ee,ge,ie);if(Ue.type==="normal"){if(st=ie.done?se:F,Ue.arg===Z)continue;return{value:Ue.arg,done:ie.done}}else Ue.type==="throw"&&(st=se,ie.method="throw",ie.arg=Ue.arg)}}}function de(Ee,ge){var ie=ge.method,st=Ee.iterator[ie];if(st===_)return ge.delegate=null,ie==="throw"&&Ee.iterator.return&&(ge.method="return",ge.arg=_,de(Ee,ge),ge.method==="throw")||ie!=="return"&&(ge.method="throw",ge.arg=new TypeError("The iterator does not provide a '"+ie+"' method")),Z;var We=H(st,Ee.iterator,ge.arg);if(We.type==="throw")return ge.method="throw",ge.arg=We.arg,ge.delegate=null,Z;var ht=We.arg;if(!ht)return ge.method="throw",ge.arg=new TypeError("iterator result is not an object"),ge.delegate=null,Z;if(ht.done)ge[Ee.resultName]=ht.value,ge.next=Ee.nextLoc,ge.method!=="return"&&(ge.method="next",ge.arg=_);else return ht;return ge.delegate=null,Z}me(oe),R(oe,S,"Generator"),R(oe,d,function(){return this}),R(oe,"toString",function(){return"[object Generator]"});function Se(Ee){var ge={tryLoc:Ee[0]};1 in Ee&&(ge.catchLoc=Ee[1]),2 in Ee&&(ge.finallyLoc=Ee[2],ge.afterLoc=Ee[3]),this.tryEntries.push(ge)}function J(Ee){var ge=Ee.completion||{};ge.type="normal",delete ge.arg,Ee.completion=ge}function we(Ee){this.tryEntries=[{tryLoc:"root"}],Ee.forEach(Se,this),this.reset(!0)}r.keys=function(Ee){var ge=Object(Ee),ie=[];for(var st in ge)ie.push(st);return ie.reverse(),function We(){for(;ie.length;){var ht=ie.pop();if(ht in ge)return We.value=ht,We.done=!1,We}return We.done=!0,We}};function xe(Ee){if(Ee){var ge=Ee[d];if(ge)return ge.call(Ee);if(typeof Ee.next=="function")return Ee;if(!isNaN(Ee.length)){var ie=-1,st=function We(){for(;++ie<Ee.length;)if(c.call(Ee,ie))return We.value=Ee[ie],We.done=!1,We;return We.value=_,We.done=!0,We};return st.next=st}}return{next:Dt}}r.values=xe;function Dt(){return{value:_,done:!0}}return we.prototype={constructor:we,reset:function(Ee){if(this.prev=0,this.next=0,this.sent=this._sent=_,this.done=!1,this.delegate=null,this.method="next",this.arg=_,this.tryEntries.forEach(J),!Ee)for(var ge in this)ge.charAt(0)==="t"&&c.call(this,ge)&&!isNaN(+ge.slice(1))&&(this[ge]=_)},stop:function(){this.done=!0;var Ee=this.tryEntries[0],ge=Ee.completion;if(ge.type==="throw")throw ge.arg;return this.rval},dispatchException:function(Ee){if(this.done)throw Ee;var ge=this;function ie(Ue,wt){return ht.type="throw",ht.arg=Ee,ge.next=Ue,wt&&(ge.method="next",ge.arg=_),!!wt}for(var st=this.tryEntries.length-1;st>=0;--st){var We=this.tryEntries[st],ht=We.completion;if(We.tryLoc==="root")return ie("end");if(We.tryLoc<=this.prev){var It=c.call(We,"catchLoc"),qe=c.call(We,"finallyLoc");if(It&&qe){if(this.prev<We.catchLoc)return ie(We.catchLoc,!0);if(this.prev<We.finallyLoc)return ie(We.finallyLoc)}else if(It){if(this.prev<We.catchLoc)return ie(We.catchLoc,!0)}else if(qe){if(this.prev<We.finallyLoc)return ie(We.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Ee,ge){for(var ie=this.tryEntries.length-1;ie>=0;--ie){var st=this.tryEntries[ie];if(st.tryLoc<=this.prev&&c.call(st,"finallyLoc")&&this.prev<st.finallyLoc){var We=st;break}}We&&(Ee==="break"||Ee==="continue")&&We.tryLoc<=ge&&ge<=We.finallyLoc&&(We=null);var ht=We?We.completion:{};return ht.type=Ee,ht.arg=ge,We?(this.method="next",this.next=We.finallyLoc,Z):this.complete(ht)},complete:function(Ee,ge){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"&&ge&&(this.next=ge),Z},finish:function(Ee){for(var ge=this.tryEntries.length-1;ge>=0;--ge){var ie=this.tryEntries[ge];if(ie.finallyLoc===Ee)return this.complete(ie.completion,ie.afterLoc),J(ie),Z}},catch:function(Ee){for(var ge=this.tryEntries.length-1;ge>=0;--ge){var ie=this.tryEntries[ge];if(ie.tryLoc===Ee){var st=ie.completion;if(st.type==="throw"){var We=st.arg;J(ie)}return We}}throw new Error("illegal catch attempt")},delegateYield:function(Ee,ge,ie){return this.delegate={iterator:xe(Ee),resultName:ge,nextLoc:ie},this.method==="next"&&(this.arg=_),Z}},r}(o.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})(QA);var Sf={exports:{}};(function(o){(function(n,r){o.exports?o.exports=r():n.log=r()})(Eb,function(){var n=function(){},r="undefined",a=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),c=["trace","debug","info","warn","error"];function e(F,W){var se=F[W];if(typeof se.bind=="function")return se.bind(F);try{return Function.prototype.bind.call(se,F)}catch{return function(){return Function.prototype.apply.apply(se,[F,arguments])}}}function _(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function v(F){return F==="debug"&&(F="log"),typeof console===r?!1:F==="trace"&&a?_:console[F]!==void 0?e(console,F):console.log!==void 0?e(console,"log"):n}function d(F,W){for(var se=0;se<c.length;se++){var Z=c[se];this[Z]=se<F?n:this.methodFactory(Z,F,W)}this.log=this.debug}function C(F,W,se){return function(){typeof console!==r&&(d.call(this,W,se),this[F].apply(this,arguments))}}function S(F,W,se){return v(F)||C.apply(this,arguments)}function R(F,W,se){var Z=this,Re;W=W??"WARN";var X="loglevel";typeof F=="string"?X+=":"+F:typeof F=="symbol"&&(X=void 0);function te(oe){var me=(c[oe]||"silent").toUpperCase();if(!(typeof window===r||!X)){try{window.localStorage[X]=me;return}catch{}try{window.document.cookie=encodeURIComponent(X)+"="+me+";"}catch{}}}function ye(){var oe;if(!(typeof window===r||!X)){try{oe=window.localStorage[X]}catch{}if(typeof oe===r)try{var me=window.document.cookie,_e=me.indexOf(encodeURIComponent(X)+"=");_e!==-1&&(oe=/^([^;]+)/.exec(me.slice(_e))[1])}catch{}return Z.levels[oe]===void 0&&(oe=void 0),oe}}function Oe(){if(!(typeof window===r||!X)){try{window.localStorage.removeItem(X);return}catch{}try{window.document.cookie=encodeURIComponent(X)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}Z.name=F,Z.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},Z.methodFactory=se||S,Z.getLevel=function(){return Re},Z.setLevel=function(oe,me){if(typeof oe=="string"&&Z.levels[oe.toUpperCase()]!==void 0&&(oe=Z.levels[oe.toUpperCase()]),typeof oe=="number"&&oe>=0&&oe<=Z.levels.SILENT){if(Re=oe,me!==!1&&te(oe),d.call(Z,oe,F),typeof console===r&&oe<Z.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+oe},Z.setDefaultLevel=function(oe){W=oe,ye()||Z.setLevel(oe,!1)},Z.resetLevel=function(){Z.setLevel(W,!1),Oe()},Z.enableAll=function(oe){Z.setLevel(Z.levels.TRACE,oe)},Z.disableAll=function(oe){Z.setLevel(Z.levels.SILENT,oe)};var Q=ye();Q==null&&(Q=W),Z.setLevel(Q,!1)}var D=new R,H={};D.getLogger=function(F){if(typeof F!="symbol"&&typeof F!="string"||F==="")throw new TypeError("You must supply a name when creating a logger.");var W=H[F];return W||(W=H[F]=new R(F,D.getLevel(),D.methodFactory)),W};var K=typeof window!==r?window.log:void 0;return D.noConflict=function(){return typeof window!==r&&window.log===D&&(window.log=K),D},D.getLoggers=function(){return H},D.default=D,D})})(Sf);var Vn=Sf.exports;const Hs=()=>`${new Date().toISOString()} | metrics`,zs=(o,n,r)=>`${o} | ${n} | ${r}`;Vn.setDefaultLevel(Vn.levels.TRACE);const ZA=o=>{Vn.info(zs(Hs(),"log ",`set log level to ${o?"verbose":"info"}`)),Vn.setLevel(o?Vn.levels.TRACE:Vn.levels.INFO)},e1=o=>{const n=[...Object.keys(Vn.levels)];n.includes(o)?(Vn.info(zs(Hs(),"log ",`update log level to ${o.toLowerCase()}`)),Vn.setLevel(o)):Vn.warn(zs(Hs(),"log ","Incorrect log level please choose one of "),n)},Rt=(o,n,r)=>{r?Vn.debug(zs(Hs(),o,n),r):Vn.debug(zs(Hs(),o,n))},Pd=(o,n)=>{Vn.info(zs(Hs(),o,n))},wa=(o,n)=>{Vn.info(zs(Hs(),o,n))},Bu=(o,n)=>{Vn.warn(zs(Hs(),o,n))},so=(o,n)=>{Vn.error(zs(Hs(),o,n))};function t1(o){return Math.floor(Math.random()*o).toString()}function Ef(o,n){let r=n;return o.forEach(a=>{r=r.replace(a,"")}),r}function n1(o,n){let r="";for(let a=0;a<n;a+=1)r+=o[t1(o.length)];return r}function r1({length:o=20,useLetters:n=!0,useNumbers:r=!0,includeSymbols:a=[],excludeSymbols:c=[]}={}){let e="abcdefghijklmnopqrstuvwxyz",_="0123456789",v=[],d=[],C=[];return n&&(c.length&&(e=Ef(c,e)),d=e.split("")),r&&(c.length&&(_=Ef(c,_)),C=_.split("")),v=[...d,...C,...a],n1(v,o)}var s1=r1;const fl=Qt(s1),i1=()=>"WebRTCMetrics",a1=()=>"5.0.3",zt={INBOUND:"inbound",OUTBOUND:"outbound"},Fs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ml={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},o1=()=>({delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}),Cf={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:zt.INBOUND},Af={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:zt.OUTBOUND},If={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:zt.INBOUND},Rf={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:zt.OUTBOUND},l1=o=>{const n={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(o){const r={...o,audio:{},video:{},data:{...o.data},network:{...o.network},experimental:{...o.experimental}};return Object.keys(o.audio).forEach(a=>{r.audio[a]={...o.audio[a]}}),Object.keys(o.video).forEach(a=>{r.video[a]={...o.video[a]}}),r}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},u1={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${fl()}`,cid:`c-${fl()}`,uid:`u-${fl()}`,record:!1,ticket:!0},Vr={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},ve={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"},ae={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},gl={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Ld={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},Me={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},qd="config ",c1=(o,n={},r)=>{const a={...r,...n};return n.pname||Bu(qd,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),n.cid||Bu(qd,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),n.uid||Bu(qd,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),a.pc=o,a},d1=(o={})=>{const n={...u1,...o};return n.name=i1(),n.version=a1(),n},vl=(o,n,r,a=!1,c)=>{let e=o.map(_=>{if(!r)return _[n];if(!c)return _[n][r];const v=_[n][c];return v?v[r]:null});return e=e.filter(_=>a?Number.isFinite(_)&&_>0:Number.isFinite(_)),e.length===0?[]:e},mi=o=>o.reduce((n,r)=>n+r,0)/o.length,h1=()=>`probe-${fl()}`,p1=()=>`coltr-${fl()}`,xf=o=>new Promise(n=>setTimeout(n,o)),Hd=(o,n,r)=>{n?o.call(n,r):o(r)},Zt=(o,n,r,a)=>{const c=vl(o,n,r,!0,a);if(c.length===0)return null;const e=c.reduce((_,v)=>_+v,0)/c.length;return e===0?null:c.map(_=>Math.abs(e-_)).reduce((_,v)=>_+v,0)/c.length*100/e},nn=(o,n,r,a=!1,c)=>{const e=vl(o,n,r,a,c);return e.length===0?null:e.reduce((_,v)=>_+v,0)/e.length},Sa=(o,n,r)=>vl(o,n,r).reduce((a,c)=>a+c,0),en=(o,n,r,a)=>{const c=vl(o,n,r,!0,a);return c.length===0?null:Math.min(...c)},tn=(o,n,r,a)=>{const c=vl(o,n,r,!1,a);return c.length===0?null:Math.max(...c)},Un=(o,n,r,a)=>{const c=o.slice().pop();if(!c)return null;if(!r)return c[n];if(!a)return c[n][r];const e=c[n][a];return e?e[r]:null},_1=o=>o.slice().pop(),wn=(o,n,r)=>{if(!n)return null;const a={};let c=n[ae.AUDIO][o];c||(c=r===zt.INBOUND?{...Cf}:{...Af}),a[ae.AUDIO]=c;let e=n[ae.VIDEO][o];return e||(e=r===zt.INBOUND?{...If}:{...Rf}),a[ae.VIDEO]=e,a},yl="exporter ",f1="2.0",$f=(o,n,r)=>{if(!o||o.length===0)return 0;const a=o[o.length-1];if(!a)return 0;const c=a[n][r];if(c){const e=c.total_rtt_ms_out,_=c.total_rtt_measure_out;return!_||!e?nn(o,n,"delta_rtt_ms_out",!1,r):Number(e/_)}return null},m1=(o,n)=>{if(!o||o.length===0)return 0;const r=o[o.length-1];if(!r)return 0;const a=r[n].total_rtt_connectivity_ms,c=r[n].total_rtt_connectivity_measure;return!c||!a?nn(o,n,"delta_rtt_connectivity_ms"):Number(a/c)},g1=o=>Un(o,"network","local_candidate_type")!=="relay"?`direct/${Un(o,"network","local_candidate_protocol")}`:`turn/${Un(o,"network","local_candidate_relay_protocol")}`,v1=o=>{const n=Un(o,"network","remote_candidate_type"),r=Un(o,"network","remote_candidate_protocol");return n!=="relay"?`direct/${r}`:`turn/${r}`};class y1{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){Pd(yl,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){Pd(yl,"stop() - stop exporter...");const n=new Date;return this._end=n.toJSON(),n}saveReferenceReport(n){this._referenceReport=n}getReferenceReport(){return this._referenceReport}addReport(n){this._cfg.ticket&&(Rt(yl,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){Pd(yl,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Rt(yl,"ticket() - generate ticket");const n=Un(this._reports,"audio","total_packets_lost_in"),r=Un(this._reports,"audio","total_packets_in"),a=Un(this._reports,"video","total_packets_lost_in"),c=Un(this._reports,"video","total_packets_in"),e={},_=_1(this._reports);return _&&(Object.keys(_[ae.AUDIO]).forEach(v=>{const d=_[ae.AUDIO][v];if(e[d.ssrc]={type:ae.AUDIO,direction:d.direction},d.direction===zt.INBOUND){const C={avg:nn(this._reports,ae.AUDIO,"delta_jitter_ms_in",!1,v),min:en(this._reports,ae.AUDIO,"delta_jitter_ms_in",v),max:tn(this._reports,ae.AUDIO,"delta_jitter_ms_in",v),volatility:Zt(this._reports,ae.AUDIO,"delta_jitter_ms_in",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ae.AUDIO,"delta_kbs_in",!1,v),min:en(this._reports,ae.AUDIO,"delta_kbs_in",v),max:tn(this._reports,ae.AUDIO,"delta_kbs_in",v),volatility:Zt(this._reports,ae.AUDIO,"delta_kbs_in",v),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ae.AUDIO,"delta_KBytes_in",!1,v),min:en(this._reports,ae.AUDIO,"delta_KBytes_in",v),max:tn(this._reports,ae.AUDIO,"delta_KBytes_in",v),volatility:Zt(this._reports,ae.AUDIO,"delta_KBytes_in",v),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D={emodel:{avg:nn(this._reports,ae.AUDIO,"mos_emodel_in",!1,v),min:en(this._reports,ae.AUDIO,"mos_emodel_in",v),max:tn(this._reports,ae.AUDIO,"mos_emodel_in",v),volatility:Zt(this._reports,ae.AUDIO,"mos_emodel_in",v)},effective:{avg:nn(this._reports,ae.AUDIO,"mos_in",!1,v),min:en(this._reports,ae.AUDIO,"mos_in",v),max:tn(this._reports,ae.AUDIO,"mos_in",v),volatility:Zt(this._reports,ae.AUDIO,"mos_in",v)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},H=Un(this._reports,ae.AUDIO,"total_packets_lost_in",v),K=Un(this._reports,ae.AUDIO,"total_packets_in",v),F={lost:H,avg:Math.round((H/(H+K)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[v].jitter=C,e[v].mos=D,e[v].traffic=R,e[v].bitrate=S,e[v].loss=F}else{const C={avg:nn(this._reports,ae.AUDIO,"delta_jitter_ms_out",!1,v),min:en(this._reports,ae.AUDIO,"delta_jitter_ms_out",v),max:tn(this._reports,ae.AUDIO,"delta_jitter_ms_out",v),volatility:Zt(this._reports,ae.AUDIO,"delta_jitter_ms_out",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ae.AUDIO,"delta_kbs_out",!1,v),min:en(this._reports,ae.AUDIO,"delta_kbs_out",v),max:tn(this._reports,ae.AUDIO,"delta_kbs_out",v),volatility:Zt(this._reports,ae.AUDIO,"delta_kbs_out",v),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ae.AUDIO,"delta_KBytes_out",!1,v),min:en(this._reports,ae.AUDIO,"delta_KBytes_out",v),max:tn(this._reports,ae.AUDIO,"delta_KBytes_out",v),volatility:Zt(this._reports,ae.AUDIO,"delta_KBytes_out",v),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},D={avg:$f(this._reports,ae.AUDIO,v),min:en(this._reports,ae.AUDIO,"delta_rtt_ms_out",v),max:tn(this._reports,ae.AUDIO,"delta_rtt_ms_out",v),volatility:Zt(this._reports,ae.AUDIO,"delta_rtt_ms_out",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ae.AUDIO,"total_packets_lost_out",v),K=Un(this._reports,ae.AUDIO,"total_packets_out",v),F={lost:H,avg:Math.round((H/(H+K)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},W={emodel:{avg:nn(this._reports,ae.AUDIO,"mos_emodel_out",!1,v),min:en(this._reports,ae.AUDIO,"mos_emodel_out",v),max:tn(this._reports,ae.AUDIO,"mos_emodel_out",v),volatility:Zt(this._reports,ae.AUDIO,"mos_emodel_out",v)},effective:{avg:nn(this._reports,ae.AUDIO,"mos_out",!1,v),min:en(this._reports,ae.AUDIO,"mos_out",v),max:tn(this._reports,ae.AUDIO,"mos_out",v),volatility:Zt(this._reports,ae.AUDIO,"mos_out",v)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};e[v].jitter=C,e[v].rtt=D,e[v].traffic=R,e[v].bitrate=S,e[v].loss=F,e[v].mos=W}}),Object.keys(_[ae.VIDEO]).forEach(v=>{const d=_[ae.VIDEO][v];if(e[v]={type:ae.VIDEO,direction:d.direction},d.direction===zt.INBOUND){const C={avg:nn(this._reports,ae.VIDEO,"delta_jitter_ms_in",!1,v),min:en(this._reports,ae.VIDEO,"delta_jitter_ms_in",v),max:tn(this._reports,ae.VIDEO,"delta_jitter_ms_in",v),volatility:Zt(this._reports,ae.VIDEO,"delta_jitter_ms_in",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ae.VIDEO,"delta_kbs_in",!1,v),min:en(this._reports,ae.VIDEO,"delta_kbs_in",v),max:tn(this._reports,ae.VIDEO,"delta_kbs_in",v),volatility:Zt(this._reports,ae.VIDEO,"delta_kbs_in",v),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ae.VIDEO,"delta_KBytes_in",!1,v),min:en(this._reports,ae.VIDEO,"delta_KBytes_in",v),max:tn(this._reports,ae.VIDEO,"delta_KBytes_in",v),volatility:Zt(this._reports,ae.VIDEO,"delta_KBytes_in",v),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D=Un(this._reports,ae.VIDEO,"total_packets_lost_in",v),H=Un(this._reports,ae.VIDEO,"total_packets_in",v),K={lost:D,avg:Math.round((D/(D+H)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[v].jitter=C,e[v].traffic=R,e[v].bitrate=S,e[v].loss=K}else{const C={avg:nn(this._reports,ae.VIDEO,"delta_jitter_ms_out",!1,v),min:en(this._reports,ae.VIDEO,"delta_jitter_ms_out",v),max:tn(this._reports,ae.VIDEO,"delta_jitter_ms_out",v),volatility:Zt(this._reports,ae.VIDEO,"delta_jitter_ms_out",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ae.VIDEO,"delta_kbs_out",!1,v),min:en(this._reports,ae.VIDEO,"delta_kbs_out",v),max:tn(this._reports,ae.VIDEO,"delta_kbs_out",v),volatility:Zt(this._reports,ae.VIDEO,"delta_kbs_out",v),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ae.VIDEO,"delta_KBytes_out",!1,v),min:en(this._reports,ae.VIDEO,"delta_KBytes_out",v),max:tn(this._reports,ae.VIDEO,"delta_KBytes_out",v),volatility:Zt(this._reports,ae.VIDEO,"delta_KBytes_out",v),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D={avg:$f(this._reports,ae.VIDEO,v),min:en(this._reports,ae.VIDEO,"delta_rtt_ms_out",v),max:tn(this._reports,ae.VIDEO,"delta_rtt_ms_out",v),volatility:Zt(this._reports,ae.VIDEO,"delta_rtt_ms_out",v),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ae.VIDEO,"total_packets_lost_out",v),K=Un(this._reports,ae.VIDEO,"total_packets_out",v),F={lost:H,avg:Math.round((H/(H+K)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[v].jitter=C,e[v].rtt=D,e[v].traffic=R,e[v].bitrate=S,e[v].loss=F}})),{version:f1,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:e,data:{rtt:{avg:m1(this._reports,"data"),min:en(this._reports,"data","delta_rtt_connectivity_ms"),max:tn(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Zt(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((n/(n+r)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+c)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:nn(this._reports,"data","delta_kbs_in"),min:en(this._reports,"data","delta_kbs_in"),max:tn(this._reports,"data","delta_kbs_in"),volatility:Zt(this._reports,"data","delta_kbs_in")},out:{avg:nn(this._reports,"data","delta_kbs_out"),min:en(this._reports,"data","delta_kbs_out"),max:tn(this._reports,"data","delta_kbs_out"),volatility:Zt(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:nn(this._reports,"data","delta_KBytes_in"),min:en(this._reports,"data","delta_KBytes_in"),max:tn(this._reports,"data","delta_KBytes_in"),volatility:Zt(this._reports,"data","delta_KBytes_in")},out:{avg:nn(this._reports,"data","delta_KBytes_out"),min:en(this._reports,"data","delta_KBytes_out"),max:tn(this._reports,"data","delta_KBytes_out"),volatility:Zt(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:g1(this._reports),remoteConnection:v1(this._reports)}}}}updateConfig(n){this._cfg=n}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const n=this._reports.slice();return n.pop(),n.pop()||null}getReportsNumber(){return this._reports.length}}const gi="extractor ",Of=(o,n,r,a)=>{let c=!1;const e=a[n].total_rtt_ms_out,_=a[n].total_rtt_measure_out,v=r?r[n].total_rtt_ms_out:0,d=r?r[n].total_rtt_measure_out:0,C={rtt:null,totalRTT:e,totalRTTMeasurements:_};if(o[ve.TIMESTAMP]===a[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ve.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(o,ve.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(c=!0,Number(o[ve.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(o[ve.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d===_))return C;const S=1e3*Number(o[ve.ROUND_TRIP_TIME]);let R=e+S,D=_+1;return c&&(R=1e3*Number(o[ve.TOTAL_ROUND_TRIP_TIME])-v,D=Number(o[ve.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d),{rtt:S,totalRTT:R,totalRTTMeasurements:D}},T1=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[n].total_rtt_connectivity_ms,totalRTTMeasurements:a[n].total_rtt_connectivity_measure};const c=1e3*Number(o[ve.CURRENT_ROUND_TRIP_TIME]);let e=a[n].total_rtt_connectivity_ms+c,_=a[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(o,ve.TOTAL_ROUND_TRIP_TIME)&&(e=1e3*Number(o[ve.TOTAL_ROUND_TRIP_TIME])-(r?r[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(o,ve.RESPONSES_RECEIVED)&&(_=Number(o[ve.RESPONSES_RECEIVED])-(r?r[n].total_rtt_connectivity_measure:0)),{rtt:c,totalRTT:e,totalRTTMeasurements:_}},Vu=(o,n,r)=>o[ve.TIMESTAMP]===r[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ve.JITTER)?null:1e3*(Number(o[ve.JITTER])||0),b1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(o,ve.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[ae.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[ae.VIDEO].total_frames_decoded_in,total_decode_time:n[ae.VIDEO].total_time_decoded_in};const r=o[ve.FRAMES_DECODED],a=o[ve.TOTAL_DECODE_TIME],c=a-n[ae.VIDEO].total_time_decoded_in,e=r-n[ae.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:e>0?c*1e3/e:0,frames_decoded:r,total_decode_time:a}},w1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(o,ve.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[ae.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[ae.VIDEO].total_frames_encoded_out,total_encode_time:n[ae.VIDEO].total_time_encoded_out};const r=o[ve.FRAMES_ENCODED],a=o[ve.TOTAL_ENCODE_TIME],c=a-n[ae.VIDEO].total_time_encoded_out,e=r-n[ae.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:e>0&&c?c*1e3/e:0,frames_encoded:r,total_encode_time:a}},kf=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(o,ve.BYTES_SENT))return{packetsSent:r[n].total_packets_out,packetsLost:r[n].total_packets_lost_out,bytesSent:r[n].total_KBytes_out};const c=Number(o[ve.PACKETS_SENT])||0-(a?a[n].total_packets_out:0),e=c-r[n].total_packets_out,_=Number(o[ve.BYTES_SENT])/1024-(a?a[n].total_KBytes_out:0),v=_-r[n].total_KBytes_out,d=o[ve.TIMESTAMP]||Date.now(),C=a?a.timestamp:null;let S=r.timestamp;!S&&C&&(S=C);const R=S?d-S:0,D=R>0?v*.008*1024/R*1e3:0;return{packetsSent:c,deltaPacketsSent:e,KBytesSent:_,deltaKBytesSent:v,kbsSent:D}},Df=(o,n,r,a)=>{let c=r[n].total_packets_lost_out,e=0,_=0;return Object.prototype.hasOwnProperty.call(o,ve.PACKETS_LOST)&&(c=Number(o[ve.PACKETS_LOST])||0-(a?a[n].total_packets_lost_out:0),e=c-r[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(o,ve.FRACTION_LOST)&&(_=Number(100*o[ve.FRACTION_LOST])),{packetsLost:c,deltaPacketsLost:e,fractionLost:_}},Nf=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(o,ve.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(o,ve.BYTES_RECEIVED))return{percent_packets_lost:r[n].percent_packets_lost_in,packetsReceived:r[n].total_packets_in,packetsLost:r[n].total_packets_lost_in,bytesReceived:r[n].total_KBytes_in};const c=Number(o[ve.PACKETS_RECEIVED])||0-(a?a[n].total_packets_in:0),e=Number(o[ve.PACKETS_LOST])||0-(a?a[n].total_packets_lost_in:0),_=e-r[n].total_packets_lost_in,v=c-r[n].total_packets_in,d=c!==r[n].total_packets_in?_*100/(_+v):0,C=Number(o[ve.BYTES_RECEIVED])/1024-(a?a[n].total_KBytes_in:0),S=C-r[n].total_KBytes_in,R=o[ve.TIMESTAMP]||Date.now(),D=a?a.timestamp:null;let H=r.timestamp;!H&&D&&(H=D);const K=H?R-H:0,F=K>0?S*.008*1024/K*1e3:0;return{percentPacketsLost:d,packetsReceived:c,deltaPacketsReceived:v,packetsLost:e,deltaPacketsLost:_,KBytesReceived:C,deltaKBytesReceived:S,kbsReceived:F}},S1=o=>o[ve.CANDIDATE_TYPE]!=="relay"?"":o[ve.RELAY_PROTOCOL]||"",E1=o=>{if(!Object.prototype.hasOwnProperty.call(o,ve.NETWORK_TYPE))return gl.WIFI;switch(o[ve.NETWORK_TYPE]){case Ld.ETHERNET:return gl.ETHERNET;case Ld.CELLULAR_4G:return gl.CELLULAR_4G;case Ld.WIFI:return gl.WIFI;default:return gl.CELLULAR}},Mf=o=>!Object.prototype.hasOwnProperty.call(o,ve.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(o,ve.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:o[ve.FRAME_WIDTH]||null,height:o[ve.FRAME_HEIGHT]||null,framerate:o[ve.FRAMES_PER_SECOND]},C1=o=>{const n=Object.prototype.hasOwnProperty.call(o,ve.QUALITY_LIMITATION_REASON)?o[ve.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(o,ve.QUALITY_LIMITATION_RESOLUTION_CHANGES)?o[ve.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(o,ve.QUALITY_LIMITATION_DURATIONS)?o[ve.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(c=>{a[c]>1e3&&(a[c]=Number(a[c]/1e3))}),{reason:n,durations:a,resolutionChanges:r}},A1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.PLI)||!Object.prototype.hasOwnProperty.call(o,ve.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(o[ve.PLI]||0)-(r?r[ae.VIDEO].total_pli_sent_in:0),c=(o[ve.NACK]||0)-(r?r[ae.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ae.VIDEO].total_pli_sent_in,deltaNackCount:c-n[ae.VIDEO].total_nack_sent_in}},I1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ve.PLI)||!Object.prototype.hasOwnProperty.call(o,ve.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(o[ve.PLI]||0)-(r?r[ae.VIDEO].total_pli_received_out:0),c=(o[ve.NACK]||0)-(r?r[ae.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ae.VIDEO].total_pli_received_out,deltaNackCount:c-n[ae.VIDEO].total_nack_received_out}},R1=o=>({channels:o[ve.CHANNELS]||null,clock_rate:o[ve.CLOCK_RATE]||null,mime_type:o[ve.MIME_TYPE]||null,sdp_fmtp_line:o[ve.SDP_FMTP_LINE]||null}),x1=o=>({clock_rate:o[ve.CLOCK_RATE]||null,mime_type:o[ve.MIME_TYPE]||null}),$1=(o,n,r)=>{const a=(o[ve.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),c=(o[ve.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),e=o[ve.TIMESTAMP]||Date.now(),_=a-n.data.total_KBytes_in,v=c-n.data.total_KBytes_out,d=r?r.timestamp:null;let C=n.timestamp;!C&&d&&(C=d);const S=C?e-C:0,R=S>0?_*.008*1024/S*1e3:0,D=S>0?v*.008*1024/S*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:c,delta_KBytes_received:_,delta_KBytes_sent:v,kbs_speed_received:R,kbs_speed_sent:D}},O1=o=>{const n=o[ve.AVAILABLE_INCOMING_BITRATE]/1024||0,r=o[ve.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:r}},k1=(o,n,r,a)=>{if(!o)return[];switch(o[ve.TYPE]){case Vr.CANDIDATE_PAIR:let c=!1;if(o[ve.NOMINATED]&&o[ve.STATE]===ae.SUCCEEDED&&(c=!0,Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o),ve.SELECTED in o&&!o[ve.SELECTED]&&(c=!1)),c){const _=o[ve.LOCAL_CANDIDATE_ID],v=o[ve.REMOTE_CANDIDATE_ID],d=$1(o,n,a),C=O1(o),S=T1(o,"data",a,n);return[{type:Me.NETWORK,value:{local_candidate_id:_}},{type:Me.NETWORK,value:{remote_candidate_id:v}},{type:Me.DATA,value:{total_KBytes_in:d.total_KBytes_received}},{type:Me.DATA,value:{total_KBytes_out:d.total_KBytes_sent}},{type:Me.DATA,value:{delta_KBytes_in:d.delta_KBytes_received}},{type:Me.DATA,value:{delta_KBytes_out:d.delta_KBytes_sent}},{type:Me.DATA,value:{delta_kbs_in:d.kbs_speed_received}},{type:Me.DATA,value:{delta_kbs_out:d.kbs_speed_sent}},{type:Me.DATA,value:{delta_kbs_bandwidth_in:C.kbs_incoming_bandwidth}},{type:Me.DATA,value:{delta_kbs_bandwidth_out:C.kbs_outgoing_bandwidth}},{type:Me.DATA,value:{delta_rtt_connectivity_ms:S.rtt}},{type:Me.DATA,value:{total_rtt_connectivity_ms:S.totalRTT}},{type:Me.DATA,value:{total_rtt_connectivity_measure:S.totalRTTMeasurements}}]}break;case Vr.LOCAL_CANDIDATE:if(o[ve.ID]===n.network.local_candidate_id)return[{type:Me.NETWORK,value:{infrastructure:E1(o)}},{type:Me.NETWORK,value:{local_candidate_type:o[ve.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{local_candidate_protocol:o[ve.PROTOCOL]||""}},{type:Me.NETWORK,value:{local_candidate_relay_protocol:S1(o)}}];break;case Vr.REMOTE_CANDIDATE:if(o[ve.ID]===n.network.remote_candidate_id)return[{type:Me.NETWORK,value:{remote_candidate_type:o[ve.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{remote_candidate_protocol:o[ve.PROTOCOL]||""}}];break;case Vr.INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);const _=o[ve.SSRC],v=wn(_,n,zt.INBOUND);v&&(v.timestamp=n.timestamp);const d=wn(_,a,zt.INBOUND);if(d&&(d.timestamp=a.timestamp),o[ve.MEDIA_TYPE]===ae.AUDIO){const C=Nf(o,ae.AUDIO,v,d),S=Vu(o,ae.AUDIO,v),R=o[ve.CODEC_ID]||"";return[{ssrc:_,type:Me.AUDIO,value:{codec_id_in:R}},{ssrc:_,type:Me.AUDIO,value:{total_packets_in:C.packetsReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_in:C.deltaPacketsReceived}},{ssrc:_,type:Me.AUDIO,value:{total_packets_lost_in:C.packetsLost}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_lost_in:C.deltaPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{percent_packets_lost_in:C.percentPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{total_KBytes_in:C.KBytesReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_KBytes_in:C.deltaKBytesReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_kbs_in:C.kbsReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_jitter_ms_in:S}}]}if(o[ve.MEDIA_TYPE]===ae.VIDEO){const C=b1(o,v),S=Nf(o,ae.VIDEO,v,d),R=Vu(o,ae.VIDEO,v),D=o[ve.DECODER_IMPLEMENTATION]||null,H=o[ve.CODEC_ID]||null,K=Mf(o),F=A1(o,v,d);return[{ssrc:_,type:Me.VIDEO,value:{codec_id_in:H}},{ssrc:_,type:Me.VIDEO,value:{total_packets_in:S.packetsReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_in:S.deltaPacketsReceived}},{ssrc:_,type:Me.VIDEO,value:{total_packets_lost_in:S.packetsLost}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_lost_in:S.deltaPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{percent_packets_lost_in:S.percentPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{total_KBytes_in:S.KBytesReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_KBytes_in:S.deltaKBytesReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_kbs_in:S.kbsReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_jitter_ms_in:R}},{ssrc:_,type:Me.VIDEO,value:{decoder_in:D}},{ssrc:_,type:Me.VIDEO,value:{delta_ms_decode_frame_in:C.delta_ms_decode_frame}},{ssrc:_,type:Me.VIDEO,value:{total_frames_decoded_in:C.frames_decoded}},{ssrc:_,type:Me.VIDEO,value:{total_time_decoded_in:C.total_decode_time}},{ssrc:_,type:Me.VIDEO,value:{total_nack_sent_in:F.nackCount}},{ssrc:_,type:Me.VIDEO,value:{delta_nack_sent_in:F.deltaNackCount}},{ssrc:_,type:Me.VIDEO,value:{total_pli_sent_in:F.pliCount}},{ssrc:_,type:Me.VIDEO,value:{delta_pli_sent_in:F.deltaPliCount}},{ssrc:_,type:Me.VIDEO,value:{size_in:K}}]}break}case Vr.OUTBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);const _=o[ve.SSRC],v=wn(_,n,zt.OUTBOUND);v&&(v.timestamp=n.timestamp);const d=wn(_,a,zt.OUTBOUND);if(d&&(d.timestamp=a.timestamp),o[ve.MEDIA_TYPE]===ae.AUDIO){const C=o[ve.CODEC_ID]||null,S=kf(o,ae.AUDIO,v,d);return[{ssrc:_,type:Me.AUDIO,value:{codec_id_out:C}},{ssrc:_,type:Me.AUDIO,value:{total_packets_out:S.packetsSent}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_out:S.deltaPacketsSent}},{ssrc:_,type:Me.AUDIO,value:{total_KBytes_out:S.KBytesSent}},{ssrc:_,type:Me.AUDIO,value:{delta_KBytes_out:S.deltaKBytesSent}},{ssrc:_,type:Me.AUDIO,value:{delta_kbs_out:S.kbsSent}}]}if(o[ve.MEDIA_TYPE]===ae.VIDEO){const C=o[ve.ENCODER_IMPLEMENTATION]||null,S=o[ve.CODEC_ID]||null,R=w1(o,v),D=Mf(o),H=C1(o),K=I1(o,v,d),F=kf(o,ae.VIDEO,v,d);return[{ssrc:_,type:Me.VIDEO,value:{codec_id_out:S}},{ssrc:_,type:Me.VIDEO,value:{total_packets_out:F.packetsSent}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_out:F.deltaPacketsSent}},{ssrc:_,type:Me.VIDEO,value:{total_KBytes_out:F.KBytesSent}},{ssrc:_,type:Me.VIDEO,value:{delta_KBytes_out:F.deltaKBytesSent}},{ssrc:_,type:Me.VIDEO,value:{delta_kbs_out:F.kbsSent}},{ssrc:_,type:Me.VIDEO,value:{encoder_out:C}},{ssrc:_,type:Me.VIDEO,value:{delta_ms_encode_frame_out:R.delta_ms_encode_frame}},{ssrc:_,type:Me.VIDEO,value:{total_frames_encoded_out:R.frames_encoded}},{ssrc:_,type:Me.VIDEO,value:{total_time_encoded_out:R.total_encode_time}},{ssrc:_,type:Me.VIDEO,value:{total_nack_received_out:K.nackCount}},{ssrc:_,type:Me.VIDEO,value:{delta_nack_received_out:K.deltaNackCount}},{ssrc:_,type:Me.VIDEO,value:{total_pli_received_out:K.pliCount}},{ssrc:_,type:Me.VIDEO,value:{delta_pli_received_out:K.deltaPliCount}},{ssrc:_,type:Me.VIDEO,value:{size_out:D}},{ssrc:_,type:Me.VIDEO,value:{limitation_out:H}}]}break}case Vr.MEDIA_SOURCE:{Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);break}case Vr.TRACK:{Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);break}case Vr.CODEC:const e=[];return Object.keys(n[ae.AUDIO]).forEach(_=>{const v=n[ae.AUDIO][_];if(v.codec_id_in===o[ve.ID]||v.codec_id_out===o[ve.ID]){Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);const d=R1(o);o[ve.ID]===v.codec_id_in?e.push({ssrc:v.ssrc,type:Me.AUDIO,value:{codec_in:d}}):e.push({ssrc:v.ssrc,type:Me.AUDIO,value:{codec_out:d}})}}),Object.keys(n[ae.VIDEO]).forEach(_=>{const v=n[ae.VIDEO][_];if(v.codec_id_in===o[ve.ID]||v.codec_id_out===o[ve.ID]){Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);const d=x1(o);o[ve.ID]===v.codec_id_in?e.push({ssrc:v.ssrc,type:Me.VIDEO,value:{codec_in:d}}):e.push({ssrc:v.ssrc,type:Me.VIDEO,value:{codec_out:d}})}}),e;case Vr.REMOTE_INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ve.TYPE]} for ${r}`,o);const _=o[ve.SSRC],v=wn(_,n,zt.OUTBOUND),d=wn(_,a,zt.OUTBOUND);if(o[ve.KIND]===ae.AUDIO){const C=Of(o,ae.AUDIO,d,v),S=Vu(o,ae.AUDIO,v),R=Df(o,ae.AUDIO,v,d);return[{ssrc:_,type:Me.AUDIO,value:{delta_rtt_ms_out:C.rtt}},{ssrc:_,type:Me.AUDIO,value:{total_rtt_ms_out:C.totalRTT}},{ssrc:_,type:Me.AUDIO,value:{total_rtt_measure_out:C.totalRTTMeasurements}},{ssrc:_,type:Me.AUDIO,value:{delta_jitter_ms_out:S}},{ssrc:_,type:Me.AUDIO,value:{timestamp_out:o[ve.TIMESTAMP]}},{ssrc:_,type:Me.AUDIO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{percent_packets_lost_out:R.fractionLost}}]}if(o[ve.KIND]===ae.VIDEO){const C=Of(o,ae.VIDEO,d,v),S=Vu(o,ae.VIDEO,v),R=Df(o,ae.VIDEO,v,d);return[{ssrc:_,type:Me.VIDEO,value:{delta_rtt_ms_out:C.rtt}},{ssrc:_,type:Me.VIDEO,value:{total_rtt_ms_out:C.totalRTT}},{ssrc:_,type:Me.VIDEO,value:{total_rtt_measure_out:C.totalRTTMeasurements}},{ssrc:_,type:Me.VIDEO,value:{delta_jitter_ms_out:S}},{ssrc:_,type:Me.VIDEO,value:{timestamp_out:o[ve.TIMESTAMP]}},{ssrc:_,type:Me.VIDEO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{percent_packets_lost_out:R.fractionLost}}]}break}}return[]},ju=o=>o<0?1:o>100?4.5:1+.035*o+7/1e6*o*(o-60)*(100-o),D1=(o,n=ae.AUDIO,r,a,c)=>{const e=wn(c,o,zt.INBOUND),_=wn(c,r,zt.INBOUND),v=wn(c,a,zt.INBOUND),d=[],C=[],S=e[n].percent_packets_lost_in,R=e[n].delta_jitter_ms_in,D=_&&_[n].delta_jitter_ms_in||null,H=v&&v[n].delta_jitter_ms_in||null,K=o.data.delta_rtt_connectivity_ms,F=r&&r.data.delta_rtt_connectivity_ms||null,W=a&&a.data.delta_rtt_connectivity_ms||null;K&&d.push(K),F&&d.push(F),W&&d.push(W),R&&C.push(R),r&&D&&C.push(D),a&&H&&C.push(H);const se=d.length>0?mi(d):100,Z=C.length>0?mi(C):10,Re=93.2-S,X=.18*Re*Re-27.9*Re+1126.62,te=(se+Z)/2,ye=te-177.3<0?0:1,Oe=.024*te+.11*(te-177.3)*ye,Q=X-Oe;return ju(Q)},N1=(o,n=ae.AUDIO,r,a,c)=>{const e=wn(c,o,zt.OUTBOUND),_=wn(c,r,zt.OUTBOUND),v=wn(c,a,zt.OUTBOUND),d=[],C=[],S=e[n].percent_packets_lost_out,R=e[n].delta_rtt_ms_out,D=_&&_[n].delta_rtt_ms_out||null,H=v&&v[n].delta_rtt_ms_out||null,K=e[n].delta_jitter_ms_out,F=_&&_[n].delta_jitter_ms_out||null,W=v&&v[n].delta_jitter_ms_out||null,se=o.data.delta_rtt_connectivity_ms,Z=r&&r.data.delta_rtt_connectivity_ms||null,Re=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):se&&d.push(se),D?d.push(D):Z&&d.push(Z),H?d.push(H):Re&&d.push(Re),K&&C.push(K),r&&F&&C.push(F),a&&W&&C.push(W);const X=d.length>0?mi(d):100,te=C.length>0?mi(C):10,ye=93.2-S,Oe=.18*ye*ye-27.9*ye+1126.62,Q=(X+te)/2,oe=Q-177.3<0?0:1,me=.024*Q+.11*(Q-177.3)*oe,_e=Oe-me;return ju(_e)},M1=(o,n=ae.AUDIO,r,a,c)=>{const e=wn(c,o,zt.INBOUND),_=wn(c,r,zt.INBOUND),v=wn(c,a,zt.INBOUND),d=[],C=[],S=e[n].percent_packets_lost_in/100,R=e[n].delta_jitter_ms_in,D=_&&_[n].delta_jitter_ms_in||null,H=v&&v[n].delta_jitter_ms_in||null,K=o.data.delta_rtt_connectivity_ms,F=r&&r.data.delta_rtt_connectivity_ms||null,W=a&&a.data.delta_rtt_connectivity_ms||null;K&&d.push(K),F&&d.push(F),W&&d.push(W),R&&C.push(R),_&&D&&C.push(D),v&&H&&C.push(H);const se=d.length>0?mi(d):100,Z=C.length>0?mi(C):10,Re=0,X=19.8,te=29.7,ye=30,Oe=(se+Z)/2+ye,Q=Oe-177.3<0?0:1,oe=.024*Oe+.11*(Oe-177.3)*Q,me=93.2-(Re+X*Math.log(1+te*S)+oe);return ju(me)},U1=(o,n=ae.AUDIO,r,a,c)=>{const e=wn(c,o,zt.OUTBOUND),_=wn(c,r,zt.OUTBOUND),v=wn(c,a,zt.OUTBOUND),d=[],C=[],S=e[n].percent_packets_lost_out/100,R=e[n].delta_rtt_ms_out,D=_&&_[n].delta_rtt_ms_out||null,H=v&&v[n].delta_rtt_ms_out||null,K=e[n].delta_jitter_ms_out,F=_&&_[n].delta_jitter_ms_out||null,W=v&&v[n].delta_jitter_ms_out||null,se=o.data.delta_rtt_connectivity_ms,Z=r&&r.data.delta_rtt_connectivity_ms||null,Re=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):se&&d.push(se),D?d.push(D):Z&&d.push(Z),H?d.push(H):Re&&d.push(Re),K&&C.push(K),_&&F&&C.push(F),v&&W&&C.push(W);const X=d.length>0?mi(d):100,te=C.length>0?mi(C):10,ye=0,Oe=19.8,Q=29.7,oe=30,me=(X+te)/2+oe,_e=me-177.3<0?0:1,le=.024*me+.11*(me-177.3)*_e,de=93.2-(ye+Oe*Math.log(1+Q*S)+le);return ju(de)};class P1{constructor(n,r){this._callbacks={onreport:null,onticket:null},this._id=p1(),this._moduleName=this._id,this._probeId=r,this._config=n,this._exporter=new y1(n),this._state=Fs.IDLE,this.registerToPCEvents(),wa(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,r,a,c){const e=(d,C)=>d===ae.AUDIO?C===Vr.INBOUND_RTP?{...Cf}:{...Af}:C===Vr.INBOUND_RTP?{...If}:{...Rf},_=l1(r);_.pname=this._config.pname,_.call_id=this._config.cid,_.user_id=this._config.uid,_.count=r?r.count+1:1;let v=null;return n.forEach(d=>{!v&&d.timestamp&&(v=d.timestamp),k1(d,_,_.pname,c).forEach(C=>{if(C.value&&C.type)if(C.ssrc){let S=_[C.type][C.ssrc];S||(S=e(C.type,d.type),S.ssrc=C.ssrc,_[C.type][C.ssrc]=S),Object.keys(C.value).forEach(R=>{S[R]=C.value[R]})}else Object.keys(C.value).forEach(S=>{_[C.type][S]=C.value[S]})})}),_.timestamp=v,Object.keys(_[ae.AUDIO]).forEach(d=>{const C=_[ae.AUDIO][d];C.direction===zt.INBOUND?(C.mos_emodel_in=D1(_,ae.AUDIO,r,a,C.ssrc),C.mos_in=M1(_,ae.AUDIO,r,a,C.ssrc)):(C.mos_emodel_out=N1(_,ae.AUDIO,r,a,C.ssrc),C.mos_out=U1(_,ae.AUDIO,r,a,C.ssrc))}),_}async takeReferenceStats(){return new Promise((n,r)=>{const a=Date.now();setTimeout(async()=>{try{const c=Date.now()-a,e=Date.now(),_=await this._config.pc.getStats(),v=this.analyze(_,null,null,null),d=Date.now();v.experimental.time_to_measure_ms=d-e,v.experimental.time_to_wait_ms=c,this._exporter.saveReferenceReport(v),Rt(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(c){r(c)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Fs.RUNNING||!this._config.pc)return Rt(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),r=await this._config.pc.getStats(),a=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),c=Date.now();return a.experimental.time_to_measure_ms=c-n,this._exporter.addReport(a),Rt(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(n){return so(this._moduleName,`got error ${n}`),null}}async start(){Rt(this._moduleName,"starting"),this.state=Fs.RUNNING,this._startedTime=this._exporter.start(),Rt(this._moduleName,"started")}async mute(){this.state=Fs.MUTED,Rt(this._moduleName,"muted")}async unmute(){this.state=Fs.RUNNING,Rt(this._moduleName,"unmuted")}async stop(n){if(Rt(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Fs.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Rt(this._moduleName,"stopped")}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(this._moduleName,`registered callback '${n}'`)):so(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&Hd(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&Hd(this._callbacks.onticket.callback,this._callbacks.onticket.context,n)}updateConfig(n){this._config=n,this._exporter.updateConfig(n)}get state(){return this._state}set state(n){this._state=n,Rt(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,r,a,c){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:r,name:a,description:c})}async registerToPCEvents(){const{pc:n}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const r=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${r.length} devices found`,"Media Devices state")}catch{so(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const a=n.iceConnectionState;a===ml.CONNECTED||a===ml.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.DISCONNECTED||a===ml.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const a=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},n.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},n.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=n.getReceivers();if(r&&r.length>0){const a=r[0],{transport:c}=a;if(c){const{iceTransport:e}=c;e&&(e.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class L1{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||h1(),this._moduleName=this._id,wa(this._moduleName,"probe created"),this._config=n,this._collector=new P1(this._config,this._id)}set onreport(n){n?this._collector.registerCallback("onreport",n):this._collector.unregisterCallback("onreport")}set onticket(n){n?this._collector.registerCallback("onticket",n):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(n){this._collector.state=n}addCustomEvent(n,r,a,c=new Date().toJSON()){this._collector.addCustomEvent(c,r,n,a)}get isRunning(){return this._collector.state===Fs.RUNNING}get isIdle(){return this._collector.state===Fs.IDLE}updateUserId(n){this._config.uid=n,this._collector.updateConfig(this._config)}updateCallId(n){this._config.cid=n,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Bu(this._moduleName,"probe is already running");return}this._collector.start()}stop(n=!1){this.isRunning&&this._collector.stop(n)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const jn="engine ";class q1{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},wa(jn,`configured for probing every ${this._config.refreshEvery}ms`),wa(jn,`configured for starting after ${this._config.startAfter}ms`),wa(jn,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Rt(jn,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(n=>n.isRunning)}get isIdle(){return this._probes.every(n=>n.isIdle)}addNewProbe(n,r){if(!n)throw new Error("undefined peer connection");const a=c1(n,r,this._config),c=new L1(a);return this._probes.push(c),Rt(jn,`${this._probes.length} probes registered`),c}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===Fs.RUNNING&&n.stop(),this._probes=this._probes.filter(r=>n.id!==r.id)}async start(){const n=()=>{this._probes.forEach(e=>e.start())},r=async()=>Promise.all(this._probes.map(e=>e.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,c=async()=>{const e=o1(),_=this._probes.filter(v=>v.isRunning);for(const v of _){const d=await v.collectStats();d&&e.probes.push(d),Rt(jn,`got probe ${v.id}`),await xf(0)}return e.delta_time_to_measure_probes_ms=Sa(e.probes,"experimental","time_to_measure_ms"),e.delta_KBytes_in=Sa(e.probes,"data","delta_KBytes_in"),e.delta_KBytes_out=Sa(e.probes,"data","delta_KBytes_out"),e.delta_kbs_in=Sa(e.probes,"data","delta_kbs_in"),e.delta_kbs_out=Sa(e.probes,"data","delta_kbs_out"),e.total_time_decoded_in=Sa(e.probes,"video","total_time_decoded_in"),e.total_time_encoded_out=Sa(e.probes,"video","total_time_encoded_out"),e};for(Rt(jn,"starting to collect"),n(),Rt(jn,"generating reference reports..."),await r(),Rt(jn,"reference reports generated"),this._startedTime=Date.now();a();)if(Rt(jn,`wait ${this._config.refreshEvery}ms before collecting`),await xf(this._config.refreshEvery),a()){Rt(jn,"collecting...");const e=Date.now(),_=await c(),v=Date.now();_.delta_time_consumed_to_measure_ms=v-e,this.fireOnReports(_),Rt(jn,"collected")}Rt(jn,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const r=a=>{this._probes.forEach(c=>{c.stop(a)})};wa(jn,"stop collecting"),r(n)}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(jn,`registered callback '${n}'`)):so(jn,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&Hd(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const H1="interface ";class z1{constructor(n){this._config=d1(n),wa(H1,`welcome to ${this._config.name} version ${this._config.version}`),ZA(this._config.verbose||!1),this._engine=new q1(this._config)}setupLogLevel(n){e1(n)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(n,r){return this._engine.addNewProbe(n,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(n){this._engine.removeExistingProbe(n)}set onresult(n){n?this._engine.registerCallback("onresult",n):this._engine.unregisterCallback("onresult")}}function F1(o,n){return Object.keys(o).filter(r=>n.includes(r)).reduce((r,a)=>{const c=a;return{...r,[c]:o[c]}},{})}const B1=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],V1={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class j1{constructor(n){this.intervals={},this.analysers={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}async start(n,r,a){r&&r.getTracks().length&&await this.beginCalculation(n,r,a)}stop(n){this.clearVolumeInterval(n),this.analysers[n]&&typeof this.analysers[n].disconnect=="function"&&(this.analysers[n].disconnect(),delete this.analysers[n])}clearVolumeInterval(n){this.intervals[n]&&(clearInterval(this.intervals[n]),delete this.intervals[n])}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{this.stop(n)}),this.intervals={},this.analysers={}}async beginCalculation(n,r,a){this.clearVolumeInterval(a);const c=n.createAnalyser(),e=n.createMediaStreamSource(r);c.smoothingTimeConstant=.8,c.fftSize=1024,e.connect(c),this.analysers[a]=c,this.intervals[a]=setInterval(()=>{const _=new Uint8Array(c.frequencyBinCount);c.getByteFrequencyData(_);let v=0;const d=_.length;for(let S=0;S<d;S++)v+=_[S];const C=v/d;this.onChangeFunction(a,C)},this.emitInterval)}}class G1{constructor(){this.resumePromise=null,this.context=new AudioContext,this.setupErrorHandling()}setupErrorHandling(){this.context.addEventListener("statechange",()=>{(this.context.state==="interrupted"||this.context.state==="closed")&&console.warn(`[ManagedAudioContext] AudioContext state changed to: ${this.context.state}`)})}createNewContext(){return console.log("[ManagedAudioContext] Creating new AudioContext instance"),this.context=new AudioContext,this.setupErrorHandling(),this.context}async getContext(){if(this.context.state==="closed")return console.warn("[ManagedAudioContext] AudioContext is closed, creating new instance"),this.createNewContext();if(this.context.state==="interrupted"){console.warn("[ManagedAudioContext] AudioContext is interrupted, attempting to resume");try{this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(n=>{console.error("[ManagedAudioContext] Failed to resume interrupted context:",n),this.resumePromise=null,this.createNewContext()})),await this.resumePromise}catch(n){return console.error("[ManagedAudioContext] Error resuming context, creating new one:",n),this.createNewContext()}}return this.context.state==="suspended"&&(this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(n=>{throw console.error("[ManagedAudioContext] Failed to resume suspended context:",n),this.resumePromise=null,n})),await this.resumePromise),this.context.state==="closed"?(console.warn("[ManagedAudioContext] Context closed after resume attempt, creating new instance"),this.createNewContext()):this.context}}const Gu={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},W1=0;class K1{constructor(n){var r;this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.isCallWaitingEnabled=!0,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.conferenceNodes={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.vadSessions={},this.vadSessionsState={},this.vadIntervals={},this.vadMrsIntervals={},this.ringbackTimers={},this.ringbackAudioContexts={},this.ringbackSessionProgressReceived={},this.hangupBeepContext=null,this.managedAudioContext=new G1,this.context=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new j1({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices(),this.processVADConfiguration(((r=this.context.options.configuration)==null?void 0:r.noiseReductionOptions)||{}),this.setupVADInstance()}setVADConfiguration(n){if(!this.MicVAD)throw new Error("VAD module is not provided in the initial configuration");const r=Object.keys(n);for(const a of r)this.noiseReduction[a]=n[a];this.hasActiveCalls&&this.roomReconfigure(this.currentActiveRoomId)}setupVADInstance(){var n,r;const a=(r=(n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)==null?void 0:r.vadModule;a&&a.MicVAD?(this.MicVAD=a.MicVAD,console.log("✅ VAD module loaded successfully")):this.noiseReduction.mode!=="disabled"&&(console.warn("⚠️ Noise reduction is enabled but VAD module is not provided. To use VAD features, please install @ricky0123/vad-web and pass it via configuration.noiseReductionOptions.vadModule option."),this.noiseReduction.mode="disabled")}processVADConfiguration(n){this.noiseReduction={mode:n.mode||"disabled",checkEveryMs:n.checkEveryMs||500,noiseCheckInterval:n.noiseCheckInterval||2e3,noiseThreshold:n.noiseThreshold||.004,vadConfig:n.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(n){this.currentActiveRoomIdValue=n,this.context.emit("currentActiveRoomChanged",n)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(n){this.isCallAddingInProgress=n,this.context.emit("callAddingInProgressChanged",n)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get isCallWaiting(){return this.isCallWaitingEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get hasActiveAnsweredCalls(){return Object.values(this.activeRooms).filter(n=>!n.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return bf()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input},echoCancellation:!0,echoCancellationType:"system",noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,latency:.01},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(n){this.availableMediaDevices=n,this.context.emit("changeAvailableDeviceList",n)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n)}async initializeMediaDevices(){const n=localStorage.getItem(Gu.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(Gu.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),c=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(c),await this.setMicrophone(n),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const e=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(e)}),a.getTracks().forEach(e=>e.stop())}catch(a){console.error(a)}}async cleanupConferenceNodes(n){const r=this.conferenceNodes[n];if(!r)return;let a=0;r.sources.forEach((_,v)=>{var d;try{_.disconnect(),a++}catch(C){console.error(`[cleanupConferenceNodes] Error disconnecting source ${v}:`,C),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting source ${v}:`,C)}});let c=0;r.destinations.forEach((_,v)=>{var d;try{_.disconnect(),c++}catch(C){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${v}:`,C),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting destination ${v}:`,C)}});let e=0;r.gains.forEach((_,v)=>{var d;try{_.disconnect(),e++}catch(C){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${v}:`,C),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting gain ${v}:`,C)}}),delete this.conferenceNodes[n]}setCallTime(n){const r={...n};delete r.callId,this.callTime={...this.callTime,[n.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(n){const r={...this.callTime};delete r[n],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(n,r){this.timeIntervals={...this.timeIntervals,[n]:r}}removeTimeInterval(n){const r={...this.timeIntervals};r[n]&&(clearInterval(r[n]),delete r[n],this.timeIntervals={...r})}stopCallTimer(n){this.removeTimeInterval(n),this.removeCallTime(n)}emitVolumeChange(n,r){this.context.emit("changeCallVolume",{callId:n,volume:r})}getNoiseReductionMode(){return this.noiseReduction.mode}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,r){if(!/^[A-D0-9*#]+$/g.test(r))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[n].sendDTMF(r)}setIsMuted(n){this.muted=n,this.context.emit("changeIsMuted",n)}processMute(n){const r=this.currentActiveRoomId;this.setIsMuted(n),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!n),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:r,automatic:a}){const c=this.extendedCalls[n];if(!c)return;c._automaticHold=a??!1;const e=new Promise((_,v)=>{const d=setTimeout(()=>{v(new Error("Hold operation timeout"))},5e3),C=()=>{clearTimeout(d),c.putOnHoldTimestamp=r?Date.now():void 0,_()},S=R=>{clearTimeout(d),v(R)};try{r?(this.stopSessionVad(c._id),c.hold({},C)):c.unhold({},C)}catch(R){S(R)}});try{await e,this.updateCall(c);const _=Object.values(this.extendedCalls).filter(v=>v.roomId===c.roomId&&(r?n!==v._id:!0));_.length>1&&await this.doConference(_)}catch(_){throw console.error("Hold operation failed:",_),_}}holdCall(n,r=!1){return this.processHold({callId:n,automatic:r,toHold:!0})}unholdCall(n){return this.processHold({callId:n,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(n=>n.direction==="outgoing"&&n.status===W1).forEach(n=>this.terminateCall(n._id))}answerCall(n){const r=this.extendedCalls[n];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",a=>{this.triggerAddStream(a,r)})}async moveCall(n,r){this.updateCallStatus({callId:n,isMoving:!0}),await this.processRoomChange({callId:n,roomId:r}),this.updateCallStatus({callId:n,isMoving:!1})}updateCall(n){this.activeCalls[n._id]=yf(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const r={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...r}},this.context.emit("updateRoom",{room:r,roomList:this.activeRooms})}hasAutoAnswerHeaders(n){const r=/answer-after=0/,a=n.request.getHeader("Call-Info");return a&&r.test(a)}addCall(n,r=!0){this.activeCalls={...this.activeCalls,[n._id]:yf(n)},this.extendedCalls[n._id]=n,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(n){this.callStatus={...this.callStatus,[n]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const r={...this.callStatus[n.callId]};n.isMoving!==void 0&&(r.isMoving=n.isMoving),n.isTransferring!==void 0&&(r.isTransferring=n.isTransferring),n.isMerging!==void 0&&(r.isMerging=n.isMerging),n.isTransferred!==void 0&&(r.isTransferred=n.isTransferred),this.callStatus={...this.callStatus,[n.callId]:{...r}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(n){const r={...this.callStatus};delete r[n],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(n){this.activeRooms={...this.activeRooms,[n.roomId]:n},this.context.emit("addRoom",{room:n,roomList:this.activeRooms})}async setupActiveStream(){const n=await Nd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n)}async getActiveStream(){const n=await Nd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:a})=>a===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async a=>{await this.setupActiveStream();const c=this.activeStream;a.connection.getSenders()[0].replaceTrack(c.getTracks()[0]),this.updateCall(a)}):await this.doConference(r)}async setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:c})=>c===n))return;this.setSelectedOutputDevice(n);const r=Object.values(this.extendedCalls);if(r.length===0)return;const a=r.filter(c=>c.roomId===this.currentActiveRoomId);a.length===1?r.forEach(c=>{var e;(e=c.audioTag)==null||e.setSinkId(n),this.updateCall(c)}):await this.doConference(a)}removeRoom(n){const r={...this.activeRooms},a={...r[n]};delete r[n],this.activeRooms={...r},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(n){n!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===n).length===0&&(this.removeRoom(n),this.currentActiveRoomId===n&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(n){this.muted?n.mute({audio:!0}):n.unmute({audio:!0})}async startNoiseMonitor({sessionId:n,stream:r,onNoiseDetected:a,onNoiseStop:c}){var e,_,v;let d;try{d=await this.managedAudioContext.getContext()}catch(H){console.error("[startNoiseMonitor] Failed to get AudioContext:",H),(e=this.context.logger)==null||e.error("[startNoiseMonitor] Failed to get AudioContext:",H);return}let C,S;try{C=d.createMediaStreamSource(r.clone()),S=d.createAnalyser()}catch(H){console.error("[startNoiseMonitor] Failed to create audio nodes:",H),console.error("[startNoiseMonitor] AudioContext state:",d.state),(_=this.context.logger)==null||_.error("[startNoiseMonitor] Failed to create audio nodes:",H),(v=this.context.logger)==null||v.error("[startNoiseMonitor] AudioContext state:",d.state);return}S.fftSize=1024;const R=new Float32Array(S.fftSize);C.connect(S);const D=[];this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),this.vadIntervals[n]=null),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),this.vadMrsIntervals[n]=null),this.vadMrsIntervals[n]=setInterval(()=>{S.getFloatTimeDomainData(R);const H=YA(R);D.push(H);const K=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);D.length>K&&D.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[n]=setInterval(()=>{var H;if(D.length===0)return;const K=D.reduce((se,Z)=>se+Z,0)/D.length,F=this.vadSessionsState[n];if(!F){console.warn(`[startNoiseMonitor] State not found for sessionId ${n}, stopping interval`),(H=this.context.logger)==null||H.warn(`[startNoiseMonitor] State not found for sessionId ${n}, stopping interval`),this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),delete this.vadIntervals[n]),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),delete this.vadMrsIntervals[n]);return}const W=K>this.noiseReduction.noiseThreshold;F.isSpeaking||(W&&F.currentMode==="clean"?(F.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!0}),a()):!W&&F.currentMode==="noisy"&&(F.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!1}),c()))},this.noiseReduction.noiseCheckInterval)}async processVAD(n,r){var a;const c=r.clone();this.stopSessionVad(n._id),this.vadSessionsState[n._id]={currentMode:"clean",isSpeaking:!1},console.log("[processVAD] Process for",n._id),(a=this.context.logger)==null||a.log("[processVAD] Process for",n._id);const e=await this.managedAudioContext.getContext(),_=await XA(c,e,150);let v=!1;const d=await this.MicVAD.new({getStream:()=>new Promise(C=>C(c)),...V1,...this.noiseReduction.vadConfig,baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.28/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",onFrameProcessed:()=>{var C;if(!v){if(v=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){n.connection.getSenders()[0]&&n.connection.getSenders()[0].replaceTrack(_.stream.getAudioTracks()[0]);return}if(!this.vadSessionsState[n._id]){console.error(`[processVAD] CRITICAL: State not found for session ${n._id} after being set at line 988! This should not happen.`),(C=this.context.logger)==null||C.error(`[processVAD] CRITICAL: State not found for session ${n._id} after being set at line 988! This should not happen.`);return}this.startNoiseMonitor({sessionId:n._id,stream:c,onNoiseDetected:async()=>{var S,R;console.log("[processVad] - Replace track with Vad Controlled"),(S=this.context.logger)==null||S.log("[processVad] - Replace track with Vad Controlled"),await((R=n.connection.getSenders()[0])==null?void 0:R.replaceTrack(_.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const S=n.connection.getSenders()[0];S&&S.track&&S.transport&&S.transport.state!=="closed"&&S.transport.state!=="failed"&&(console.log("Replace track with Original"),await S.replaceTrack(c.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var C;console.log("🎤 Speech started"),_.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((C=n.connection.getSenders()[0])==null||C.replaceTrack(_.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!0},onSpeechEnd:()=>{var C;console.log("🛑 Speech end"),_.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((C=n.connection.getSenders()[0])==null||C.replaceTrack(_.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!1}});this.vadSessions[n._id]&&(this.vadSessions[n._id].pause(),delete this.vadSessions[n._id]),this.vadSessions[n._id]=d,d.start()}stopSessionVad(n){this.vadSessions[n]&&(this.vadSessions[n].pause(),delete this.vadSessions[n]),this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),delete this.vadIntervals[n]),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),delete this.vadMrsIntervals[n]),this.vadSessionsState[n]&&delete this.vadSessionsState[n]}async roomReconfigure(n){var r,a,c,e;if(n===void 0)return;const _=Object.values(this.extendedCalls).filter(d=>d.roomId===n),v=this.currentActiveRoomId===n;if(console.log("[roomReconfigure] - Calls In Room:",_),(r=this.context.logger)==null||r.log("[roomReconfigure] - Calls In Room:",_),_.forEach((d,C)=>{if(d.audioTag){d.connection.getReceivers().forEach(R=>{R.track.enabled=!d.localMuted}),v&&this.muteReconfigure(d);const S=!v;d.audioTag.muted=S,this.updateCall(d)}}),_.length===0){this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n),console.log("[roomReconfigure] - Delete empty room",n),(a=this.context.logger)==null||a.log("[roomReconfigure] - Delete empty room",n),this.deleteRoomIfEmpty(n);return}if(_.length===1&&!v){const d=_[0];d.isOnHold().local||await this.holdCall(d._id,!0),this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}if(_.length===1&&v){const d=_[0];d.isOnHold().local&&d._automaticHold&&await this.unholdCall(d._id);const C=(((c=d.connection)==null?void 0:c.getSenders())||[])[0];if(d.connection&&C)try{await this.setupActiveStream();const S=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&(console.log("[roomReconfigure] - Call processVAD from roomReconfigure"),(e=this.context.logger)==null||e.log("[roomReconfigure] - Call processVAD from roomReconfigure"),this.processVAD(_[0],S));const R=S.getTracks();await C.replaceTrack(R[0]),this.muteReconfigure(d)}catch(S){console.error(S)}this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}_.length>1&&await this.doConference(_)}async doConference(n){var r,a,c,e,_,v,d;if(console.log("[doConference] - In doConference, sessions:",n),(r=this.context.logger)==null||r.log("[doConference] - In doConference, sessions:",n),n.length===0)return;const C=n[0].roomId,S=this.currentActiveRoomId===C;if(n.find(F=>F.roomId!==C))return;let R;try{R=await this.managedAudioContext.getContext()}catch(F){console.error("[doConference] Failed to get AudioContext:",F),(a=this.context.logger)==null||a.error("[doConference] Failed to get AudioContext:",F);return}const D=R.state;if(D!=="running")if(console.error(`[doConference] ERROR: AudioContext is not running! State: ${D}`),(c=this.context.logger)==null||c.error(`[doConference] ERROR: AudioContext is not running! State: ${D}`),D==="suspended"||D==="interrupted")try{await R.resume();const F=R.state;if(F!=="running"){console.error(`[doConference] Failed to resume AudioContext, state: ${F}`),(e=this.context.logger)==null||e.error(`[doConference] Failed to resume AudioContext, state: ${F}`);return}}catch(F){console.error("[doConference] Error resuming AudioContext:",F),(_=this.context.logger)==null||_.error("[doConference] Error resuming AudioContext:",F);return}else if(D==="closed"){console.error("[doConference] AudioContext is closed, cannot proceed"),(v=this.context.logger)==null||v.error("[doConference] AudioContext is closed, cannot proceed");return}else return;await this.cleanupConferenceNodes(C),this.conferenceNodes[C]={sources:new Map,destinations:new Map,gains:new Map};const H=this.conferenceNodes[C],K=new Map;console.log("[doConference] - Before sessions forEach, sessions:",n),(d=this.context.logger)==null||d.log("[doConference] - Before sessions forEach, sessions:",n),n.forEach((F,W)=>{var se,Z,Re;if(console.log("[doConference] - In sessions forEach, iteration for",F._id),(se=this.context.logger)==null||se.log("[doConference] - In sessions forEach, iteration for",F._id),F&&F.connection){const X=F.connection.getReceivers();console.log("[doConference] - Receivers list length for",F._id,X.length),(Z=this.context.logger)==null||Z.log("[doConference] - Receivers list length for",F._id,X.length),X.forEach((te,ye)=>{var Oe,Q,oe,me,_e,le;te.track.enabled=!F.localMuted;const de=(Oe=te.track)==null?void 0:Oe.id;(Q=te.track)==null||Q.readyState,(oe=te.track)==null||oe.kind;const Se=`${F._id}-${de}`;console.log("[doConference] - Gathering receiver tracks",F._id),console.log("[doConference] - Receiver track readyState",te.track.readyState),(me=this.context.logger)==null||me.log("[doConference] - Gathering receiver tracks",F._id),(_e=this.context.logger)==null||_e.log("[doConference] - Receiver track readyState",te.track.readyState),te.track&&te.track.readyState==="live"&&(console.log("[doConference] - Gathered receiver track",F._id),(le=this.context.logger)==null||le.log("[doConference] - Gathered receiver track",F._id),K.set(Se,te.track))})}else console.log("[doConference] - No session or RTC connection, session:",F),(Re=this.context.logger)==null||Re.log("[doConference] - No session or RTC connection, session:",F)}),await this.setupActiveStream(),await JA.forEach(n,async(F,W)=>{var se,Z,Re,X,te,ye;if(!F||!F.connection){console.log("[doConference] - Return because of no session or connection, session:",F),(se=this.context.logger)==null||se.log("[doConference] - Return because of no session or connection, session:",F);return}const Oe=R.createMediaStreamDestination();H.destinations.set(F._id,Oe);let Q=0;const oe=F.connection.getReceivers(),me=oe.length>0;if(console.log(`[doConference] Session ${F._id} has ${oe.length} receivers`),(Z=this.context.logger)==null||Z.log(`[doConference] Session ${F._id} has ${oe.length} receivers`),me||(console.warn(`[doConference] Session ${F._id} has no receivers yet. Will re-configure when track arrives.`),(Re=this.context.logger)==null||Re.warn(`[doConference] Session ${F._id} has no receivers yet. Will re-configure when track arrives.`)),K.forEach((de,Se)=>{var J,we,xe;if(console.log("[doConference] - In forEach receiverTracks for",F._id),(J=this.context.logger)==null||J.log("[doConference] - In forEach receiverTracks for",F._id),!Se.startsWith(F._id)){if(!de||de.readyState!=="live"){console.warn(`[doConference] Skipping invalid track ${de?.id||"unknown"} for session ${F._id}`),(we=this.context.logger)==null||we.warn(`[doConference] Skipping invalid track ${de?.id||"unknown"} for session ${F._id}`);return}try{const Dt=R.createMediaStreamSource(new MediaStream([de])),Ee=R.createGain(),ge=`${F._id}-${Se}`;Dt.connect(Ee),Ee.connect(Oe),console.log("[doConference] - In forEach connect track for",F._id),(xe=this.context.logger)==null||xe.log("[doConference] - In forEach connect track for",F._id),H.sources.set(ge,Dt),H.gains.set(ge,Ee),Q++}catch(Dt){console.error(Dt)}}}),S&&this.activeStreamValue)try{const de=this.activeStream,Se=R.createMediaStreamSource(de),J=R.createGain(),we=`${F._id}-local`;Se.connect(J),J.connect(Oe),H.sources.set(we,Se),H.gains.set(we,J)}catch(de){console.error(de)}else S&&(console.error(`Host room but no activeStreamValue - skipping host microphone for session ${F._id}`),(X=this.context.logger)==null||X.error(`Host room but no activeStreamValue - skipping host microphone for session ${F._id}`));const _e=F.connection.getSenders()[0],le=Oe.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&(console.log("[doConference] - Call processVAD from doConference"),(te=this.context.logger)==null||te.log("[doConference] - Call processVAD from doConference"),this.processVAD(F,Oe.stream)),_e&&le[0])try{console.log("[doConference] - Final replaceTrack for",F._id),(ye=this.context.logger)==null||ye.log("[doConference] - Final replaceTrack for",F._id),await _e.replaceTrack(le[0]),this.muteReconfigure(F)}catch(de){console.error(de)}})}processCallerMute(n,r){const a=this.extendedCalls[n];a&&a.connection.getReceivers().length&&(a.localMuted=r,a.connection.getReceivers().forEach(c=>{c.track.enabled=!r}),this.updateCall(a))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const r=this.extendedCalls[n];r._status===4?r.terminate({status_code:603,reason_phrase:"Decline"}):r._status!==8&&r.terminate()}handleSipResponseForRingback(n,r){var a,c,e,_,v;let d=null;if(this.extendedCalls[n])d=n;else{const S=Object.values(this.extendedCalls).find(R=>R.id===n||R._id===n||R.id&&R.id.includes(n)||R._id&&R._id.includes(n));S&&(d=S.id)}if(!d){(a=this.context.logger)==null||a.warn(`[handleSipResponseForRingback] Could not find session for identifier ${n}, status ${r}`);return}const C=this.extendedCalls[d];if(!C){(c=this.context.logger)==null||c.warn(`[handleSipResponseForRingback] Call not found in extendedCalls for ${d}`);return}if(C.direction==="outgoing"){if(r===Fu.TRYING||r===Fu.RINGING){if(this.ringbackTimers[d])return;this.ringbackSessionProgressReceived[d]=!1,this.ringbackTimers[d]=setTimeout(()=>{var S;this.ringbackSessionProgressReceived[d]||(this.startLocalRingbackTone(d),(S=this.context.logger)==null||S.log(`[handleSipResponseForRingback] Started local ringback tone for call ${d} after 2 seconds without 183`)),delete this.ringbackTimers[d]},2e3),(e=this.context.logger)==null||e.log(`[handleSipResponseForRingback] Started 2-second timer for call ${d} after receiving ${r}`)}r===Fu.SESSION_PROGRESS&&(this.ringbackSessionProgressReceived[d]=!0,this.ringbackTimers[d]&&(clearTimeout(this.ringbackTimers[d]),delete this.ringbackTimers[d],(_=this.context.logger)==null||_.log(`[handleSipResponseForRingback] Cancelled ringback timer for call ${d} - 183 received`)),this.stopLocalRingbackTone(d),(v=this.context.logger)==null||v.log(`[handleSipResponseForRingback] Stopped local ringback tone for call ${d} - 183 received with SDP`))}}async startLocalRingbackTone(n){var r,a;if(!this.ringbackAudioContexts[n])try{const c=await this.managedAudioContext.getContext(),e=c.createOscillator(),_=c.createOscillator(),v=c.createGain();e.frequency.value=440,_.frequency.value=480,e.type="sine",_.type="sine",v.gain.value=0,e.connect(v),_.connect(v),v.connect(c.destination),e.start(),_.start();const d={context:c,oscillator1:e,oscillator2:_,gainNode:v,intervalId:null};this.ringbackAudioContexts[n]=d;const C=()=>{if(!this.ringbackAudioContexts[n])return;const R=c.currentTime;v.gain.cancelScheduledValues(R),v.gain.setValueAtTime(0,R),v.gain.linearRampToValueAtTime(.3,R+.05),v.gain.linearRampToValueAtTime(0,R+1)};C();const S=setInterval(()=>{if(!this.ringbackAudioContexts[n]){clearInterval(S);return}C()},4e3);d.intervalId=S,this.ringbackAudioContexts[n]=d,(r=this.context.logger)==null||r.log(`[startLocalRingbackTone] Started ringback tone for session ${n}`)}catch(c){(a=this.context.logger)==null||a.error(`[startLocalRingbackTone] Error starting ringback tone for session ${n}:`,c),console.error(`[startLocalRingbackTone] Error starting ringback tone for session ${n}:`,c)}}stopLocalRingbackTone(n){var r,a;const c=this.ringbackAudioContexts[n];if(c)try{c.intervalId&&clearInterval(c.intervalId),c.oscillator1&&c.oscillator1.stop(),c.oscillator2&&c.oscillator2.stop(),c.gainNode&&c.gainNode.disconnect(),delete this.ringbackAudioContexts[n],(r=this.context.logger)==null||r.log(`[stopLocalRingbackTone] Stopped ringback tone for session ${n}`)}catch(e){(a=this.context.logger)==null||a.error(`[stopLocalRingbackTone] Error stopping ringback tone for session ${n}:`,e),console.error(`[stopLocalRingbackTone] Error stopping ringback tone for session ${n}:`,e),delete this.ringbackAudioContexts[n]}}cleanupRingbackTone(n){this.ringbackTimers[n]&&(clearTimeout(this.ringbackTimers[n]),delete this.ringbackTimers[n]),this.stopLocalRingbackTone(n),delete this.ringbackSessionProgressReceived[n]}async playHangupBeep(){var n,r;if(!this.hangupBeepContext)try{const a=await this.managedAudioContext.getContext(),c=a.createOscillator(),e=a.createGain();c.frequency.value=800,c.type="sine",e.gain.value=0,c.connect(e),e.connect(a.destination),this.hangupBeepContext={context:a,oscillator:c,gainNode:e},c.start();const _=a.currentTime;e.gain.setValueAtTime(0,_),e.gain.linearRampToValueAtTime(.3,_+.01),e.gain.setValueAtTime(.3,_+.15),e.gain.linearRampToValueAtTime(0,_+.2),c.stop(_+.2),setTimeout(()=>{if(this.hangupBeepContext){try{this.hangupBeepContext.oscillator&&this.hangupBeepContext.oscillator.disconnect(),this.hangupBeepContext.gainNode&&this.hangupBeepContext.gainNode.disconnect()}catch(v){console.error("[playHangupBeep] Cleanup playing hangup beep error:",v)}this.hangupBeepContext=null}},250),(n=this.context.logger)==null||n.log("[playHangupBeep] Played hangup beep")}catch(a){(r=this.context.logger)==null||r.error("[playHangupBeep] Error playing hangup beep:",a),console.error("[playHangupBeep] Error playing hangup beep:",a),this.hangupBeepContext=null}}transferCall(n,r){if(r.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[n];if(!a._is_confirmed&&!a._is_canceled){const c=`sip:${r}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${c}`]});return}this.updateCallStatus({callId:n,isTransferring:!0,isTransferred:!1}),a.refer(`sip:${r}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(a)}mergeCall(n){const r=Object.values(this.extendedCalls).filter(e=>e.roomId===n);if(r.length!==2)return;const a=r[0],c=r[1];!a||!c||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:c._id,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a))}mergeCallByIds(n,r){const a=Object.values(this.extendedCalls).find(e=>e._id===n),c=Object.values(this.extendedCalls).find(e=>e._id===r);if(!a||!c)throw new Error("Call ID is not provided");this.updateCallStatus({callId:n,isMerging:!0}),this.updateCallStatus({callId:r,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a)}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}setCallWaiting(n){this.isCallWaitingEnabled=n,this.context.emit("changeIsCallWaiting",n)}startCallTimer(n){this.removeTimeInterval(n);const r={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const a=setInterval(()=>{const c={...this.callTime[n]},e=KA(c);this.setCallTime({callId:n,...e})},1e3);this.setTimeInterval(n,a)}async setActiveRoom(n){const r=this.currentActiveRoomId;n!==r&&(this.currentActiveRoomId=n,await this.roomReconfigure(r),await this.roomReconfigure(n))}getNewRoomId(){const n=Object.keys(this.activeRooms);return n.length===0?1:parseInt(n.sort()[n.length-1])+1}async setupCall(n){var r,a;const c=n.session;if(this.getActiveCalls[c.id]!==void 0)return;const e=this.getNewRoomId(),_={started:new Date,incomingInProgress:!1,roomId:e};if(c.direction==="incoming")this.context.logger.log("New incoming call from",(a=(r=c._remote_identity)==null?void 0:r._uri)==null?void 0:a._user),_.incomingInProgress=!0,this.context.subscribe(Br.CALL_CONFIRMED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.startCallTimer(c.id))}),this.context.subscribe(Br.CALL_FAILED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.deleteRoomIfEmpty(e))});else if(c.direction==="outgoing"){const S=R=>{var D,H,K,F,W,se,Z,Re,X;const te=!!((D=R?.response)!=null&&D.body),ye=(K=(H=R?.response)==null?void 0:H.getHeader)==null?void 0:K.call(H,"Content-Type"),Oe=(W=(F=R?.response)==null?void 0:F.getHeader)==null?void 0:W.call(F,"Content-Length");console.log("PPP SDP Check:",{hasBody:te,contentType:ye,contentLength:Oe,bodyLength:((Z=(se=R?.response)==null?void 0:se.body)==null?void 0:Z.length)||0,bodyPreview:((X=(Re=R?.response)==null?void 0:Re.body)==null?void 0:X.substring(0,100))||"N/A"}),R.response&&R.response.status_code===Fu.SESSION_PROGRESS&&(this.startCallTimer(c.id),c.off("progress",S))};c.on("progress",S),c.once("confirmed",()=>{this.startCallTimer(c.id)})}const v=c,d=this.hasAutoAnswerHeaders(n),C=v.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);v.roomId=e,v.localMuted=!1,v.autoAnswer=C,C?this.addCall(v,!1):this.addCall(v),this.addCallStatus(c.id),this.addRoom(_),C&&this.answerCall(v._id)}removeCall(n){const r={...this.activeCalls};delete r[n],this.activeCalls={...r};const a={...this.extendedCalls};delete a[n],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const r=this.extendedCalls[n._id];if(!r)return;this.stopVUMeter("origin"),this.stopVUMeter(n._id);const a=r.roomId;this.removeCall(n._id),this.roomReconfigure(a).then(()=>{}).catch(c=>{console.error("Error reconfiguring room after call removal:",c)})}shouldTerminateNewSession(n){if(n.session.direction==="outgoing")return!1;const r=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||r}async newRTCSessionCallback(n){const r=n.session;if(this.shouldTerminateNewSession(n)){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}this.context.triggerListener({listenerType:Br.NEW_CALL,session:r,event:n}),r.on("ended",c=>{var e,_,v;if(this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_ENDED,session:r,event:c}),r._is_confirmed&&this.playHangupBeep(),r.connection){const C=r.connection.connectionState;(C==="closed"||C==="disconnected")&&this.context.emit("connectionStateChange",{session:r,connectionState:C})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id),this.cleanupRingbackTone(r.id);const d=this.getActiveCalls[r.id];d&&this.activeCallListRemove(d),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(v=this.initialStreamValue)==null||v.getTracks().forEach(C=>C.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("progress",c=>{var e,_;this.context.logger.log("Session in progress for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_PROGRESS,session:r,event:c})}),r.on("failed",c=>{var e,_,v;if(this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_FAILED,session:r,event:c}),r.connection){const C=r.connection.connectionState;(C==="closed"||C==="disconnected")&&this.context.emit("connectionStateChange",{session:r,connectionState:C})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id),this.cleanupRingbackTone(r.id),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const d=this.getActiveCalls[r.id];d&&this.activeCallListRemove(d),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(v=this.initialStreamValue)==null||v.getTracks().forEach(C=>C.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("confirmed",c=>{var e,_;this.context.logger.log("Session confirmed for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_CONFIRMED,session:r,event:c}),this.updateCall(r),this.cleanupRingbackTone(r.id),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)});const a=c=>{c&&c.addEventListener("connectionstatechange",e=>{this.context.emit("connectionStateChange",{session:r,connectionState:c.connectionState})})};if(r.connection&&a(r.connection),r.on("peerconnection",({peerconnection:c})=>{a(c)}),await this.setupCall(n),r.direction==="outgoing"){const c=this.getActiveCalls[r.id].roomId;await this.setActiveRoom(c)}}setMuteWhenJoin(n){this.muteWhenJoinEnabled=n,this.context.emit("changeMuteWhenJoin",n)}setMicrophoneSensitivity(n){if(n<0||n>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=n,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(n){this.speakerVolumeValue=n,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=n,this.updateCall(r))})}setAutoAnswer(n){this.isAutoAnswer=n}setSelectedInputDevice(n){localStorage.setItem(Gu.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(Gu.SELECTED_OUTPUT_DEVICE,n),this.selectedMediaDevices.output=n,this.context.emit("changeActiveOutputMediaDevice",n)}setCallMetrics(n){const r={...n};delete r.callId,this.callMetrics={...this.callMetrics,[n.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(n){const r={...this.callMetrics};delete r[n],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(n){const r=new z1(this.metricConfig),a=r.createProbe(n.connection,{cid:n._id}),c=[];let e;a.onreport=_=>{Object.entries(_.audio).forEach(([C,S])=>{S.direction==="inbound"&&!c.includes(C)&&(c.push(C),e=C)});const v=_.audio[e];if(!v)return;const d=F1(v,B1);d.callId=n._id,this.setCallMetrics(d)},this.context.subscribe(Br.CALL_ENDED,_=>{_._id===n._id&&r.stopAllProbes()}),r.startAllProbes()}async setupVUMeter(n,r){await this.VUMeter.start(await this.managedAudioContext.getContext(),n,r)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){try{const n=Date.now(),r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((a,c)=>{a.stop()}),this.initialStreamValue=null),this.initialStreamValue=r}catch(n){throw n}}async triggerAddStream(n,r){var a,c;console.log(`[triggerAddStream] - For ${r._id}`),(a=this.context.logger)==null||a.log(`[triggerAddStream] - For ${r._id}`);const e=this.muteWhenJoin||this.isMuted;this.setIsMuted(e),this.initialStreamValue||await this.setupStream();const _=await this.managedAudioContext.getContext(),v=await Nd(_,this.initialStreamValue,this.microphoneInputLevel*2),d=this.isMuted||this.muteWhenJoin;v.getTracks().forEach(R=>{R.enabled=!d}),await this.setActiveStream(v),await r.connection.getSenders()[0].replaceTrack(v.getTracks()[0]);const C=new MediaStream([n.track]);!Object.values(this.extendedCalls).find(R=>R.audioTag&&R.audioTag.id===r._id)&&DA(C,r,this.selectedOutputDevice,this.speakerVolume);const S=r.roomId===this.currentActiveRoomId;r.audioTag&&(r.audioTag.muted=!S),await this.setupVUMeter(C,r._id),this.getCallQuality(r),this.updateCall(r),r.roomId!==void 0&&Object.values(this.extendedCalls).filter(R=>R.roomId===r.roomId).length>1&&(console.log(`[triggerAddStream] Re-configuring conference for room ${r.roomId} - track received for call ${r._id}`),(c=this.context.logger)==null||c.log(`[triggerAddStream] Re-configuring conference for room ${r.roomId} - track received for call ${r._id}`),setTimeout(()=>{this.roomReconfigure(r.roomId)},100)),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(r,v)}initCall(n,r,a=!1){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const c=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=c.id,r&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:c.id,roomId:this.currentActiveRoomId}),a)){const e=Object.values(this.extendedCalls).filter(_=>_.roomId===this.currentActiveRoomId&&_._id!==c.id);for(const _ of e)this.holdCall(_._id,!0)}c.connection.addEventListener("track",e=>{this.triggerAddStream(e,c)})}async processRoomChange({callId:n,roomId:r}){const a=this.extendedCalls[n];if(!a)return;const c=a.roomId;a.roomId=r,this.updateCall(a),await this.roomReconfigure(c),await this.roomReconfigure(r)}}class Y1{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n,r){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${n}@${this.context.sipDomain}`,r,this.sipOptions)}stop(n={}){this.context.terminateJanusSessions(n)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(n){this.context.changeMediaConstraints(n)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class X1{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(n){const r=this.extendedMessages[n];this.updateMSRPSession(r)}updateMSRPSession(n){this.activeMessages[n._id]=Tf(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:Tf(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,r){const a=this.msrpHistory[r.id]||[];a.push(n),this.msrpHistory={...this.msrpHistory,[r.id]:[...a]},this.context.emit("newMSRPMessage",{message:n,session:r})}messageTerminate(n){const r=this.extendedMessages[n];r._status!==8&&r.terminate()}addMessageSession(n){if(!n._id||this.getActiveMessages[n._id]!==void 0)return;const r=n;this.addMMSRPSession(r)}triggerMSRPListener({listenerType:n,session:r,event:a}){const c=this.context.listenersList[n];!c||!c.length||c.forEach(e=>{e(r,a)})}removeMMSRPSession(n){const r={...this.activeMessages};delete r[n],this.activeMessages={...r};const a={...this.extendedMessages};delete a[n],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){n.session._id||(n.session._id=n.request.call_id+n.request.from._parameters.tag);const r=n.session;r.on("ended",a=>{this.triggerMSRPListener({listenerType:Br.CALL_ENDED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("failed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_FAILED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_CONFIRMED,session:r,event:a}),this.updateMSRPSession(r)}),r.on("newMessage",a=>{this.addMSRPMessage(a,r)}),this.addMessageSession(r)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,r,a){if(n.length===0)return console.error("Target must be a valid string");const c=this.context.startMSRP(n,a);c.on("active",()=>{this.addMessageSession(c),c.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,r){const a=this.extendedMessages[n];if(!a)throw new Error(`MSRP session with id ${n} doesn't exist!`);a.sendMSRP(r)}}const Wu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Uf{constructor(n){this.opensips=null,this.session=null,this.name=null,this.name=n}setOpensips(n){this.opensips=n}setSession(n){this.session=n}kill(){this.opensips.kill(this.name)}}class J1 extends Uf{constructor(n,r){super(n),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=r}connect(n={}){this.opaqueId=this.session.generateOpaqueId();const r=kt.cloneArray(n.extraHeaders),a={from_tag:this.session._from_tag};n.fromUserName&&(a.from_uri=new ba("sip",n.fromUserName,this.session._ua.configuration.uri.host),r.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(a.from_display_name=n.fromDisplayName),r.push(`Contact: ${this.session._contact}`),r.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&r.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new On.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,r),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let n;this._connection.onicecandidate=r=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||r.candidate&&(this._candidates.push(r.candidate),clearTimeout(n),n=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(n){n.forEach(r=>{this._connection.addTrack(r)})}async _sendInitialRequest(){const n=new sl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const r={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(r),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},c=JSON.stringify(a);this._request.body=c,n.send()}_receiveInviteResponse(n){if(this._publisherSubscribeSent||!n.body)return;const r=JSON.parse(n.body);this.handleId=r.data.id;const a={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},c=[this.session.getPTypeHeader(ir.PUBLISHER)];this.session.sendRequest(ue.SUBSCRIBE,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{var _,v,d,C;if(e.status_code===200){if(this._subscribeSent=!0,e.body)try{const S=JSON.parse(e.body)||{};((v=(_=S.plugindata)==null?void 0:_.data)==null?void 0:v.videoroom)==="joined"&&this.session.myFeedList.push(S.plugindata.data.id),(C=(d=S.plugindata)==null?void 0:d.data)!=null&&C.publishers&&this.session.receivePublishers(S)}catch(S){console.error(S)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(n){const r=this._candidates.map(e=>({janus:"trickle",candidate:e,handle_id:this.handleId,session_id:this.session.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...n},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...r]},c=["Content-Type: application/json",this.session.getPTypeHeader(ir.ICE)];this.session.sendRequest(ue.INFO,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{this._configureSent=!0;const _=e.data.split(`\r
159
159
  `),v=_[_.length-1],d=JSON.parse(v);await this._connection.setRemoteDescription(d.jsep),this._candidates=[]}}})}_sendDetach(){const n={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},r=[this.session.getPTypeHeader(ir.DETACH)];this.session.sendRequest(ue.INFO,{extraHeaders:r,body:JSON.stringify(n)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const n=this._connection.getSenders();n.forEach(r=>{const a=r.track;a&&a.stop()}),n.forEach(r=>{this._connection.removeTrack(r)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Q1 extends Uf{constructor(n,r,a={}){super(n),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=r}start(n){return n}stop(){throw new Error("stop method is not implemented")}async process(n){if(this.immediate){const r=await this.start(n);return this.running=!0,r}return n}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class Z1 extends AA{constructor(n,r){if(!n.modules.length)throw new Error("options.modules should include at least 1 module");const a={...n.configuration,sockets:n.socketInterfaces.map(c=>new WA.WebSocketInterface(c))};super(a),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.waitingForSessionHangup=!1,this.waitingForSessionTimeout=null,this.reconnectionAttemptsLimit=1/0,this.reconnectionAttemptsCounter=0,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],n.pnExtraHeaders&&Object.keys(n.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(n.pnExtraHeaders),this.options=n,this.modules=n.modules,n.configuration.reconnectionAttemptsLimit&&(this.reconnectionAttemptsLimit=n.configuration.reconnectionAttemptsLimit),r&&NA(r)&&(this.logger=r)}isWaitingForSessionHangup(){return this.waitingForSessionHangup}stopSessionAfterWaiting(){this.setInitialized(!1),this.waitingForSessionHangup=!1,clearTimeout(this.waitingForSessionTimeout),this.waitingForSessionTimeout=null,this.activeConnection&&this.reconnect()}get hasActiveSessions(){return this.modules.includes(Wu.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(n,r){return super.on(n,r)}off(n,r){return super.off(n,r)}emit(n,r){return super.emit(n,r)}get sipDomain(){return this.options.sipDomain}use(n){if(this.newStreamPlugins.find(r=>r.name===n.name)||this.processStreamPlugins.find(r=>r.name===n.name))throw new Error(`Plugin with name ${n.name} already exists`);if(n instanceof J1)n.setOpensips(this),this.newStreamPlugins.push(n);else if(n instanceof Q1)n.setOpensips(this),this.processStreamPlugins.push(n);else throw new Error("Wrong plugin instance")}getPlugin(n){return this.newStreamPlugins.find(r=>r.name===n)||this.processStreamPlugins.find(r=>r.name===n)}reconnect(){if(this.reconnectionAttemptsCounter<this.reconnectionAttemptsLimit){const n=5e3*Math.pow(2,this.reconnectionAttemptsCounter);this.reconnectionAttemptsCounter++,setTimeout(this.start.bind(this),n)}else this.emit("reconnectionAttemptsLimitReached",void 0)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Wu.AUDIO)&&(this.audio=new K1(this)),this.modules.includes(Wu.MSRP)&&(this.msrp=new X1(this)),this.modules.includes(Wu.VIDEO)&&(this.video=new Y1(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.setReconnecting(!1),this.activeConnection=!0,this.waitingForSessionHangup=!1,this.reconnectionAttemptsCounter=0}),this.on(this.disconnectedEventName,()=>{this.setConnected(!1),!this.isReconnecting&&(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.hasActiveSessions?(this.waitingForSessionHangup=!0,this.stop(!1),this.waitingForSessionTimeout=setTimeout(()=>{this.terminateAllSessions(),this.setInitialized(!1),this.waitingForSessionHangup=!1,this.activeConnection&&this.reconnect()},12e5)):(this.stop(),this.setInitialized(!1),this.activeConnection&&this.reconnect()))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(n,r){const a=!this.listenersList[n]||!this.listenersList[n].length?[r]:[...this.listenersList[n],r];this.listenersList={...this.listenersList,[n]:a}}removeIListener(n){const r={...this.listenersList};delete r[n],this.listenersList={...r}}triggerListener({listenerType:n,session:r,event:a}){const c=this.listenersList[n];!c||!c.length||c.forEach(e=>{e(r,a)})}setInitialized(n){this.initialized=n,this.emit("ready",n)}setConnected(n){this.connected=n,this.emit("connection",n)}setReconnecting(n){this.isReconnecting=n,this.emit("reconnecting",n)}}var Gn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function eI(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var zd={},Tl={};Object.defineProperty(Tl,"__esModule",{value:!0}),Tl.baseAssetPath=void 0;const Pf=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let Lf="/";Pf&&(Lf=Pf.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")),Tl.baseAssetPath=Lf;var io={};Object.defineProperty(io,"__esModule",{value:!0}),io.defaultModelFetcher=void 0;const tI=o=>fetch(o).then(n=>n.arrayBuffer());io.defaultModelFetcher=tI;var us={},ao={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.log=o.LOG_PREFIX=void 0,o.LOG_PREFIX="[VAD]";const n=["error","debug","warn"];function r(c){return(...e)=>{console[c](o.LOG_PREFIX,...e)}}const a=n.reduce((c,e)=>(c[e]=r(e),c),{});o.log=a})(ao);var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.Message=void 0;var qf;(function(o){o.AudioFrame="AUDIO_FRAME",o.SpeechStart="SPEECH_START",o.VADMisfire="VAD_MISFIRE",o.SpeechEnd="SPEECH_END",o.SpeechStop="SPEECH_STOP",o.SpeechRealStart="SPEECH_REAL_START",o.FrameProcessed="FRAME_PROCESSED"})(qf||(Ea.Message=qf={})),Object.defineProperty(us,"__esModule",{value:!0}),us.FrameProcessor=us.validateOptions=us.defaultFrameProcessorOptions=void 0;const bl=ao,Ca=Ea;us.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function nI(o){(o.positiveSpeechThreshold<0||o.positiveSpeechThreshold>1)&&bl.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(o.negativeSpeechThreshold<0||o.negativeSpeechThreshold>o.positiveSpeechThreshold)&&bl.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),o.preSpeechPadMs<0&&bl.log.error("preSpeechPadMs should be positive"),o.redemptionMs<0&&bl.log.error("redemptionMs should be positive"),o.minSpeechMs<0&&bl.log.error("minSpeechMs should be positive")}us.validateOptions=nI;const Hf=o=>{const n=o.reduce((a,c)=>(a.push(a.at(-1)+c.length),a),[0]),r=new Float32Array(n.at(-1));return o.forEach((a,c)=>{const e=n[c];r.set(a,e)}),r};class rI{constructor(n,r,a,c){this.modelProcessFunc=n,this.modelResetFunc=r,this.options=a,this.msPerFrame=c,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=e=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(e):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=e=>{const _=this.audioBuffer;this.audioBuffer=[];const v=this.speaking;if(this.reset(),v)if(_.reduce((C,S)=>S.isSpeech?C+1:C,0)>=this.minSpeechFrames){const C=Hf(_.map(S=>S.frame));e({msg:Ca.Message.SpeechEnd,audio:C})}else e({msg:Ca.Message.VADMisfire});return{}},this.process=async(e,_)=>{if(!this.active)return;const v=await this.modelProcessFunc(e),d=v.isSpeech>=this.options.positiveSpeechThreshold;if(_({probs:v,msg:Ca.Message.FrameProcessed,frame:e}),this.audioBuffer.push({frame:e,isSpeech:d}),d&&(this.speechFrameCount++,this.redemptionCounter=0),d&&!this.speaking&&(this.speaking=!0,_({msg:Ca.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,_({msg:Ca.Message.SpeechRealStart})),v.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const C=this.audioBuffer;if(this.audioBuffer=[],C.reduce((R,D)=>D.isSpeech?R+1:R,0)>=this.minSpeechFrames){const R=Hf(C.map(D=>D.frame));_({msg:Ca.Message.SpeechEnd,audio:R})}else _({msg:Ca.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[],this.redemptionFrames=Math.floor(a.redemptionMs/this.msPerFrame),this.preSpeechPadFrames=Math.floor(a.preSpeechPadMs/this.msPerFrame),this.minSpeechFrames=Math.floor(a.minSpeechMs/this.msPerFrame),this.reset()}}us.FrameProcessor=rI;var zf={};function oo(o){throw new Error('Could not dynamically require "'+o+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ff={exports:{}};/*!
160
160
  * ONNX Runtime Web v1.23.2
161
161
  * Copyright (c) Microsoft Corporation. All rights reserved.