@voicenter-team/opensips-js 1.0.78 → 1.0.79
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +8 -0
- package/dist/index.d.ts +21 -4
- package/dist/opensips-js.cjs.js +1 -1
- package/dist/opensips-js.es.js +1 -1
- package/dist/opensips-js.iife.js +1 -1
- package/dist/opensips-js.umd.js +1 -1
- package/package.json +1 -1
- package/src/types/rtc.d.ts +6 -1
package/dist/opensips-js.iife.js
CHANGED
@@ -152,4 +152,4 @@ t=0 0
|
|
152
152
|
m=message 2856 TCP/TLS/MSRP *
|
153
153
|
a=accept-types:text/plain text/html
|
154
154
|
a=path:${n.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization_user}.${this._ua._configuration.realm}:2856/${this.auth_id};ws
|
155
|
-
`),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,console.log("dialog be",this._dialog),new yf(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:t=>{this.onTransportError(),console.log(t)},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t),console.log("dialog af",this._dialog),t.status_code===200&&(t.parseSDP(!0),this._status=Ce.STATUS_CONFIRMED,this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Ce.STATUS_INVITE_SENT}terminate(n={}){console.log("terminate",this);const r=n.cause||q.causes.BYE,o=Me.cloneArray(n.extraHeaders),a=n.body;let t,s=n.status_code,p=n.reason_phrase;if(this._status===Ce.STATUS_TERMINATED)throw new Ys.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:if(s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||q.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===Ce.STATUS_NULL||this._status===Ce.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===Ce.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=Ce.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,q.causes.CANCELED);break;case Ce.STATUS_WAITING_FOR_ANSWER:case Ce.STATUS_ANSWERED:if(s=s||480,console.log("REPLY 480"),s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._request.reply(s,p,o,a),console.log("failed 2"),this._failed("local",null,q.causes.REJECTED);break;case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:if(p=n.reason_phrase||q.REASON_PHRASE[s]||"",s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);if(s&&o.push(`Reason: SIP ;cause=${s}; text="${p}"`),this._status===Ce.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Lt.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:d})=>{d===q.ACK&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Lt.C.STATUS_TERMINATED&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())}),this._ended("local",null,r),this._dialog=_,this._ua.newDialog(_)}else console.log("here it is"),this.sendRequest(q.BYE,{extraHeaders:o,body:a}),this._ended("local",null,r)}}sendRequest(n,r){return this._dialog.sendRequest(n,r)}authenticate(n){this.status="auth";let r=new Un("");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 o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(r.toString())}onmessage(n){console.log("onmessage",n);const r=new Un(n.data);if(this.status==="auth"&&r.code===401){const o=this.parseAuth(r.getHeader("WWW-Authenticate")),a=new fm(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,Me.createRandomToken(12)),this.authenticate(a)}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),console.log("======================================================================")),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 o=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=r.candidate.candidate.match(o);this.my_ip=a&&a[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(q.ACK);return}else{const r=new Xl(this,n,"UAC");if(r.error!==void 0){console.log(r.error);return}this.sendRequest(q.ACK),this.sendRequest(q.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!==Ce.STATUS_INVITE_SENT&&this._status!==Ce.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(n.status_code):this._status=Ce.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=Ce.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 o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",n)).catch(a=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(console.log("maybe here???"),this._status=Ce.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,q.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",n,q.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(o=>this._connection.setLocalDescription(o)).catch(o=>{this._acceptAndTerminate(n,500,o.toString()),console.log("failed 4"),this._failed("local",n,q.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(n),this._accepted("remote",n),this.sendRequest(q.ACK),this._confirmed("local",null)});break}default:{const r=Me.sipErrorCause(n.status_code);console.log("failed 5"),this._failed("remote",n,r)}}}sendMSRP(n){const r=new Un("");r.method="SEND",r.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),r.addHeader("From-Path",`${this.my_addr[0]}`),r.addHeader("Message-ID",Me.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 o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),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,o=n.getHeader("Message-ID"),a=new Un("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.ident=r;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}_sendReport(n){let r=n.ident,o=n.getHeader("Message-ID"),a=new Un("");a.method="REPORT",a.addHeader("To-Path",`${n.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=r;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}parseAuth(n){const r={},o=n.replace("Digest","").split(",");for(const a of o){const t=a.trim().split("=");r[t[0]]=t[1].match('^"(.+)"$')[1]}return r}init_incoming(n,r){let o;const a=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&a!=="application/sdp"){n.reply(415);return}if(this._status=Ce.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")&&(o=n.getHeader("expires")*1e3),n.to_tag=Me.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=Ce.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),console.log("failed 6"),this._failed("local",null,q.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),console.log("failed 7"),this._failed("system",null,q.causes.EXPIRES))},o)),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!==Ce.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(n,r,o){this.emit("_failed",{originator:n,message:r||null,cause:o}),this._close(),this.emit("failed",{originator:n,message:r||null,cause:o})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ce.STATUS_TERMINATED){if(this._status=Ce.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,o){const a=r==="UAS"?n.to_tag:n.from_tag,t=r==="UAS"?n.from_tag:n.to_tag,s=n.call_id+a+t;let p=this._earlyDialogs[s];if(o)return p?!0:(p=new Xl(this,n,r,Xl.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[s]=p,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,p)return p.update(n,r),this._dialog=p,delete this._earlyDialogs[s],!0;const _=new Xl(this,n,r);return _.error?(console.log("failed 9"),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(this._dialog=_,!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 Ce.STATUS_CANCELED:case Ce.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,o){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:o})}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=q.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._runSessionTimer()}receiveRequest(n){if(console.log("receiveRequest()"),n.method===q.CANCEL)(this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED)&&(this._status=Ce.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",n,q.causes.CANCELED));else switch(n.method){case q.ACK:if(this._status!==Ce.STATUS_WAITING_FOR_ACK)return;if(this._status=Ce.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:q.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 o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(a=>{this.terminate({cause:q.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",n);break;case q.BYE:this._status===Ce.STATUS_CONFIRMED||this._status===Ce.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,q.causes.BYE)):this._status===Ce.STATUS_INVITE_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,q.causes.BYE)):n.reply(403,"Wrong Status");break;case q.INVITE:this._status===Ce.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case q.INFO:this._status===Ce.STATUS_1XX_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED||this._status===Ce.STATUS_WAITING_FOR_ACK||this._status===Ce.STATUS_CONFIRMED?(n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Va(this).init_incoming(n):n.reply(415):n.reply(403,"Wrong Status");break;case q.UPDATE:this._status===Ce.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case q.REFER:this._status===Ce.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case q.NOTIFY:this._status===Ce.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.CONNECTION_ERROR,cause:q.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:q.causes.REQUEST_TIMEOUT,cause:q.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.DIALOG_ERROR,cause:q.causes.DIALOG_ERROR})}}const Nt=console,Zf={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},zg=Wg;class Jg extends zg{constructor(n){super(n),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[]}call(n,r){return super.call(n,r)}joinVideoCall(n,r){Nt.debug("call()");const o=new oo(this);return o.connect(n,r),o}newMSRPSession(n,r){n.on("msgHistoryUpdate",o=>{console.log(o)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",r)}newJanusSession(n,r){this._janus_sessions[n.id]=n,this.emit("newJanusSession",r)}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}receiveRequest(n){const r=n.method;if(console.log("-----------"),n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){Nt.debug("Request-URI does not point to us"),n.method!==De.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===De.SIPS){n.reply_sl(416);return}if(Lt.checkTransaction(this,n))return;if(r===De.INVITE?new Lt.InviteServerTransaction(this,this._transport,n):r!==De.ACK&&r!==De.CANCEL&&new Lt.NonInviteServerTransaction(this,this._transport,n),r===De.OPTIONS){if(this.listeners("newOptions").length===0){n.reply(200);return}new lf.Options(this).init_incoming(n)}else if(r===De.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new lf.Message(this).init_incoming(n)}else if(r===De.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let o,a;if(n.to_tag)o=this._findDialog(n.call_id,n.from_tag,n.to_tag),o?o.receiveRequest(n):r===De.NOTIFY?(a=this._findSession(n),a?a.receiveRequest(n):(Nt.debug("received NOTIFY request for a non existent subscription"),n.reply(481,"Subscription does not exist"))):r!==De.ACK&&n.reply(481);else switch(r){case De.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const t=n.replaces;o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o?(a=o.owner,a.isEnded()?n.reply(603):a.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(a=new lu(this),a.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(a=new sg(this),a.init_incoming(n));else Nt.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case De.BYE:n.reply(481);break;case De.CANCEL:a=this._findSession(n),a?a.receiveRequest(n):Nt.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,r){Nt.debug("startMSRP()",r);const o=new lu(this);return o.connect(n),o}startJanus(n,r){Nt.debug("startJanus()",r);const o=new lu(this);return o.connect(n),o}terminateMSRPSessions(n){Nt.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(n)}terminateJanusSessions(n){Nt.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(n)}stop(){if(Nt.debug("stop()"),this._dynConfiguration={},this._status===Zf.STATUS_USER_CLOSED){Nt.debug("UA already closed");return}this._registrator.close();const n=Object.keys(this._sessions).length;for(const o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){Nt.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,o)){Nt.debug(`closing session ${o}`);try{this._msrp_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,o)){Nt.debug(`closing session ${o}`);try{this._janus_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch(a){console.error(a)}this._status=Zf.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&n===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}const es=new AudioContext,Xg=["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"],Qg=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function e_(c){const n={};return Xg.forEach(r=>{c[r]!==void 0&&(n[r]=c[r])}),n.localHold=c._localHold,n}function t_(c){const n={};return Qg.forEach(r=>{c[r]!==void 0&&(n[r]=c[r])}),n}function s_(c,n){const r=es.createMediaStreamSource(c),o=es.createMediaStreamDestination(),a=es.createGain();return r.connect(a),a.connect(o),a.gain.value=n,o.stream}function Zg(c,n,r,o){const a=document.createElement("audio");a.id=n._id,a.className="audioTag",a.srcObject=c,a.setSinkId(r),a.volume=o,a.play(),n.audioTag=a}function eT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}const tT=lt,sT=Xt(),It=new tT("WebSocketInterface");var nT=class{constructor(n){It.debug('new() [url:"%s"]',n),this._url=n,this._sip_uri=null,this._via_transport=null,this._ws=null;const r=sT.parse(n,"absoluteURI");if(r===-1)throw It.warn(`invalid WebSocket URI: ${n}`),new TypeError(`Invalid argument: ${n}`);if(r.scheme!=="wss"&&r.scheme!=="ws")throw It.warn(`invalid WebSocket URI scheme: ${r.scheme}`),new TypeError(`Invalid argument: ${n}`);this._sip_uri=`sip:${r.host}${r.port?`:${r.port}`:""};transport=ws`,this._via_transport=r.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(n){this._via_transport=n.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(It.debug("connect()"),this.isConnected()){It.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){It.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),It.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(n){this._onError(n)}}disconnect(){It.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(n){return It.debug("send()"),this.isConnected()?(this._ws.send(n),!0):(It.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(){It.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:n,code:r,reason:o}){It.debug(`WebSocket ${this._url} closed`),n===!1&&It.debug("WebSocket abrupt disconnection"),this.ondisconnect(!n,r,o)}_onMessage({data:n}){It.debug("received WebSocket message"),this.ondata(n)}_onError(n){It.warn(`WebSocket ${this._url} error: `,n)}};const ou=ol,rT=De,iT=hs,lT=pt(),oT=Qf,aT=cs(),uT=ba(),cT=Xt(),fT=nT;An("JsSIP")("version %s",ou.version);var _T={C:rT,Exceptions:iT,Utils:lT,UA:oT,URI:aT,NameAddrHeader:uT,WebSocketInterface:fT,Grammar:cT,debug:An,get name(){return ou.title},get version(){return ou.version}};const hT=it(_T);function au(c){return c<10?`0${c}`:`${c}`}function dT(c){let n=c.hours||0,r=c.minutes||0,o=c.seconds||0;o++,o===60&&(o=0,r++,r===60&&(r=0,n++));const a=`${au(n)}:${au(r)}:${au(o)}`;return{seconds:o,minutes:r,hours:n,formatted:a}}var vt={};vt.forEach=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)if(a in c){const t=Promise.resolve(c[a]).then(s=>n.call(r||globalThis,s,a,c));o.push(t)}await Promise.all(o)},vt.forEachSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)o in c&&await n.call(r||globalThis,await c[o],o,c)},vt.map=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=Promise.resolve(c[a]).then(t=>n.call(r||globalThis,t,a,c)));return Promise.all(o)},vt.mapSeries=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=await n.call(r||globalThis,await c[a],a,c));return o},vt.find=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o();let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(c[s]):t===c.length&&o(),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.findSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(await n.call(r||globalThis,await c[o],o,c))return c[o]},vt.findIndex=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(-1);let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(s):t===c.length&&o(-1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.findIndexSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(await n.call(r||globalThis,await c[o],o,c))return o},vt.some=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(!1);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?o(!0):t===c.length&&o(!1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.someSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(o in c&&await n.call(r||globalThis,await c[o],o,c))return!0;return!1},vt.every=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(!0);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?t===c.length&&o(!0):o(!1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.everySeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(o in c&&!await n.call(r||globalThis,await c[o],o,c))return!1;return!0},vt.filter=(c,n,r)=>new Promise(async(o,a)=>{const t=[];for(let p=0;p<c.length;p++)p in c&&(t[p]=Promise.resolve(c[p]).then(_=>n.call(r||globalThis,_,p,c)).catch(a));const s=[];for(let p=0;p<t.length;p++)await t[p]&&s.push(await c[p]);o(s)}),vt.filterSeries=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&await n.call(r||globalThis,await c[a],a,c)&&o.push(await c[a]);return o},vt.reduce=async(c,n,r)=>{if(c.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let o,a;for(r!==void 0?(a=r,o=0):(a=c[0],o=1),o;o<c.length;o++)o in c&&(a=await n(await a,await c[o],o,c));return a};var n_={};(function(c){const n=vt;Object.keys(n).forEach(r=>{const o=r.charAt(0).toUpperCase()+r.slice(1);c[`async${o}`]=async function(...a){return n[r](this,...a)}})})(n_);var r_=Object.assign(vt,{instanceMethods:n_});const ts={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var pT={exports:{}};(function(c){var n=function(r){var o=Object.prototype,a=o.hasOwnProperty,t=Object.defineProperty||function(ee,Y,G){ee[Y]=G.value},s,p=typeof Symbol=="function"?Symbol:{},_=p.iterator||"@@iterator",d=p.asyncIterator||"@@asyncIterator",g=p.toStringTag||"@@toStringTag";function T(ee,Y,G){return Object.defineProperty(ee,Y,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[Y]}try{T({},"")}catch{T=function(Y,G,re){return Y[G]=re}}function E(ee,Y,G,re){var ge=Y&&Y.prototype instanceof ae?Y:ae,be=Object.create(ge.prototype),xe=new P(re||[]);return t(be,"_invoke",{value:z(ee,G,xe)}),be}r.wrap=E;function y(ee,Y,G){try{return{type:"normal",arg:ee.call(Y,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",R="suspendedYield",I="executing",$="completed",L={};function ae(){}function N(){}function F(){}var Se={};T(Se,_,function(){return this});var ve=Object.getPrototypeOf,M=ve&&ve(ve(se([])));M&&M!==o&&a.call(M,_)&&(Se=M);var D=F.prototype=ae.prototype=Object.create(Se);N.prototype=F,t(D,"constructor",{value:F,configurable:!0}),t(F,"constructor",{value:N,configurable:!0}),N.displayName=T(F,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(Y){T(ee,Y,function(G){return this._invoke(Y,G)})})}r.isGeneratorFunction=function(ee){var Y=typeof ee=="function"&&ee.constructor;return Y?Y===N||(Y.displayName||Y.name)==="GeneratorFunction":!1},r.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,F):(ee.__proto__=F,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},r.awrap=function(ee){return{__await:ee}};function j(ee,Y){function G(be,xe,Re,le){var ye=y(ee[be],ee,xe);if(ye.type==="throw")le(ye.arg);else{var rt=ye.arg,ot=rt.value;return ot&&typeof ot=="object"&&a.call(ot,"__await")?Y.resolve(ot.__await).then(function(Ee){G("next",Ee,Re,le)},function(Ee){G("throw",Ee,Re,le)}):Y.resolve(ot).then(function(Ee){rt.value=Ee,Re(rt)},function(Ee){return G("throw",Ee,Re,le)})}}var re;function ge(be,xe){function Re(){return new Y(function(le,ye){G(be,xe,le,ye)})}return re=re?re.then(Re,Re):Re()}t(this,"_invoke",{value:ge})}B(j.prototype),T(j.prototype,d,function(){return this}),r.AsyncIterator=j,r.async=function(ee,Y,G,re,ge){ge===void 0&&(ge=Promise);var be=new j(E(ee,Y,G,re),ge);return r.isGeneratorFunction(Y)?be:be.next().then(function(xe){return xe.done?xe.value:be.next()})};function z(ee,Y,G){var re=A;return function(be,xe){if(re===I)throw new Error("Generator is already running");if(re===$){if(be==="throw")throw xe;return nt()}for(G.method=be,G.arg=xe;;){var Re=G.delegate;if(Re){var le=H(Re,G);if(le){if(le===L)continue;return le}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=$,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=I;var ye=y(ee,Y,G);if(ye.type==="normal"){if(re=G.done?$:R,ye.arg===L)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=$,G.method="throw",G.arg=ye.arg)}}}function H(ee,Y){var G=Y.method,re=ee.iterator[G];if(re===s)return Y.delegate=null,G==="throw"&&ee.iterator.return&&(Y.method="return",Y.arg=s,H(ee,Y),Y.method==="throw")||G!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+G+"' method")),L;var ge=y(re,ee.iterator,Y.arg);if(ge.type==="throw")return Y.method="throw",Y.arg=ge.arg,Y.delegate=null,L;var be=ge.arg;if(!be)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,L;if(be.done)Y[ee.resultName]=be.value,Y.next=ee.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=s);else return be;return Y.delegate=null,L}B(D),T(D,g,"Generator"),T(D,_,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function Z(ee){var Y={tryLoc:ee[0]};1 in ee&&(Y.catchLoc=ee[1]),2 in ee&&(Y.finallyLoc=ee[2],Y.afterLoc=ee[3]),this.tryEntries.push(Y)}function U(ee){var Y=ee.completion||{};Y.type="normal",delete Y.arg,ee.completion=Y}function P(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(Z,this),this.reset(!0)}r.keys=function(ee){var Y=Object(ee),G=[];for(var re in Y)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in Y)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var Y=ee[_];if(Y)return Y.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(a.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=s,ge.done=!0,ge};return re.next=re}}return{next:nt}}r.values=se;function nt(){return{value:s,done:!0}}return P.prototype={constructor:P,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=s,this.done=!1,this.delegate=null,this.method="next",this.arg=s,this.tryEntries.forEach(U),!ee)for(var Y in this)Y.charAt(0)==="t"&&a.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=s)},stop:function(){this.done=!0;var ee=this.tryEntries[0],Y=ee.completion;if(Y.type==="throw")throw Y.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var Y=this;function G(le,ye){return be.type="throw",be.arg=ee,Y.next=le,ye&&(Y.method="next",Y.arg=s),!!ye}for(var re=this.tryEntries.length-1;re>=0;--re){var ge=this.tryEntries[re],be=ge.completion;if(ge.tryLoc==="root")return G("end");if(ge.tryLoc<=this.prev){var xe=a.call(ge,"catchLoc"),Re=a.call(ge,"finallyLoc");if(xe&&Re){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0);if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else if(xe){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0)}else if(Re){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,Y){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&a.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=Y&&Y<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=Y,ge?(this.method="next",this.next=ge.finallyLoc,L):this.complete(be)},complete:function(ee,Y){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&Y&&(this.next=Y),L},finish:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),L}},catch:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.tryLoc===ee){var re=G.completion;if(re.type==="throw"){var ge=re.arg;U(G)}return ge}}throw new Error("illegal catch attempt")},delegateYield:function(ee,Y,G){return this.delegate={iterator:se(ee),resultName:Y,nextLoc:G},this.method==="next"&&(this.arg=s),L}},r}(c.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})(pT);var i_={exports:{}};(function(c){(function(n,r){c.exports?c.exports=r():n.log=r()})(E_,function(){var n=function(){},r="undefined",o=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function t(R,I){var $=R[I];if(typeof $.bind=="function")return $.bind(R);try{return Function.prototype.bind.call($,R)}catch{return function(){return Function.prototype.apply.apply($,[R,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(R){return R==="debug"&&(R="log"),typeof console===r?!1:R==="trace"&&o?s:console[R]!==void 0?t(console,R):console.log!==void 0?t(console,"log"):n}function _(R,I){for(var $=0;$<a.length;$++){var L=a[$];this[L]=$<R?n:this.methodFactory(L,R,I)}this.log=this.debug}function d(R,I,$){return function(){typeof console!==r&&(_.call(this,I,$),this[R].apply(this,arguments))}}function g(R,I,$){return p(R)||d.apply(this,arguments)}function T(R,I,$){var L=this,ae;I=I??"WARN";var N="loglevel";typeof R=="string"?N+=":"+R:typeof R=="symbol"&&(N=void 0);function F(D){var B=(a[D]||"silent").toUpperCase();if(!(typeof window===r||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Se(){var D;if(!(typeof window===r||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===r)try{var B=window.document.cookie,j=B.indexOf(encodeURIComponent(N)+"=");j!==-1&&(D=/^([^;]+)/.exec(B.slice(j))[1])}catch{}return L.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===r||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}L.name=R,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=$||g,L.getLevel=function(){return ae},L.setLevel=function(D,B){if(typeof D=="string"&&L.levels[D.toUpperCase()]!==void 0&&(D=L.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=L.levels.SILENT){if(ae=D,B!==!1&&F(D),_.call(L,D,R),typeof console===r&&D<L.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},L.setDefaultLevel=function(D){I=D,Se()||L.setLevel(D,!1)},L.resetLevel=function(){L.setLevel(I,!1),ve()},L.enableAll=function(D){L.setLevel(L.levels.TRACE,D)},L.disableAll=function(D){L.setLevel(L.levels.SILENT,D)};var M=Se();M==null&&(M=I),L.setLevel(M,!1)}var E=new T,y={};E.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var $=y[I];return $||($=y[I]=new T(I,E.getLevel(),E.methodFactory)),$};var A=typeof window!==r?window.log:void 0;return E.noConflict=function(){return typeof window!==r&&window.log===E&&(window.log=A),E},E.getLoggers=function(){return y},E.default=E,E})})(i_);var At=i_.exports;const ds=()=>`${new Date().toISOString()} | metrics`,ps=(c,n,r)=>`${c} | ${n} | ${r}`;At.setDefaultLevel(At.levels.TRACE);const mT=c=>{At.info(ps(ds(),"log ",`set log level to ${c?"verbose":"info"}`)),At.setLevel(c?At.levels.TRACE:At.levels.INFO)},gT=c=>{const n=[...Object.keys(At.levels)];n.includes(c)?(At.info(ps(ds(),"log ",`update log level to ${c.toLowerCase()}`)),At.setLevel(c)):At.warn(ps(ds(),"log ","Incorrect log level please choose one of "),n)},Pe=(c,n,r)=>{r?At.debug(ps(ds(),c,n),r):At.debug(ps(ds(),c,n))},uu=(c,n)=>{At.info(ps(ds(),c,n))},Qs=(c,n)=>{At.info(ps(ds(),c,n))},ao=(c,n)=>{At.warn(ps(ds(),c,n))},Pn=(c,n)=>{At.error(ps(ds(),c,n))};function TT(c){return Math.floor(Math.random()*c).toString()}function l_(c,n){let r=n;return c.forEach(o=>{r=r.replace(o,"")}),r}function vT(c,n){let r="";for(let o=0;o<n;o+=1)r+=c[TT(c.length)];return r}function ET({length:c=20,useLetters:n=!0,useNumbers:r=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let t="abcdefghijklmnopqrstuvwxyz",s="0123456789",p=[],_=[],d=[];return n&&(a.length&&(t=l_(a,t)),_=t.split("")),r&&(a.length&&(s=l_(a,s)),d=s.split("")),p=[..._,...d,...o],vT(p,c)}var ST=ET;const Wr=it(ST),yT=()=>"WebRTCMetrics",AT=()=>"5.0.3",Le={INBOUND:"inbound",OUTBOUND:"outbound"},ms={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Kr={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},CT=()=>({...{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:[]}}),o_={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:Le.INBOUND},a_={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:Le.OUTBOUND},u_={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:Le.INBOUND},c_={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:Le.OUTBOUND},RT=c=>{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(c){const r={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(o=>{r.audio[o]={...c.audio[o]}}),Object.keys(c.video).forEach(o=>{r.video[o]={...c.video[o]}}),r}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},IT={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Wr()}`,cid:`c-${Wr()}`,uid:`u-${Wr()}`,record:!1,ticket:!0},Wt={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"},V={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"},x={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Yr={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},cu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},fu="config ",bT=(c,n={},r)=>{const o={...r,...n};return n.pname||ao(fu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),n.cid||ao(fu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),n.uid||ao(fu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),o.pc=c,o},wT=(c={})=>{const n={...IT,...c};return n.name=yT(),n.version=AT(),n},zr=(c,n,r,o=!1,a)=>{let t=c.map(s=>{if(!r)return s[n];if(!a)return s[n][r];const p=s[n][a];return p?p[r]:null});return t=t.filter(s=>o?Number.isFinite(s)&&s>0:Number.isFinite(s)),t.length===0?[]:t},ws=c=>c.reduce((n,r)=>n+r,0)/c.length,OT=()=>`probe-${Wr()}`,DT=()=>`coltr-${Wr()}`,f_=c=>new Promise(n=>setTimeout(n,c)),_u=(c,n,r)=>{n?c.call(n,r):c(r)},Ge=(c,n,r,o)=>{const a=zr(c,n,r,!0,o);if(a.length===0)return null;const t=a.reduce((d,g)=>d+g,0)/a.length;return t===0?null:a.map(d=>Math.abs(t-d)).reduce((d,g)=>d+g,0)/a.length*100/t},Je=(c,n,r,o=!1,a)=>{const t=zr(c,n,r,o,a);return t.length===0?null:t.reduce((s,p)=>s+p,0)/t.length},Zs=(c,n,r)=>zr(c,n,r).reduce((a,t)=>a+t,0),We=(c,n,r,o)=>{const a=zr(c,n,r,!0,o);return a.length===0?null:Math.min(...a)},Ke=(c,n,r,o)=>{const a=zr(c,n,r,!1,o);return a.length===0?null:Math.max(...a)},Et=(c,n,r,o)=>{const a=c.slice().pop();if(!a)return null;if(!r)return a[n];if(!o)return a[n][r];const t=a[n][o];return t?t[r]:null},NT=c=>c.slice().pop(),ft=(c,n,r)=>{if(!n)return null;const o={};let a=n[x.AUDIO][c];a||(a=r===Le.INBOUND?{...o_}:{...a_}),o[x.AUDIO]=a;let t=n[x.VIDEO][c];return t||(t=r===Le.INBOUND?{...u_}:{...c_}),o[x.VIDEO]=t,o},Jr="exporter ",UT="2.0",__=(c,n,r)=>{if(!c||c.length===0)return 0;const o=c[c.length-1];if(!o)return 0;const a=o[n][r];if(a){const t=a.total_rtt_ms_out,s=a.total_rtt_measure_out;return!s||!t?Je(c,n,"delta_rtt_ms_out",!1,r):Number(t/s)}return null},PT=(c,n)=>{if(!c||c.length===0)return 0;const r=c[c.length-1];if(!r)return 0;const o=r[n].total_rtt_connectivity_ms,a=r[n].total_rtt_connectivity_measure;return!a||!o?Je(c,n,"delta_rtt_connectivity_ms"):Number(o/a)},xT=c=>Et(c,"network","local_candidate_type")!=="relay"?`direct/${Et(c,"network","local_candidate_protocol")}`:`turn/${Et(c,"network","local_candidate_relay_protocol")}`,MT=c=>{const n=Et(c,"network","remote_candidate_type"),r=Et(c,"network","remote_candidate_protocol");return n!=="relay"?`direct/${r}`:`turn/${r}`};class kT{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){uu(Jr,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){uu(Jr,"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&&(Pe(Jr,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){uu(Jr,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Pe(Jr,"ticket() - generate ticket");const n=Et(this._reports,"audio","total_packets_lost_in"),r=Et(this._reports,"audio","total_packets_in"),o=Et(this._reports,"video","total_packets_lost_in"),a=Et(this._reports,"video","total_packets_in"),t={},s=NT(this._reports);return s&&(Object.keys(s[x.AUDIO]).forEach(p=>{const _=s[x.AUDIO][p];if(t[_.ssrc]={type:x.AUDIO,direction:_.direction},_.direction===Le.INBOUND){const d={avg:Je(this._reports,x.AUDIO,"delta_jitter_ms_in",!1,p),min:We(this._reports,x.AUDIO,"delta_jitter_ms_in",p),max:Ke(this._reports,x.AUDIO,"delta_jitter_ms_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.AUDIO,"delta_kbs_in",!1,p),min:We(this._reports,x.AUDIO,"delta_kbs_in",p),max:Ke(this._reports,x.AUDIO,"delta_kbs_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.AUDIO,"delta_KBytes_in",!1,p),min:We(this._reports,x.AUDIO,"delta_KBytes_in",p),max:Ke(this._reports,x.AUDIO,"delta_KBytes_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:Je(this._reports,x.AUDIO,"mos_emodel_in",!1,p),min:We(this._reports,x.AUDIO,"mos_emodel_in",p),max:Ke(this._reports,x.AUDIO,"mos_emodel_in",p),volatility:Ge(this._reports,x.AUDIO,"mos_emodel_in",p)},effective:{avg:Je(this._reports,x.AUDIO,"mos_in",!1,p),min:We(this._reports,x.AUDIO,"mos_in",p),max:Ke(this._reports,x.AUDIO,"mos_in",p),volatility:Ge(this._reports,x.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=Et(this._reports,x.AUDIO,"total_packets_lost_in",p),A=Et(this._reports,x.AUDIO,"total_packets_in",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].mos=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R}else{const d={avg:Je(this._reports,x.AUDIO,"delta_jitter_ms_out",!1,p),min:We(this._reports,x.AUDIO,"delta_jitter_ms_out",p),max:Ke(this._reports,x.AUDIO,"delta_jitter_ms_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.AUDIO,"delta_kbs_out",!1,p),min:We(this._reports,x.AUDIO,"delta_kbs_out",p),max:Ke(this._reports,x.AUDIO,"delta_kbs_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.AUDIO,"delta_KBytes_out",!1,p),min:We(this._reports,x.AUDIO,"delta_KBytes_out",p),max:Ke(this._reports,x.AUDIO,"delta_KBytes_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:__(this._reports,x.AUDIO,p),min:We(this._reports,x.AUDIO,"delta_rtt_ms_out",p),max:Ke(this._reports,x.AUDIO,"delta_rtt_ms_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Et(this._reports,x.AUDIO,"total_packets_lost_out",p),A=Et(this._reports,x.AUDIO,"total_packets_out",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:Je(this._reports,x.AUDIO,"mos_emodel_out",!1,p),min:We(this._reports,x.AUDIO,"mos_emodel_out",p),max:Ke(this._reports,x.AUDIO,"mos_emodel_out",p),volatility:Ge(this._reports,x.AUDIO,"mos_emodel_out",p)},effective:{avg:Je(this._reports,x.AUDIO,"mos_out",!1,p),min:We(this._reports,x.AUDIO,"mos_out",p),max:Ke(this._reports,x.AUDIO,"mos_out",p),volatility:Ge(this._reports,x.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R,t[p].mos=I}}),Object.keys(s[x.VIDEO]).forEach(p=>{const _=s[x.VIDEO][p];if(t[p]={type:x.VIDEO,direction:_.direction},_.direction===Le.INBOUND){const d={avg:Je(this._reports,x.VIDEO,"delta_jitter_ms_in",!1,p),min:We(this._reports,x.VIDEO,"delta_jitter_ms_in",p),max:Ke(this._reports,x.VIDEO,"delta_jitter_ms_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.VIDEO,"delta_kbs_in",!1,p),min:We(this._reports,x.VIDEO,"delta_kbs_in",p),max:Ke(this._reports,x.VIDEO,"delta_kbs_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.VIDEO,"delta_KBytes_in",!1,p),min:We(this._reports,x.VIDEO,"delta_KBytes_in",p),max:Ke(this._reports,x.VIDEO,"delta_KBytes_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=Et(this._reports,x.VIDEO,"total_packets_lost_in",p),y=Et(this._reports,x.VIDEO,"total_packets_in",p),A={lost:E,avg:Math.round((E/(E+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].traffic=T,t[p].bitrate=g,t[p].loss=A}else{const d={avg:Je(this._reports,x.VIDEO,"delta_jitter_ms_out",!1,p),min:We(this._reports,x.VIDEO,"delta_jitter_ms_out",p),max:Ke(this._reports,x.VIDEO,"delta_jitter_ms_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.VIDEO,"delta_kbs_out",!1,p),min:We(this._reports,x.VIDEO,"delta_kbs_out",p),max:Ke(this._reports,x.VIDEO,"delta_kbs_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.VIDEO,"delta_KBytes_out",!1,p),min:We(this._reports,x.VIDEO,"delta_KBytes_out",p),max:Ke(this._reports,x.VIDEO,"delta_KBytes_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:__(this._reports,x.VIDEO,p),min:We(this._reports,x.VIDEO,"delta_rtt_ms_out",p),max:Ke(this._reports,x.VIDEO,"delta_rtt_ms_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Et(this._reports,x.VIDEO,"total_packets_lost_out",p),A=Et(this._reports,x.VIDEO,"total_packets_out",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R}})),{version:UT,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:t,data:{rtt:{avg:PT(this._reports,"data"),min:We(this._reports,"data","delta_rtt_connectivity_ms"),max:Ke(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ge(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((o/(o+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Je(this._reports,"data","delta_kbs_in"),min:We(this._reports,"data","delta_kbs_in"),max:Ke(this._reports,"data","delta_kbs_in"),volatility:Ge(this._reports,"data","delta_kbs_in")},out:{avg:Je(this._reports,"data","delta_kbs_out"),min:We(this._reports,"data","delta_kbs_out"),max:Ke(this._reports,"data","delta_kbs_out"),volatility:Ge(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Je(this._reports,"data","delta_KBytes_in"),min:We(this._reports,"data","delta_KBytes_in"),max:Ke(this._reports,"data","delta_KBytes_in"),volatility:Ge(this._reports,"data","delta_KBytes_in")},out:{avg:Je(this._reports,"data","delta_KBytes_out"),min:We(this._reports,"data","delta_KBytes_out"),max:Ke(this._reports,"data","delta_KBytes_out"),volatility:Ge(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:xT(this._reports),remoteConnection:MT(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 Os="extractor ",h_=(c,n,r,o)=>{let a=!1;const t=o[n].total_rtt_ms_out,s=o[n].total_rtt_measure_out,p=r?r[n].total_rtt_ms_out:0,_=r?r[n].total_rtt_measure_out:0,d={rtt:null,totalRTT:t,totalRTTMeasurements:s};if(c[V.TIMESTAMP]===o[n].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_===s))return d;const g=1e3*Number(c[V.ROUND_TRIP_TIME]);let T=t+g,E=s+1;return a&&(T=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-p,E=Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_),{rtt:g,totalRTT:T,totalRTTMeasurements:E}},LT=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:o[n].total_rtt_connectivity_ms,totalRTTMeasurements:o[n].total_rtt_connectivity_measure};const a=1e3*Number(c[V.CURRENT_ROUND_TRIP_TIME]);let t=o[n].total_rtt_connectivity_ms+a,s=o[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME)&&(t=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-(r?r[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,V.RESPONSES_RECEIVED)&&(s=Number(c[V.RESPONSES_RECEIVED])-(r?r[n].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:t,totalRTTMeasurements:s}},uo=(c,n,r)=>c[V.TIMESTAMP]===r[n].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.JITTER)?null:1e3*(Number(c[V.JITTER])||0),$T=(c,n)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[x.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[x.VIDEO].total_frames_decoded_in,total_decode_time:n[x.VIDEO].total_time_decoded_in};const r=c[V.FRAMES_DECODED],o=c[V.TOTAL_DECODE_TIME],a=o-n[x.VIDEO].total_time_decoded_in,t=r-n[x.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:t>0?a*1e3/t:0,frames_decoded:r,total_decode_time:o}},HT=(c,n)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[x.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[x.VIDEO].total_frames_encoded_out,total_encode_time:n[x.VIDEO].total_time_encoded_out};const r=c[V.FRAMES_ENCODED],o=c[V.TOTAL_ENCODE_TIME],a=o-n[x.VIDEO].total_time_encoded_out,t=r-n[x.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:t>0&&a?a*1e3/t:0,frames_encoded:r,total_encode_time:o}},d_=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,V.BYTES_SENT))return{packetsSent:r[n].total_packets_out,packetsLost:r[n].total_packets_lost_out,bytesSent:r[n].total_KBytes_out};const a=Number(c[V.PACKETS_SENT])||0-(o?o[n].total_packets_out:0),t=a-r[n].total_packets_out,s=Number(c[V.BYTES_SENT])/1024-(o?o[n].total_KBytes_out:0),p=s-r[n].total_KBytes_out,_=c[V.TIMESTAMP]||Date.now(),d=o?o.timestamp:null;let g=r.timestamp;!g&&d&&(g=d);const T=g?_-g:0,E=T>0?p*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:t,KBytesSent:s,deltaKBytesSent:p,kbsSent:E}},p_=(c,n,r,o)=>{let a=r[n].total_packets_lost_out,t=0,s=0;return Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)&&(a=Number(c[V.PACKETS_LOST])||0-(o?o[n].total_packets_lost_out:0),t=a-r[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,V.FRACTION_LOST)&&(s=Number(100*c[V.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:t,fractionLost:s}},m_=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,V.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 a=Number(c[V.PACKETS_RECEIVED])||0-(o?o[n].total_packets_in:0),t=Number(c[V.PACKETS_LOST])||0-(o?o[n].total_packets_lost_in:0),s=t-r[n].total_packets_lost_in,p=a-r[n].total_packets_in,_=a!==r[n].total_packets_in?s*100/(s+p):0,d=Number(c[V.BYTES_RECEIVED])/1024-(o?o[n].total_KBytes_in:0),g=d-r[n].total_KBytes_in,T=c[V.TIMESTAMP]||Date.now(),E=o?o.timestamp:null;let y=r.timestamp;!y&&E&&(y=E);const A=y?T-y:0,R=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:_,packetsReceived:a,deltaPacketsReceived:p,packetsLost:t,deltaPacketsLost:s,KBytesReceived:d,deltaKBytesReceived:g,kbsReceived:R}},FT=c=>c[V.CANDIDATE_TYPE]!=="relay"?"":c[V.RELAY_PROTOCOL]||"",VT=c=>{if(!Object.prototype.hasOwnProperty.call(c,V.NETWORK_TYPE))return Yr.WIFI;switch(c[V.NETWORK_TYPE]){case cu.ETHERNET:return Yr.ETHERNET;case cu.CELLULAR_4G:return Yr.CELLULAR_4G;case cu.WIFI:return Yr.WIFI;default:return Yr.CELLULAR}},g_=c=>!Object.prototype.hasOwnProperty.call(c,V.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,V.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[V.FRAME_WIDTH]||null,height:c[V.FRAME_HEIGHT]||null,framerate:c[V.FRAMES_PER_SECOND]},jT=c=>{const n=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_REASON)?c[V.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[V.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,o=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_DURATIONS)?c[V.QUALITY_LIMITATION_DURATIONS]:null;return o&&Object.keys(o).forEach(a=>{o[a]>1e3&&(o[a]=Number(o[a]/1e3))}),{reason:n,durations:o,resolutionChanges:r}},qT=(c,n,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_sent_in:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_sent_in:0);return{pliCount:o,nackCount:a,deltaPliCount:o-n[x.VIDEO].total_pli_sent_in,deltaNackCount:a-n[x.VIDEO].total_nack_sent_in}},BT=(c,n,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_received_out:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_received_out:0);return{pliCount:o,nackCount:a,deltaPliCount:o-n[x.VIDEO].total_pli_received_out,deltaNackCount:a-n[x.VIDEO].total_nack_received_out}},GT=c=>({channels:c[V.CHANNELS]||null,clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null,sdp_fmtp_line:c[V.SDP_FMTP_LINE]||null}),WT=c=>({clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null}),KT=(c,n,r)=>{const o=(c[V.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),a=(c[V.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),t=c[V.TIMESTAMP]||Date.now(),s=o-n.data.total_KBytes_in,p=a-n.data.total_KBytes_out,_=r?r.timestamp:null;let d=n.timestamp;!d&&_&&(d=_);const g=d?t-d:0,T=g>0?s*.008*1024/g*1e3:0,E=g>0?p*.008*1024/g*1e3:0;return{total_KBytes_received:o,total_KBytes_sent:a,delta_KBytes_received:s,delta_KBytes_sent:p,kbs_speed_received:T,kbs_speed_sent:E}},YT=c=>{const n=c[V.AVAILABLE_INCOMING_BITRATE]/1024||0,r=c[V.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:r}},zT=(c,n,r,o)=>{if(!c)return[];switch(c[V.TYPE]){case Wt.CANDIDATE_PAIR:let a=!1;if(c[V.NOMINATED]&&c[V.STATE]===x.SUCCEEDED&&(a=!0,Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c),V.SELECTED in c&&!c[V.SELECTED]&&(a=!1)),a){const s=c[V.LOCAL_CANDIDATE_ID],p=c[V.REMOTE_CANDIDATE_ID],_=KT(c,n,o),d=YT(c),g=LT(c,"data",o,n);return[{type:ne.NETWORK,value:{local_candidate_id:s}},{type:ne.NETWORK,value:{remote_candidate_id:p}},{type:ne.DATA,value:{total_KBytes_in:_.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:_.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:_.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:_.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:_.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:_.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:d.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:d.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case Wt.LOCAL_CANDIDATE:if(c[V.ID]===n.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:VT(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[V.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:FT(c)}}];break;case Wt.REMOTE_CANDIDATE:if(c[V.ID]===n.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[V.PROTOCOL]||""}}];break;case Wt.INBOUND_RTP:{Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.INBOUND);p&&(p.timestamp=n.timestamp);const _=ft(s,o,Le.INBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=m_(c,x.AUDIO,p,_),g=uo(c,x.AUDIO,p),T=c[V.CODEC_ID]||"";return[{ssrc:s,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:s,type:ne.AUDIO,value:{total_packets_in:d.packetsReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:s,type:ne.AUDIO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=$T(c,p),g=m_(c,x.VIDEO,p,_),T=uo(c,x.VIDEO,p),E=c[V.DECODER_IMPLEMENTATION]||null,y=c[V.CODEC_ID]||null,A=g_(c),R=qT(c,p,_);return[{ssrc:s,type:ne.VIDEO,value:{codec_id_in:y}},{ssrc:s,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:s,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:s,type:ne.VIDEO,value:{decoder_in:E}},{ssrc:s,type:ne.VIDEO,value:{delta_ms_decode_frame_in:d.delta_ms_decode_frame}},{ssrc:s,type:ne.VIDEO,value:{total_frames_decoded_in:d.frames_decoded}},{ssrc:s,type:ne.VIDEO,value:{total_time_decoded_in:d.total_decode_time}},{ssrc:s,type:ne.VIDEO,value:{total_nack_sent_in:R.nackCount}},{ssrc:s,type:ne.VIDEO,value:{delta_nack_sent_in:R.deltaNackCount}},{ssrc:s,type:ne.VIDEO,value:{total_pli_sent_in:R.pliCount}},{ssrc:s,type:ne.VIDEO,value:{delta_pli_sent_in:R.deltaPliCount}},{ssrc:s,type:ne.VIDEO,value:{size_in:A}}]}break}case Wt.OUTBOUND_RTP:{Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.OUTBOUND);p&&(p.timestamp=n.timestamp);const _=ft(s,o,Le.OUTBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=c[V.CODEC_ID]||null,g=d_(c,x.AUDIO,p,_);return[{ssrc:s,type:ne.AUDIO,value:{codec_id_out:d}},{ssrc:s,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:s,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:s,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:s,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=c[V.ENCODER_IMPLEMENTATION]||null,g=c[V.CODEC_ID]||null,T=HT(c,p),E=g_(c),y=jT(c),A=BT(c,p,_),R=d_(c,x.VIDEO,p,_);return[{ssrc:s,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:s,type:ne.VIDEO,value:{total_packets_out:R.packetsSent}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_out:R.deltaPacketsSent}},{ssrc:s,type:ne.VIDEO,value:{total_KBytes_out:R.KBytesSent}},{ssrc:s,type:ne.VIDEO,value:{delta_KBytes_out:R.deltaKBytesSent}},{ssrc:s,type:ne.VIDEO,value:{delta_kbs_out:R.kbsSent}},{ssrc:s,type:ne.VIDEO,value:{encoder_out:d}},{ssrc:s,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:s,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:s,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:s,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:s,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:s,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:s,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:s,type:ne.VIDEO,value:{size_out:E}},{ssrc:s,type:ne.VIDEO,value:{limitation_out:y}}]}break}case Wt.MEDIA_SOURCE:{Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case Wt.TRACK:{Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case Wt.CODEC:const t=[];return Object.keys(n[x.AUDIO]).forEach(s=>{const p=n[x.AUDIO][s];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=GT(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_out:_}})}}),Object.keys(n[x.VIDEO]).forEach(s=>{const p=n[x.VIDEO][s];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=WT(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_out:_}})}}),t;case Wt.REMOTE_INBOUND_RTP:{Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.OUTBOUND),_=ft(s,o,Le.OUTBOUND);if(c[V.KIND]===x.AUDIO){const d=h_(c,x.AUDIO,_,p),g=uo(c,x.AUDIO,p),T=p_(c,x.AUDIO,p,_);return[{ssrc:s,type:ne.AUDIO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ne.AUDIO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ne.AUDIO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ne.AUDIO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:s,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[V.KIND]===x.VIDEO){const d=h_(c,x.VIDEO,_,p),g=uo(c,x.VIDEO,p),T=p_(c,x.VIDEO,p,_);return[{ssrc:s,type:ne.VIDEO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ne.VIDEO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ne.VIDEO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ne.VIDEO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:s,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},co=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),JT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.INBOUND),s=ft(a,r,Le.INBOUND),p=ft(a,o,Le.INBOUND),_=[],d=[],g=t[n].percent_packets_lost_in,T=t[n].delta_jitter_ms_in,E=s&&s[n].delta_jitter_ms_in||null,y=p&&p[n].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),R&&_.push(R),I&&_.push(I),T&&d.push(T),r&&E&&d.push(E),o&&y&&d.push(y);const $=_.length>0?ws(_):100,L=d.length>0?ws(d):10,ae=93.2-g,N=.18*ae*ae-27.9*ae+1126.62,F=($+L)/2,Se=F-177.3<0?0:1,ve=.024*F+.11*(F-177.3)*Se,M=N-ve;return co(M)},XT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.OUTBOUND),s=ft(a,r,Le.OUTBOUND),p=ft(a,o,Le.OUTBOUND),_=[],d=[],g=t[n].percent_packets_lost_out,T=t[n].delta_rtt_ms_out,E=s&&s[n].delta_rtt_ms_out||null,y=p&&p[n].delta_rtt_ms_out||null,A=t[n].delta_jitter_ms_out,R=s&&s[n].delta_jitter_ms_out||null,I=p&&p[n].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),r&&R&&d.push(R),o&&I&&d.push(I);const N=_.length>0?ws(_):100,F=d.length>0?ws(d):10,Se=93.2-g,ve=.18*Se*Se-27.9*Se+1126.62,M=(N+F)/2,D=M-177.3<0?0:1,B=.024*M+.11*(M-177.3)*D,j=ve-B;return co(j)},QT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.INBOUND),s=ft(a,r,Le.INBOUND),p=ft(a,o,Le.INBOUND),_=[],d=[],g=t[n].percent_packets_lost_in/100,T=t[n].delta_jitter_ms_in,E=s&&s[n].delta_jitter_ms_in||null,y=p&&p[n].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),R&&_.push(R),I&&_.push(I),T&&d.push(T),s&&E&&d.push(E),p&&y&&d.push(y);const $=_.length>0?ws(_):100,L=d.length>0?ws(d):10,ae=0,N=19.8,F=29.7,Se=30,ve=($+L)/2+Se,M=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*M,j=93.2-(ae+N*Math.log(1+F*g)+D);return co(j)},ZT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.OUTBOUND),s=ft(a,r,Le.OUTBOUND),p=ft(a,o,Le.OUTBOUND),_=[],d=[],g=t[n].percent_packets_lost_out/100,T=t[n].delta_rtt_ms_out,E=s&&s[n].delta_rtt_ms_out||null,y=p&&p[n].delta_rtt_ms_out||null,A=t[n].delta_jitter_ms_out,R=s&&s[n].delta_jitter_ms_out||null,I=p&&p[n].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),s&&R&&d.push(R),p&&I&&d.push(I);const N=_.length>0?ws(_):100,F=d.length>0?ws(d):10,Se=0,ve=19.8,M=29.7,D=30,B=(N+F)/2+D,j=B-177.3<0?0:1,z=.024*B+.11*(B-177.3)*j,Z=93.2-(Se+ve*Math.log(1+M*g)+z);return co(Z)};class ev{constructor(n,r){this._callbacks={onreport:null,onticket:null},this._id=DT(),this._moduleName=this._id,this._probeId=r,this._config=n,this._exporter=new kT(n),this._state=ms.IDLE,this.registerToPCEvents(),Qs(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,r,o,a){const t=(_,d)=>_===x.AUDIO?d===Wt.INBOUND_RTP?{...o_}:{...a_}:d===Wt.INBOUND_RTP?{...u_}:{...c_},s=RT(r);s.pname=this._config.pname,s.call_id=this._config.cid,s.user_id=this._config.uid,s.count=r?r.count+1:1;let p=null;return n.forEach(_=>{!p&&_.timestamp&&(p=_.timestamp),zT(_,s,s.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=s[g.type][g.ssrc];T||(T=t(g.type,_.type),T.ssrc=g.ssrc,s[g.type][g.ssrc]=T),Object.keys(g.value).forEach(E=>{T[E]=g.value[E]})}else Object.keys(g.value).forEach(T=>{s[g.type][T]=g.value[T]})})}),s.timestamp=p,Object.keys(s[x.AUDIO]).forEach(_=>{const d=s[x.AUDIO][_];d.direction===Le.INBOUND?(d.mos_emodel_in=JT(s,x.AUDIO,r,o,d.ssrc),d.mos_in=QT(s,x.AUDIO,r,o,d.ssrc)):(d.mos_emodel_out=XT(s,x.AUDIO,r,o,d.ssrc),d.mos_out=ZT(s,x.AUDIO,r,o,d.ssrc))}),s}async takeReferenceStats(){return new Promise((n,r)=>{const o=Date.now();setTimeout(async()=>{try{const a=Date.now()-o,t=Date.now(),s=await this._config.pc.getStats(),p=this.analyze(s,null,null,null),_=Date.now();p.experimental.time_to_measure_ms=_-t,p.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(p),Pe(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(a){r(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ms.RUNNING||!this._config.pc)return Pe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),r=await this._config.pc.getStats(),o=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return o.experimental.time_to_measure_ms=a-n,this._exporter.addReport(o),Pe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(o),o}catch(n){return Pn(this._moduleName,`got error ${n}`),null}}async start(){Pe(this._moduleName,"starting"),this.state=ms.RUNNING,this._startedTime=this._exporter.start(),Pe(this._moduleName,"started")}async mute(){this.state=ms.MUTED,Pe(this._moduleName,"muted")}async unmute(){this.state=ms.RUNNING,Pe(this._moduleName,"unmuted")}async stop(n){if(Pe(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ms.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Pe(this._moduleName,"stopped")}registerCallback(n,r,o){n in this._callbacks?(this._callbacks[n]={callback:r,context:o},Pe(this._moduleName,`registered callback '${n}'`)):Pn(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Pe(this._moduleName,`unregistered callback '${n}'`)):Pn(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&_u(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&_u(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,Pe(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,r,o,a){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:r,name:o,description:a})}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{Pn(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const o=n.iceConnectionState;o===Kr.CONNECTED||o===Kr.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Kr.DISCONNECTED||o===Kr.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Kr.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const o=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",o,"ICE gathering state")},n.ontrack=o=>{this.addCustomEvent(new Date().toJSON(),"call",`${o.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 o=r[0],{transport:a}=o;if(a){const{iceTransport:t}=a;t&&(t.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class tv{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||OT(),this._moduleName=this._id,Qs(this._moduleName,"probe created"),this._config=n,this._collector=new ev(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,o,a=new Date().toJSON()){this._collector.addCustomEvent(a,r,n,o)}get isRunning(){return this._collector.state===ms.RUNNING}get isIdle(){return this._collector.state===ms.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){ao(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 Ct="engine ";class sv{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Qs(Ct,`configured for probing every ${this._config.refreshEvery}ms`),Qs(Ct,`configured for starting after ${this._config.startAfter}ms`),Qs(Ct,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Pe(Ct,"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 o=bT(n,r,this._config),a=new tv(o);return this._probes.push(a),Pe(Ct,`${this._probes.length} probes registered`),a}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===ms.RUNNING&&n.stop(),this._probes=this._probes.filter(r=>n.id!==r.id)}async start(){const n=()=>{this._probes.forEach(t=>t.start())},r=async()=>Promise.all(this._probes.map(t=>t.takeReferenceStats())),o=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const t=CT(),s=this._probes.filter(p=>p.isRunning);for(const p of s){const _=await p.collectStats();_&&t.probes.push(_),Pe(Ct,`got probe ${p.id}`),await f_(0)}return t.delta_time_to_measure_probes_ms=Zs(t.probes,"experimental","time_to_measure_ms"),t.delta_KBytes_in=Zs(t.probes,"data","delta_KBytes_in"),t.delta_KBytes_out=Zs(t.probes,"data","delta_KBytes_out"),t.delta_kbs_in=Zs(t.probes,"data","delta_kbs_in"),t.delta_kbs_out=Zs(t.probes,"data","delta_kbs_out"),t.total_time_decoded_in=Zs(t.probes,"video","total_time_decoded_in"),t.total_time_encoded_out=Zs(t.probes,"video","total_time_encoded_out"),t};for(Pe(Ct,"starting to collect"),n(),Pe(Ct,"generating reference reports..."),await r(),Pe(Ct,"reference reports generated"),this._startedTime=Date.now();o();)if(Pe(Ct,`wait ${this._config.refreshEvery}ms before collecting`),await f_(this._config.refreshEvery),o()){Pe(Ct,"collecting...");const t=Date.now(),s=await a(),p=Date.now();s.delta_time_consumed_to_measure_ms=p-t,this.fireOnReports(s),Pe(Ct,"collected")}Pe(Ct,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const r=o=>{this._probes.forEach(a=>{a.stop(o)})};Qs(Ct,"stop collecting"),r(n)}registerCallback(n,r,o){n in this._callbacks?(this._callbacks[n]={callback:r,context:o},Pe(Ct,`registered callback '${n}'`)):Pn(Ct,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Pe(this._moduleName,`unregistered callback '${n}'`)):Pn(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&_u(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const nv="interface ";class rv{constructor(n){this._config=wT(n),Qs(nv,`welcome to ${this._config.name} version ${this._config.version}`),mT(this._config.verbose||!1),this._engine=new sv(this._config)}setupLogLevel(n){gT(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 iv(c,n){return Object.keys(c).filter(r=>n.includes(r)).reduce((r,o)=>{const a=o;return{...r,[a]:c[a]}},{})}const lv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class ov{constructor(n){this.intervals={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}start(n,r){n&&n.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(n,r))}stop(n){this.clearVolumeInterval(n)}clearVolumeInterval(n){console.log("clearVolumeInterval",n),clearInterval(this.intervals[n]),delete this.intervals[n]}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{clearInterval(this.intervals[n])}),this.intervals={}}beginCalculation(n,r){this.clearVolumeInterval(r);const o=es.createAnalyser(),a=es.createMediaStreamSource(n),t=es.createScriptProcessor(2048,1,1);o.smoothingTimeConstant=.8,o.fftSize=1024,a.connect(o),o.connect(t),t.connect(es.destination),this.intervals[r]=setInterval(()=>{const s=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(s);let p=0;const _=s.length;for(let g=0;g<_;g++)p+=s[g];const d=p/_;this.onChangeFunction(r,d)},this.emitInterval)}}const fo={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},av=0;class uv{constructor(n){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.context=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new ov({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}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 speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(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(fo.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(fo.SELECTED_OUTPUT_DEVICE)||"default";(await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints)).getTracks().forEach(t=>t.stop());const a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(n),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)})}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})}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,r){if(!/^[A-D0-9]+$/g.test(r))throw new Error("Not allowed character in 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(o=>o.enabled=!n),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:r,automatic:o}){const a=this.extendedCalls[n];a._automaticHold=o??!1,await new Promise(p=>{const _=()=>{p()};r?a.hold({},_):a.unhold({},_)}),this.updateCall(a);const s=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(r?n!==p._id:!0));s.length>1&&await this.doConference(s)}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===av).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",o=>{this.triggerAddStream(o,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]=e_(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const o={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...o}},this.context.emit("updateRoom",{room:o,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]:e_(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}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const o={...{...this.callStatus[n.callId]}};n.isMoving!==void 0&&(o.isMoving=n.isMoving),n.isTransferring!==void 0&&(o.isTransferring=n.isTransferring),n.isMerging!==void 0&&(o.isMerging=n.isMerging),this.callStatus={...this.callStatus,[n.callId]:{...o}},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})}getActiveStream(){const n=s_(this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(r=>r.enabled=!this.isMuted),this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:o})=>o===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async o=>{const a=this.getActiveStream();o.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(o)}):await this.doConference(r)}setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===n))return;this.setSelectedOutputDevice(n);const r=Object.values(this.extendedCalls);if(r.length===0)return;const o=r.filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?r.forEach(a=>{var t;(t=a.audioTag)==null||t.setSinkId(n),this.updateCall(a)}):await this.doConference(o)}removeRoom(n){const r={...this.activeRooms},o={...r[n]};delete r[n],this.activeRooms={...r},this.context.emit("removeRoom",{room:o,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 roomReconfigure(n){if(n===void 0)return;const r=Object.values(this.extendedCalls).filter(o=>o.roomId===n);if(this.currentActiveRoomId===n?r.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):r.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),r.length===0)this.deleteRoomIfEmpty(n);else if(r.length===1&&this.currentActiveRoomId!==n)r[0].isOnHold().local||await this.holdCall(r[0].id,!0);else if(r.length===1&&this.currentActiveRoomId===n){if(r[0].isOnHold().local&&r[0]._automaticHold&&await this.unholdCall(r[0].id),r[0].connection&&r[0].connection.getSenders()[0]){const o=this.getActiveStream();await r[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(r[0])}}else r.length>1&&await this.doConference(r)}async doConference(n){await r_.forEach(n,async o=>{o._localHold&&await this.unholdCall(o._id)});const r=[];n.forEach(o=>{o!=null&&o.connection.getReceivers().forEach(a=>{r.push(a.track)})}),await r_.forEach(n,async o=>{if(o==null)return;const a=new MediaStream,t=es.createMediaStreamDestination();if(o.connection.getReceivers().forEach(s=>{r.forEach(p=>{a.addTrack(s.track),s.track.id!==p.id&&es.createMediaStreamSource(new MediaStream([p])).connect(t)})}),n[0].roomId===this.currentActiveRoomId){const s=this.getActiveStream();es.createMediaStreamSource(s).connect(t)}o.connection.getSenders()[0]&&(await o.connection.getSenders()[0].replaceTrack(t.stream.getTracks()[0]),this.muteReconfigure(o))})}processCallerMute(n,r){const o=this.extendedCalls[n];o&&o.connection.getReceivers().length&&(o.localMuted=r,o.connection.getReceivers().forEach(a=>{a.track.enabled=!r}),this.updateCall(o))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const r=this.extendedCalls[n];r._status!==8&&r.terminate()}transferCall(n,r){if(r.toString().length===0)return new Error("Target must be passed");const o=this.extendedCalls[n];if(!o._is_confirmed&&!o._is_canceled){const a=`sip:${r}@${this.context.sipDomain}`;o.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:n,isTransferring:!0}),o.refer(`sip:${r}@${this.context.sipDomain}`),this.updateCall(o)}mergeCall(n){const r=Object.values(this.extendedCalls).filter(t=>t.roomId===n);if(r.length!==2)return;const o=r[0],a=r[1];!o||!a||(this.updateCallStatus({callId:o._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o))}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}startCallTimer(n){this.removeTimeInterval(n);const r={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const o=setInterval(()=>{const a={...this.callTime[n]},t=dT(a);this.setCallTime({callId:n,...t})},1e3);this.setTimeInterval(n,o)}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 d,g;const r=n.session;if(this.getActiveCalls[r.id]!==void 0)return;const a=this.getNewRoomId(),t={started:new Date,incomingInProgress:!1,roomId:a};r.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(d=r._remote_identity)==null?void 0:d._uri)==null?void 0:g._user),t.incomingInProgress=!0,this.context.subscribe(ts.CALL_CONFIRMED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(r.id))}),this.context.subscribe(ts.CALL_FAILED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):r.direction==="outgoing"&&(r.once("confirmed",()=>{this.startCallTimer(r.id)}),this.startCallTimer(r.id));const s=r,p=this.hasAutoAnswerHeaders(n),_=s.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);s.roomId=a,s.localMuted=!1,s.autoAnswer=_,_?this.addCall(s,!1):this.addCall(s),this.addCallStatus(r.id),this.addRoom(t),_&&this.answerCall(s._id)}removeCall(n){const r={...this.activeCalls};delete r[n],this.activeCalls={...r};const o={...this.extendedCalls};delete o[n],this.extendedCalls={...o},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const r=this.extendedCalls[n._id];this.stopVUMeter("origin"),r.connection.getSenders().forEach(a=>{a.track.stop()});const o=r.roomId;this.removeCall(n._id),this.roomReconfigure(o)}async newRTCSessionCallback(n){const r=n.session;if(this.isDND){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(r.on("ended",o=>{var t,s;this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(s=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:ts.CALL_ENDED,session:r,event:o});const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),r.on("progress",o=>{var a,t;this.context.logger.log("Session in progress for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:ts.CALL_PROGRESS,session:r,event:o})}),r.on("failed",o=>{var t,s;this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(s=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:ts.CALL_FAILED,session:r,event:o}),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),r.on("confirmed",o=>{var a,t;this.context.logger.log("Session confirmed for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:ts.CALL_CONFIRMED,session:r,event:o}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(n),r.direction==="outgoing"){const o=this.getActiveCalls[r.id].roomId;this.setActiveRoom(o)}}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(fo.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(fo.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 rv(this.metricConfig),o=r.createProbe(n.connection,{cid:n._id}),a=[];let t;o.onreport=s=>{Object.entries(s.audio).forEach(([d,g])=>{g.direction==="inbound"&&!a.includes(d)&&(a.push(d),t=d)});const p=s.audio[t],_=iv(p,lv);_.callId=n._id,this.setCallMetrics(r)},this.context.subscribe(ts.CALL_ENDED,s=>{s._id===n._id&&r.stopAllProbes()}),r.startAllProbes()}setupVUMeter(n,r){this.VUMeter.start(n,r)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){const n=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(r=>r.stop()),this.initialStreamValue=null),this.initialStreamValue=n}async triggerAddStream(n,r){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const o=s_(this.initialStreamValue,this.microphoneInputLevel*2),a=this.isMuted||this.muteWhenJoin;o.getTracks().forEach(s=>s.enabled=!a),this.setActiveStream(o),await r.connection.getSenders()[0].replaceTrack(o.getTracks()[0]);const t=new MediaStream([n.track]);Zg(t,r,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(t,r._id),this.getCallQuality(r),this.updateCall(r)}initCall(n,r){if(this.checkInitialized(),n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=o.id,r&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),o.connection.addEventListener("track",a=>{this.triggerAddStream(a,o)})}async processRoomChange({callId:n,roomId:r}){const o=this.extendedCalls[n].roomId;this.extendedCalls[n].roomId=r;const a=this.extendedCalls[n];return this.updateCall(a),await this.setActiveRoom(r),Promise.all([this.roomReconfigure(o),this.roomReconfigure(r)]).then(()=>{this.deleteRoomIfEmpty(o),this.deleteRoomIfEmpty(r)})}}class cv{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n){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}`,this.sipOptions),console.log("video call")}}class fv{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}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]=t_(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:t_(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,r){const o=this.msrpHistory[r.id]||[];o.push(n),this.msrpHistory={...this.msrpHistory,[r.id]:[...o]},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 o=n;this.addMMSRPSession(o)}triggerMSRPListener({listenerType:n,session:r,event:o}){const a=this.context.listenersList[n];!a||!a.length||a.forEach(t=>{t(r,o)})}removeMMSRPSession(n){const r={...this.activeMessages};delete r[n],this.activeMessages={...r};const o={...this.extendedMessages};delete o[n],this.extendedMessages={...o},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){const r=n.session;r.on("ended",o=>{this.triggerMSRPListener({listenerType:ts.CALL_ENDED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("failed",o=>{this.triggerMSRPListener({listenerType:ts.CALL_FAILED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("confirmed",o=>{this.triggerMSRPListener({listenerType:ts.CALL_CONFIRMED,session:r,event:o}),this.updateMSRPSession(r)}),r.on("newMessage",o=>{this.addMSRPMessage(o,r)}),this.addMessageSession(r)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,r,o){if(n.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(n,o);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,r){const o=this.extendedMessages[n];if(!o)throw new Error(`MSRP session with id ${n} doesn't exist!`);o.sendMSRP(r)}}const hu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class _v extends Jg{constructor(n,r){if(!n.modules.length)throw new Error("options.modules should include at least 1 module");const o={...n.configuration,sockets:n.socketInterfaces.map(a=>new hT.WebSocketInterface(a))};super(o),this.initialized=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],this.options=n,this.modules=n.modules,r&&eT(r)&&(this.logger=r)}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}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(hu.AUDIO)&&(this.audio=new uv(this)),this.modules.includes(hu.MSRP)&&(this.msrp=new fv(this)),this.modules.includes(hu.VIDEO)&&(this.video=new cv(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.isReconnecting=!1}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.isReconnecting=!0,this.stop(),this.setInitialized(!1),setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}subscribe(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:o}){const a=this.listenersList[n];!a||!a.length||a.forEach(t=>{t(r,o)})}setInitialized(n){this.initialized=n,this.emit("ready",n)}}return _v}();
|
155
|
+
`),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,console.log("dialog be",this._dialog),new yf(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:t=>{this.onTransportError(),console.log(t)},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t),console.log("dialog af",this._dialog),t.status_code===200&&(t.parseSDP(!0),this._status=Ce.STATUS_CONFIRMED,this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Ce.STATUS_INVITE_SENT}terminate(n={}){console.log("terminate",this);const r=n.cause||q.causes.BYE,o=Me.cloneArray(n.extraHeaders),a=n.body;let t,s=n.status_code,p=n.reason_phrase;if(this._status===Ce.STATUS_TERMINATED)throw new Ys.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:if(s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||q.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===Ce.STATUS_NULL||this._status===Ce.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===Ce.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=Ce.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,q.causes.CANCELED);break;case Ce.STATUS_WAITING_FOR_ANSWER:case Ce.STATUS_ANSWERED:if(s=s||480,console.log("REPLY 480"),s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._request.reply(s,p,o,a),console.log("failed 2"),this._failed("local",null,q.causes.REJECTED);break;case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:if(p=n.reason_phrase||q.REASON_PHRASE[s]||"",s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);if(s&&o.push(`Reason: SIP ;cause=${s}; text="${p}"`),this._status===Ce.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Lt.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:d})=>{d===q.ACK&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Lt.C.STATUS_TERMINATED&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())}),this._ended("local",null,r),this._dialog=_,this._ua.newDialog(_)}else console.log("here it is"),this.sendRequest(q.BYE,{extraHeaders:o,body:a}),this._ended("local",null,r)}}sendRequest(n,r){return this._dialog.sendRequest(n,r)}authenticate(n){this.status="auth";let r=new Un("");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 o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(r.toString())}onmessage(n){console.log("onmessage",n);const r=new Un(n.data);if(this.status==="auth"&&r.code===401){const o=this.parseAuth(r.getHeader("WWW-Authenticate")),a=new fm(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,Me.createRandomToken(12)),this.authenticate(a)}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),console.log("======================================================================")),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 o=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=r.candidate.candidate.match(o);this.my_ip=a&&a[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(q.ACK);return}else{const r=new Xl(this,n,"UAC");if(r.error!==void 0){console.log(r.error);return}this.sendRequest(q.ACK),this.sendRequest(q.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!==Ce.STATUS_INVITE_SENT&&this._status!==Ce.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(n.status_code):this._status=Ce.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=Ce.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 o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",n)).catch(a=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(console.log("maybe here???"),this._status=Ce.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,q.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",n,q.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(o=>this._connection.setLocalDescription(o)).catch(o=>{this._acceptAndTerminate(n,500,o.toString()),console.log("failed 4"),this._failed("local",n,q.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(n),this._accepted("remote",n),this.sendRequest(q.ACK),this._confirmed("local",null)});break}default:{const r=Me.sipErrorCause(n.status_code);console.log("failed 5"),this._failed("remote",n,r)}}}sendMSRP(n){const r=new Un("");r.method="SEND",r.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),r.addHeader("From-Path",`${this.my_addr[0]}`),r.addHeader("Message-ID",Me.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 o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),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,o=n.getHeader("Message-ID"),a=new Un("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.ident=r;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}_sendReport(n){let r=n.ident,o=n.getHeader("Message-ID"),a=new Un("");a.method="REPORT",a.addHeader("To-Path",`${n.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=r;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}parseAuth(n){const r={},o=n.replace("Digest","").split(",");for(const a of o){const t=a.trim().split("=");r[t[0]]=t[1].match('^"(.+)"$')[1]}return r}init_incoming(n,r){let o;const a=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&a!=="application/sdp"){n.reply(415);return}if(this._status=Ce.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")&&(o=n.getHeader("expires")*1e3),n.to_tag=Me.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=Ce.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),console.log("failed 6"),this._failed("local",null,q.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),console.log("failed 7"),this._failed("system",null,q.causes.EXPIRES))},o)),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!==Ce.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(n,r,o){this.emit("_failed",{originator:n,message:r||null,cause:o}),this._close(),this.emit("failed",{originator:n,message:r||null,cause:o})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ce.STATUS_TERMINATED){if(this._status=Ce.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,o){const a=r==="UAS"?n.to_tag:n.from_tag,t=r==="UAS"?n.from_tag:n.to_tag,s=n.call_id+a+t;let p=this._earlyDialogs[s];if(o)return p?!0:(p=new Xl(this,n,r,Xl.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[s]=p,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,p)return p.update(n,r),this._dialog=p,delete this._earlyDialogs[s],!0;const _=new Xl(this,n,r);return _.error?(console.log("failed 9"),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(this._dialog=_,!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 Ce.STATUS_CANCELED:case Ce.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,o){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:o})}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=q.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._runSessionTimer()}receiveRequest(n){if(console.log("receiveRequest()"),n.method===q.CANCEL)(this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED)&&(this._status=Ce.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",n,q.causes.CANCELED));else switch(n.method){case q.ACK:if(this._status!==Ce.STATUS_WAITING_FOR_ACK)return;if(this._status=Ce.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:q.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 o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(a=>{this.terminate({cause:q.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",n);break;case q.BYE:this._status===Ce.STATUS_CONFIRMED||this._status===Ce.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,q.causes.BYE)):this._status===Ce.STATUS_INVITE_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,q.causes.BYE)):n.reply(403,"Wrong Status");break;case q.INVITE:this._status===Ce.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case q.INFO:this._status===Ce.STATUS_1XX_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED||this._status===Ce.STATUS_WAITING_FOR_ACK||this._status===Ce.STATUS_CONFIRMED?(n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Va(this).init_incoming(n):n.reply(415):n.reply(403,"Wrong Status");break;case q.UPDATE:this._status===Ce.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case q.REFER:this._status===Ce.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case q.NOTIFY:this._status===Ce.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.CONNECTION_ERROR,cause:q.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:q.causes.REQUEST_TIMEOUT,cause:q.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.DIALOG_ERROR,cause:q.causes.DIALOG_ERROR})}}const Nt=console,Zf={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},zg=Wg;class Jg extends zg{constructor(n){super(n),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[]}call(n,r){return super.call(n,r)}joinVideoCall(n,r){Nt.debug("call()");const o=new oo(this);return o.connect(n,r),o}newMSRPSession(n,r){n.on("msgHistoryUpdate",o=>{console.log(o)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",r)}newJanusSession(n,r){this._janus_sessions[n.id]=n,this.emit("newJanusSession",r)}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}receiveRequest(n){const r=n.method;if(console.log("-----------"),n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){Nt.debug("Request-URI does not point to us"),n.method!==De.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===De.SIPS){n.reply_sl(416);return}if(Lt.checkTransaction(this,n))return;if(r===De.INVITE?new Lt.InviteServerTransaction(this,this._transport,n):r!==De.ACK&&r!==De.CANCEL&&new Lt.NonInviteServerTransaction(this,this._transport,n),r===De.OPTIONS){if(this.listeners("newOptions").length===0){n.reply(200);return}new lf.Options(this).init_incoming(n)}else if(r===De.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new lf.Message(this).init_incoming(n)}else if(r===De.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let o,a;if(n.to_tag)o=this._findDialog(n.call_id,n.from_tag,n.to_tag),o?o.receiveRequest(n):r===De.NOTIFY?(a=this._findSession(n),a?a.receiveRequest(n):(Nt.debug("received NOTIFY request for a non existent subscription"),n.reply(481,"Subscription does not exist"))):r!==De.ACK&&n.reply(481);else switch(r){case De.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const t=n.replaces;o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o?(a=o.owner,a.isEnded()?n.reply(603):a.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(a=new lu(this),a.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(a=new sg(this),a.init_incoming(n));else Nt.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case De.BYE:n.reply(481);break;case De.CANCEL:a=this._findSession(n),a?a.receiveRequest(n):Nt.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,r){Nt.debug("startMSRP()",r);const o=new lu(this);return o.connect(n),o}startJanus(n,r){Nt.debug("startJanus()",r);const o=new lu(this);return o.connect(n),o}terminateMSRPSessions(n){Nt.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(n)}terminateJanusSessions(n){Nt.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(n)}stop(){if(Nt.debug("stop()"),this._dynConfiguration={},this._status===Zf.STATUS_USER_CLOSED){Nt.debug("UA already closed");return}this._registrator.close();const n=Object.keys(this._sessions).length;for(const o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){Nt.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,o)){Nt.debug(`closing session ${o}`);try{this._msrp_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,o)){Nt.debug(`closing session ${o}`);try{this._janus_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch(a){console.error(a)}this._status=Zf.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&n===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}const es=new AudioContext,Xg=["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"],Qg=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function e_(c){const n={};return Xg.forEach(r=>{c[r]!==void 0&&(n[r]=c[r])}),n.localHold=c._localHold,n}function t_(c){const n={};return Qg.forEach(r=>{c[r]!==void 0&&(n[r]=c[r])}),n}function s_(c,n){const r=es.createMediaStreamSource(c),o=es.createMediaStreamDestination(),a=es.createGain();return r.connect(a),a.connect(o),a.gain.value=n,o.stream}function Zg(c,n,r,o){const a=document.createElement("audio");a.id=n._id,a.className="audioTag",a.srcObject=c,a.setSinkId(r),a.volume=o,a.play(),n.audioTag=a}function eT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}const tT=lt,sT=Xt(),It=new tT("WebSocketInterface");var nT=class{constructor(n){It.debug('new() [url:"%s"]',n),this._url=n,this._sip_uri=null,this._via_transport=null,this._ws=null;const r=sT.parse(n,"absoluteURI");if(r===-1)throw It.warn(`invalid WebSocket URI: ${n}`),new TypeError(`Invalid argument: ${n}`);if(r.scheme!=="wss"&&r.scheme!=="ws")throw It.warn(`invalid WebSocket URI scheme: ${r.scheme}`),new TypeError(`Invalid argument: ${n}`);this._sip_uri=`sip:${r.host}${r.port?`:${r.port}`:""};transport=ws`,this._via_transport=r.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(n){this._via_transport=n.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(It.debug("connect()"),this.isConnected()){It.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){It.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),It.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(n){this._onError(n)}}disconnect(){It.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(n){return It.debug("send()"),this.isConnected()?(this._ws.send(n),!0):(It.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(){It.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:n,code:r,reason:o}){It.debug(`WebSocket ${this._url} closed`),n===!1&&It.debug("WebSocket abrupt disconnection"),this.ondisconnect(!n,r,o)}_onMessage({data:n}){It.debug("received WebSocket message"),this.ondata(n)}_onError(n){It.warn(`WebSocket ${this._url} error: `,n)}};const ou=ol,rT=De,iT=hs,lT=pt(),oT=Qf,aT=cs(),uT=ba(),cT=Xt(),fT=nT;An("JsSIP")("version %s",ou.version);var _T={C:rT,Exceptions:iT,Utils:lT,UA:oT,URI:aT,NameAddrHeader:uT,WebSocketInterface:fT,Grammar:cT,debug:An,get name(){return ou.title},get version(){return ou.version}};const hT=it(_T);function au(c){return c<10?`0${c}`:`${c}`}function dT(c){let n=c.hours||0,r=c.minutes||0,o=c.seconds||0;o++,o===60&&(o=0,r++,r===60&&(r=0,n++));const a=`${au(n)}:${au(r)}:${au(o)}`;return{seconds:o,minutes:r,hours:n,formatted:a}}var vt={};vt.forEach=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)if(a in c){const t=Promise.resolve(c[a]).then(s=>n.call(r||globalThis,s,a,c));o.push(t)}await Promise.all(o)},vt.forEachSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)o in c&&await n.call(r||globalThis,await c[o],o,c)},vt.map=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=Promise.resolve(c[a]).then(t=>n.call(r||globalThis,t,a,c)));return Promise.all(o)},vt.mapSeries=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=await n.call(r||globalThis,await c[a],a,c));return o},vt.find=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o();let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(c[s]):t===c.length&&o(),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.findSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(await n.call(r||globalThis,await c[o],o,c))return c[o]},vt.findIndex=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(-1);let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(s):t===c.length&&o(-1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.findIndexSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(await n.call(r||globalThis,await c[o],o,c))return o},vt.some=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(!1);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?o(!0):t===c.length&&o(!1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.someSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(o in c&&await n.call(r||globalThis,await c[o],o,c))return!0;return!1},vt.every=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(!0);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?t===c.length&&o(!0):o(!1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.everySeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(o in c&&!await n.call(r||globalThis,await c[o],o,c))return!1;return!0},vt.filter=(c,n,r)=>new Promise(async(o,a)=>{const t=[];for(let p=0;p<c.length;p++)p in c&&(t[p]=Promise.resolve(c[p]).then(_=>n.call(r||globalThis,_,p,c)).catch(a));const s=[];for(let p=0;p<t.length;p++)await t[p]&&s.push(await c[p]);o(s)}),vt.filterSeries=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&await n.call(r||globalThis,await c[a],a,c)&&o.push(await c[a]);return o},vt.reduce=async(c,n,r)=>{if(c.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let o,a;for(r!==void 0?(a=r,o=0):(a=c[0],o=1),o;o<c.length;o++)o in c&&(a=await n(await a,await c[o],o,c));return a};var n_={};(function(c){const n=vt;Object.keys(n).forEach(r=>{const o=r.charAt(0).toUpperCase()+r.slice(1);c[`async${o}`]=async function(...a){return n[r](this,...a)}})})(n_);var r_=Object.assign(vt,{instanceMethods:n_});const ts={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var pT={exports:{}};(function(c){var n=function(r){var o=Object.prototype,a=o.hasOwnProperty,t=Object.defineProperty||function(ee,Y,G){ee[Y]=G.value},s,p=typeof Symbol=="function"?Symbol:{},_=p.iterator||"@@iterator",d=p.asyncIterator||"@@asyncIterator",g=p.toStringTag||"@@toStringTag";function T(ee,Y,G){return Object.defineProperty(ee,Y,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[Y]}try{T({},"")}catch{T=function(Y,G,re){return Y[G]=re}}function E(ee,Y,G,re){var ge=Y&&Y.prototype instanceof ae?Y:ae,be=Object.create(ge.prototype),xe=new P(re||[]);return t(be,"_invoke",{value:z(ee,G,xe)}),be}r.wrap=E;function y(ee,Y,G){try{return{type:"normal",arg:ee.call(Y,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",R="suspendedYield",I="executing",$="completed",L={};function ae(){}function N(){}function F(){}var Se={};T(Se,_,function(){return this});var ve=Object.getPrototypeOf,M=ve&&ve(ve(se([])));M&&M!==o&&a.call(M,_)&&(Se=M);var D=F.prototype=ae.prototype=Object.create(Se);N.prototype=F,t(D,"constructor",{value:F,configurable:!0}),t(F,"constructor",{value:N,configurable:!0}),N.displayName=T(F,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(Y){T(ee,Y,function(G){return this._invoke(Y,G)})})}r.isGeneratorFunction=function(ee){var Y=typeof ee=="function"&&ee.constructor;return Y?Y===N||(Y.displayName||Y.name)==="GeneratorFunction":!1},r.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,F):(ee.__proto__=F,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},r.awrap=function(ee){return{__await:ee}};function j(ee,Y){function G(be,xe,Re,le){var ye=y(ee[be],ee,xe);if(ye.type==="throw")le(ye.arg);else{var rt=ye.arg,ot=rt.value;return ot&&typeof ot=="object"&&a.call(ot,"__await")?Y.resolve(ot.__await).then(function(Ee){G("next",Ee,Re,le)},function(Ee){G("throw",Ee,Re,le)}):Y.resolve(ot).then(function(Ee){rt.value=Ee,Re(rt)},function(Ee){return G("throw",Ee,Re,le)})}}var re;function ge(be,xe){function Re(){return new Y(function(le,ye){G(be,xe,le,ye)})}return re=re?re.then(Re,Re):Re()}t(this,"_invoke",{value:ge})}B(j.prototype),T(j.prototype,d,function(){return this}),r.AsyncIterator=j,r.async=function(ee,Y,G,re,ge){ge===void 0&&(ge=Promise);var be=new j(E(ee,Y,G,re),ge);return r.isGeneratorFunction(Y)?be:be.next().then(function(xe){return xe.done?xe.value:be.next()})};function z(ee,Y,G){var re=A;return function(be,xe){if(re===I)throw new Error("Generator is already running");if(re===$){if(be==="throw")throw xe;return nt()}for(G.method=be,G.arg=xe;;){var Re=G.delegate;if(Re){var le=H(Re,G);if(le){if(le===L)continue;return le}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=$,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=I;var ye=y(ee,Y,G);if(ye.type==="normal"){if(re=G.done?$:R,ye.arg===L)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=$,G.method="throw",G.arg=ye.arg)}}}function H(ee,Y){var G=Y.method,re=ee.iterator[G];if(re===s)return Y.delegate=null,G==="throw"&&ee.iterator.return&&(Y.method="return",Y.arg=s,H(ee,Y),Y.method==="throw")||G!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+G+"' method")),L;var ge=y(re,ee.iterator,Y.arg);if(ge.type==="throw")return Y.method="throw",Y.arg=ge.arg,Y.delegate=null,L;var be=ge.arg;if(!be)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,L;if(be.done)Y[ee.resultName]=be.value,Y.next=ee.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=s);else return be;return Y.delegate=null,L}B(D),T(D,g,"Generator"),T(D,_,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function Z(ee){var Y={tryLoc:ee[0]};1 in ee&&(Y.catchLoc=ee[1]),2 in ee&&(Y.finallyLoc=ee[2],Y.afterLoc=ee[3]),this.tryEntries.push(Y)}function U(ee){var Y=ee.completion||{};Y.type="normal",delete Y.arg,ee.completion=Y}function P(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(Z,this),this.reset(!0)}r.keys=function(ee){var Y=Object(ee),G=[];for(var re in Y)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in Y)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var Y=ee[_];if(Y)return Y.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(a.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=s,ge.done=!0,ge};return re.next=re}}return{next:nt}}r.values=se;function nt(){return{value:s,done:!0}}return P.prototype={constructor:P,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=s,this.done=!1,this.delegate=null,this.method="next",this.arg=s,this.tryEntries.forEach(U),!ee)for(var Y in this)Y.charAt(0)==="t"&&a.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=s)},stop:function(){this.done=!0;var ee=this.tryEntries[0],Y=ee.completion;if(Y.type==="throw")throw Y.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var Y=this;function G(le,ye){return be.type="throw",be.arg=ee,Y.next=le,ye&&(Y.method="next",Y.arg=s),!!ye}for(var re=this.tryEntries.length-1;re>=0;--re){var ge=this.tryEntries[re],be=ge.completion;if(ge.tryLoc==="root")return G("end");if(ge.tryLoc<=this.prev){var xe=a.call(ge,"catchLoc"),Re=a.call(ge,"finallyLoc");if(xe&&Re){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0);if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else if(xe){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0)}else if(Re){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,Y){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&a.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=Y&&Y<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=Y,ge?(this.method="next",this.next=ge.finallyLoc,L):this.complete(be)},complete:function(ee,Y){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&Y&&(this.next=Y),L},finish:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),L}},catch:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.tryLoc===ee){var re=G.completion;if(re.type==="throw"){var ge=re.arg;U(G)}return ge}}throw new Error("illegal catch attempt")},delegateYield:function(ee,Y,G){return this.delegate={iterator:se(ee),resultName:Y,nextLoc:G},this.method==="next"&&(this.arg=s),L}},r}(c.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})(pT);var i_={exports:{}};(function(c){(function(n,r){c.exports?c.exports=r():n.log=r()})(E_,function(){var n=function(){},r="undefined",o=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function t(R,I){var $=R[I];if(typeof $.bind=="function")return $.bind(R);try{return Function.prototype.bind.call($,R)}catch{return function(){return Function.prototype.apply.apply($,[R,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(R){return R==="debug"&&(R="log"),typeof console===r?!1:R==="trace"&&o?s:console[R]!==void 0?t(console,R):console.log!==void 0?t(console,"log"):n}function _(R,I){for(var $=0;$<a.length;$++){var L=a[$];this[L]=$<R?n:this.methodFactory(L,R,I)}this.log=this.debug}function d(R,I,$){return function(){typeof console!==r&&(_.call(this,I,$),this[R].apply(this,arguments))}}function g(R,I,$){return p(R)||d.apply(this,arguments)}function T(R,I,$){var L=this,ae;I=I??"WARN";var N="loglevel";typeof R=="string"?N+=":"+R:typeof R=="symbol"&&(N=void 0);function F(D){var B=(a[D]||"silent").toUpperCase();if(!(typeof window===r||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Se(){var D;if(!(typeof window===r||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===r)try{var B=window.document.cookie,j=B.indexOf(encodeURIComponent(N)+"=");j!==-1&&(D=/^([^;]+)/.exec(B.slice(j))[1])}catch{}return L.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===r||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}L.name=R,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=$||g,L.getLevel=function(){return ae},L.setLevel=function(D,B){if(typeof D=="string"&&L.levels[D.toUpperCase()]!==void 0&&(D=L.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=L.levels.SILENT){if(ae=D,B!==!1&&F(D),_.call(L,D,R),typeof console===r&&D<L.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},L.setDefaultLevel=function(D){I=D,Se()||L.setLevel(D,!1)},L.resetLevel=function(){L.setLevel(I,!1),ve()},L.enableAll=function(D){L.setLevel(L.levels.TRACE,D)},L.disableAll=function(D){L.setLevel(L.levels.SILENT,D)};var M=Se();M==null&&(M=I),L.setLevel(M,!1)}var E=new T,y={};E.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var $=y[I];return $||($=y[I]=new T(I,E.getLevel(),E.methodFactory)),$};var A=typeof window!==r?window.log:void 0;return E.noConflict=function(){return typeof window!==r&&window.log===E&&(window.log=A),E},E.getLoggers=function(){return y},E.default=E,E})})(i_);var At=i_.exports;const ds=()=>`${new Date().toISOString()} | metrics`,ps=(c,n,r)=>`${c} | ${n} | ${r}`;At.setDefaultLevel(At.levels.TRACE);const mT=c=>{At.info(ps(ds(),"log ",`set log level to ${c?"verbose":"info"}`)),At.setLevel(c?At.levels.TRACE:At.levels.INFO)},gT=c=>{const n=[...Object.keys(At.levels)];n.includes(c)?(At.info(ps(ds(),"log ",`update log level to ${c.toLowerCase()}`)),At.setLevel(c)):At.warn(ps(ds(),"log ","Incorrect log level please choose one of "),n)},Pe=(c,n,r)=>{r?At.debug(ps(ds(),c,n),r):At.debug(ps(ds(),c,n))},uu=(c,n)=>{At.info(ps(ds(),c,n))},Qs=(c,n)=>{At.info(ps(ds(),c,n))},ao=(c,n)=>{At.warn(ps(ds(),c,n))},Pn=(c,n)=>{At.error(ps(ds(),c,n))};function TT(c){return Math.floor(Math.random()*c).toString()}function l_(c,n){let r=n;return c.forEach(o=>{r=r.replace(o,"")}),r}function vT(c,n){let r="";for(let o=0;o<n;o+=1)r+=c[TT(c.length)];return r}function ET({length:c=20,useLetters:n=!0,useNumbers:r=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let t="abcdefghijklmnopqrstuvwxyz",s="0123456789",p=[],_=[],d=[];return n&&(a.length&&(t=l_(a,t)),_=t.split("")),r&&(a.length&&(s=l_(a,s)),d=s.split("")),p=[..._,...d,...o],vT(p,c)}var ST=ET;const Wr=it(ST),yT=()=>"WebRTCMetrics",AT=()=>"5.0.3",Le={INBOUND:"inbound",OUTBOUND:"outbound"},ms={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Kr={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},CT=()=>({...{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:[]}}),o_={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:Le.INBOUND},a_={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:Le.OUTBOUND},u_={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:Le.INBOUND},c_={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:Le.OUTBOUND},RT=c=>{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(c){const r={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(o=>{r.audio[o]={...c.audio[o]}}),Object.keys(c.video).forEach(o=>{r.video[o]={...c.video[o]}}),r}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},IT={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Wr()}`,cid:`c-${Wr()}`,uid:`u-${Wr()}`,record:!1,ticket:!0},Wt={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"},V={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"},x={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Yr={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},cu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},fu="config ",bT=(c,n={},r)=>{const o={...r,...n};return n.pname||ao(fu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),n.cid||ao(fu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),n.uid||ao(fu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),o.pc=c,o},wT=(c={})=>{const n={...IT,...c};return n.name=yT(),n.version=AT(),n},zr=(c,n,r,o=!1,a)=>{let t=c.map(s=>{if(!r)return s[n];if(!a)return s[n][r];const p=s[n][a];return p?p[r]:null});return t=t.filter(s=>o?Number.isFinite(s)&&s>0:Number.isFinite(s)),t.length===0?[]:t},ws=c=>c.reduce((n,r)=>n+r,0)/c.length,OT=()=>`probe-${Wr()}`,DT=()=>`coltr-${Wr()}`,f_=c=>new Promise(n=>setTimeout(n,c)),_u=(c,n,r)=>{n?c.call(n,r):c(r)},Ge=(c,n,r,o)=>{const a=zr(c,n,r,!0,o);if(a.length===0)return null;const t=a.reduce((d,g)=>d+g,0)/a.length;return t===0?null:a.map(d=>Math.abs(t-d)).reduce((d,g)=>d+g,0)/a.length*100/t},Je=(c,n,r,o=!1,a)=>{const t=zr(c,n,r,o,a);return t.length===0?null:t.reduce((s,p)=>s+p,0)/t.length},Zs=(c,n,r)=>zr(c,n,r).reduce((a,t)=>a+t,0),We=(c,n,r,o)=>{const a=zr(c,n,r,!0,o);return a.length===0?null:Math.min(...a)},Ke=(c,n,r,o)=>{const a=zr(c,n,r,!1,o);return a.length===0?null:Math.max(...a)},Et=(c,n,r,o)=>{const a=c.slice().pop();if(!a)return null;if(!r)return a[n];if(!o)return a[n][r];const t=a[n][o];return t?t[r]:null},NT=c=>c.slice().pop(),ft=(c,n,r)=>{if(!n)return null;const o={};let a=n[x.AUDIO][c];a||(a=r===Le.INBOUND?{...o_}:{...a_}),o[x.AUDIO]=a;let t=n[x.VIDEO][c];return t||(t=r===Le.INBOUND?{...u_}:{...c_}),o[x.VIDEO]=t,o},Jr="exporter ",UT="2.0",__=(c,n,r)=>{if(!c||c.length===0)return 0;const o=c[c.length-1];if(!o)return 0;const a=o[n][r];if(a){const t=a.total_rtt_ms_out,s=a.total_rtt_measure_out;return!s||!t?Je(c,n,"delta_rtt_ms_out",!1,r):Number(t/s)}return null},PT=(c,n)=>{if(!c||c.length===0)return 0;const r=c[c.length-1];if(!r)return 0;const o=r[n].total_rtt_connectivity_ms,a=r[n].total_rtt_connectivity_measure;return!a||!o?Je(c,n,"delta_rtt_connectivity_ms"):Number(o/a)},xT=c=>Et(c,"network","local_candidate_type")!=="relay"?`direct/${Et(c,"network","local_candidate_protocol")}`:`turn/${Et(c,"network","local_candidate_relay_protocol")}`,MT=c=>{const n=Et(c,"network","remote_candidate_type"),r=Et(c,"network","remote_candidate_protocol");return n!=="relay"?`direct/${r}`:`turn/${r}`};class kT{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){uu(Jr,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){uu(Jr,"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&&(Pe(Jr,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){uu(Jr,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Pe(Jr,"ticket() - generate ticket");const n=Et(this._reports,"audio","total_packets_lost_in"),r=Et(this._reports,"audio","total_packets_in"),o=Et(this._reports,"video","total_packets_lost_in"),a=Et(this._reports,"video","total_packets_in"),t={},s=NT(this._reports);return s&&(Object.keys(s[x.AUDIO]).forEach(p=>{const _=s[x.AUDIO][p];if(t[_.ssrc]={type:x.AUDIO,direction:_.direction},_.direction===Le.INBOUND){const d={avg:Je(this._reports,x.AUDIO,"delta_jitter_ms_in",!1,p),min:We(this._reports,x.AUDIO,"delta_jitter_ms_in",p),max:Ke(this._reports,x.AUDIO,"delta_jitter_ms_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.AUDIO,"delta_kbs_in",!1,p),min:We(this._reports,x.AUDIO,"delta_kbs_in",p),max:Ke(this._reports,x.AUDIO,"delta_kbs_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.AUDIO,"delta_KBytes_in",!1,p),min:We(this._reports,x.AUDIO,"delta_KBytes_in",p),max:Ke(this._reports,x.AUDIO,"delta_KBytes_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:Je(this._reports,x.AUDIO,"mos_emodel_in",!1,p),min:We(this._reports,x.AUDIO,"mos_emodel_in",p),max:Ke(this._reports,x.AUDIO,"mos_emodel_in",p),volatility:Ge(this._reports,x.AUDIO,"mos_emodel_in",p)},effective:{avg:Je(this._reports,x.AUDIO,"mos_in",!1,p),min:We(this._reports,x.AUDIO,"mos_in",p),max:Ke(this._reports,x.AUDIO,"mos_in",p),volatility:Ge(this._reports,x.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=Et(this._reports,x.AUDIO,"total_packets_lost_in",p),A=Et(this._reports,x.AUDIO,"total_packets_in",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].mos=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R}else{const d={avg:Je(this._reports,x.AUDIO,"delta_jitter_ms_out",!1,p),min:We(this._reports,x.AUDIO,"delta_jitter_ms_out",p),max:Ke(this._reports,x.AUDIO,"delta_jitter_ms_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.AUDIO,"delta_kbs_out",!1,p),min:We(this._reports,x.AUDIO,"delta_kbs_out",p),max:Ke(this._reports,x.AUDIO,"delta_kbs_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.AUDIO,"delta_KBytes_out",!1,p),min:We(this._reports,x.AUDIO,"delta_KBytes_out",p),max:Ke(this._reports,x.AUDIO,"delta_KBytes_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:__(this._reports,x.AUDIO,p),min:We(this._reports,x.AUDIO,"delta_rtt_ms_out",p),max:Ke(this._reports,x.AUDIO,"delta_rtt_ms_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Et(this._reports,x.AUDIO,"total_packets_lost_out",p),A=Et(this._reports,x.AUDIO,"total_packets_out",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:Je(this._reports,x.AUDIO,"mos_emodel_out",!1,p),min:We(this._reports,x.AUDIO,"mos_emodel_out",p),max:Ke(this._reports,x.AUDIO,"mos_emodel_out",p),volatility:Ge(this._reports,x.AUDIO,"mos_emodel_out",p)},effective:{avg:Je(this._reports,x.AUDIO,"mos_out",!1,p),min:We(this._reports,x.AUDIO,"mos_out",p),max:Ke(this._reports,x.AUDIO,"mos_out",p),volatility:Ge(this._reports,x.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R,t[p].mos=I}}),Object.keys(s[x.VIDEO]).forEach(p=>{const _=s[x.VIDEO][p];if(t[p]={type:x.VIDEO,direction:_.direction},_.direction===Le.INBOUND){const d={avg:Je(this._reports,x.VIDEO,"delta_jitter_ms_in",!1,p),min:We(this._reports,x.VIDEO,"delta_jitter_ms_in",p),max:Ke(this._reports,x.VIDEO,"delta_jitter_ms_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.VIDEO,"delta_kbs_in",!1,p),min:We(this._reports,x.VIDEO,"delta_kbs_in",p),max:Ke(this._reports,x.VIDEO,"delta_kbs_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.VIDEO,"delta_KBytes_in",!1,p),min:We(this._reports,x.VIDEO,"delta_KBytes_in",p),max:Ke(this._reports,x.VIDEO,"delta_KBytes_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=Et(this._reports,x.VIDEO,"total_packets_lost_in",p),y=Et(this._reports,x.VIDEO,"total_packets_in",p),A={lost:E,avg:Math.round((E/(E+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].traffic=T,t[p].bitrate=g,t[p].loss=A}else{const d={avg:Je(this._reports,x.VIDEO,"delta_jitter_ms_out",!1,p),min:We(this._reports,x.VIDEO,"delta_jitter_ms_out",p),max:Ke(this._reports,x.VIDEO,"delta_jitter_ms_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.VIDEO,"delta_kbs_out",!1,p),min:We(this._reports,x.VIDEO,"delta_kbs_out",p),max:Ke(this._reports,x.VIDEO,"delta_kbs_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.VIDEO,"delta_KBytes_out",!1,p),min:We(this._reports,x.VIDEO,"delta_KBytes_out",p),max:Ke(this._reports,x.VIDEO,"delta_KBytes_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:__(this._reports,x.VIDEO,p),min:We(this._reports,x.VIDEO,"delta_rtt_ms_out",p),max:Ke(this._reports,x.VIDEO,"delta_rtt_ms_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Et(this._reports,x.VIDEO,"total_packets_lost_out",p),A=Et(this._reports,x.VIDEO,"total_packets_out",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R}})),{version:UT,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:t,data:{rtt:{avg:PT(this._reports,"data"),min:We(this._reports,"data","delta_rtt_connectivity_ms"),max:Ke(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ge(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((o/(o+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Je(this._reports,"data","delta_kbs_in"),min:We(this._reports,"data","delta_kbs_in"),max:Ke(this._reports,"data","delta_kbs_in"),volatility:Ge(this._reports,"data","delta_kbs_in")},out:{avg:Je(this._reports,"data","delta_kbs_out"),min:We(this._reports,"data","delta_kbs_out"),max:Ke(this._reports,"data","delta_kbs_out"),volatility:Ge(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Je(this._reports,"data","delta_KBytes_in"),min:We(this._reports,"data","delta_KBytes_in"),max:Ke(this._reports,"data","delta_KBytes_in"),volatility:Ge(this._reports,"data","delta_KBytes_in")},out:{avg:Je(this._reports,"data","delta_KBytes_out"),min:We(this._reports,"data","delta_KBytes_out"),max:Ke(this._reports,"data","delta_KBytes_out"),volatility:Ge(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:xT(this._reports),remoteConnection:MT(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 Os="extractor ",h_=(c,n,r,o)=>{let a=!1;const t=o[n].total_rtt_ms_out,s=o[n].total_rtt_measure_out,p=r?r[n].total_rtt_ms_out:0,_=r?r[n].total_rtt_measure_out:0,d={rtt:null,totalRTT:t,totalRTTMeasurements:s};if(c[V.TIMESTAMP]===o[n].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_===s))return d;const g=1e3*Number(c[V.ROUND_TRIP_TIME]);let T=t+g,E=s+1;return a&&(T=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-p,E=Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_),{rtt:g,totalRTT:T,totalRTTMeasurements:E}},LT=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:o[n].total_rtt_connectivity_ms,totalRTTMeasurements:o[n].total_rtt_connectivity_measure};const a=1e3*Number(c[V.CURRENT_ROUND_TRIP_TIME]);let t=o[n].total_rtt_connectivity_ms+a,s=o[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME)&&(t=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-(r?r[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,V.RESPONSES_RECEIVED)&&(s=Number(c[V.RESPONSES_RECEIVED])-(r?r[n].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:t,totalRTTMeasurements:s}},uo=(c,n,r)=>c[V.TIMESTAMP]===r[n].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.JITTER)?null:1e3*(Number(c[V.JITTER])||0),$T=(c,n)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[x.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[x.VIDEO].total_frames_decoded_in,total_decode_time:n[x.VIDEO].total_time_decoded_in};const r=c[V.FRAMES_DECODED],o=c[V.TOTAL_DECODE_TIME],a=o-n[x.VIDEO].total_time_decoded_in,t=r-n[x.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:t>0?a*1e3/t:0,frames_decoded:r,total_decode_time:o}},HT=(c,n)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[x.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[x.VIDEO].total_frames_encoded_out,total_encode_time:n[x.VIDEO].total_time_encoded_out};const r=c[V.FRAMES_ENCODED],o=c[V.TOTAL_ENCODE_TIME],a=o-n[x.VIDEO].total_time_encoded_out,t=r-n[x.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:t>0&&a?a*1e3/t:0,frames_encoded:r,total_encode_time:o}},d_=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,V.BYTES_SENT))return{packetsSent:r[n].total_packets_out,packetsLost:r[n].total_packets_lost_out,bytesSent:r[n].total_KBytes_out};const a=Number(c[V.PACKETS_SENT])||0-(o?o[n].total_packets_out:0),t=a-r[n].total_packets_out,s=Number(c[V.BYTES_SENT])/1024-(o?o[n].total_KBytes_out:0),p=s-r[n].total_KBytes_out,_=c[V.TIMESTAMP]||Date.now(),d=o?o.timestamp:null;let g=r.timestamp;!g&&d&&(g=d);const T=g?_-g:0,E=T>0?p*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:t,KBytesSent:s,deltaKBytesSent:p,kbsSent:E}},p_=(c,n,r,o)=>{let a=r[n].total_packets_lost_out,t=0,s=0;return Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)&&(a=Number(c[V.PACKETS_LOST])||0-(o?o[n].total_packets_lost_out:0),t=a-r[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,V.FRACTION_LOST)&&(s=Number(100*c[V.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:t,fractionLost:s}},m_=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,V.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 a=Number(c[V.PACKETS_RECEIVED])||0-(o?o[n].total_packets_in:0),t=Number(c[V.PACKETS_LOST])||0-(o?o[n].total_packets_lost_in:0),s=t-r[n].total_packets_lost_in,p=a-r[n].total_packets_in,_=a!==r[n].total_packets_in?s*100/(s+p):0,d=Number(c[V.BYTES_RECEIVED])/1024-(o?o[n].total_KBytes_in:0),g=d-r[n].total_KBytes_in,T=c[V.TIMESTAMP]||Date.now(),E=o?o.timestamp:null;let y=r.timestamp;!y&&E&&(y=E);const A=y?T-y:0,R=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:_,packetsReceived:a,deltaPacketsReceived:p,packetsLost:t,deltaPacketsLost:s,KBytesReceived:d,deltaKBytesReceived:g,kbsReceived:R}},FT=c=>c[V.CANDIDATE_TYPE]!=="relay"?"":c[V.RELAY_PROTOCOL]||"",VT=c=>{if(!Object.prototype.hasOwnProperty.call(c,V.NETWORK_TYPE))return Yr.WIFI;switch(c[V.NETWORK_TYPE]){case cu.ETHERNET:return Yr.ETHERNET;case cu.CELLULAR_4G:return Yr.CELLULAR_4G;case cu.WIFI:return Yr.WIFI;default:return Yr.CELLULAR}},g_=c=>!Object.prototype.hasOwnProperty.call(c,V.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,V.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[V.FRAME_WIDTH]||null,height:c[V.FRAME_HEIGHT]||null,framerate:c[V.FRAMES_PER_SECOND]},jT=c=>{const n=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_REASON)?c[V.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[V.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,o=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_DURATIONS)?c[V.QUALITY_LIMITATION_DURATIONS]:null;return o&&Object.keys(o).forEach(a=>{o[a]>1e3&&(o[a]=Number(o[a]/1e3))}),{reason:n,durations:o,resolutionChanges:r}},qT=(c,n,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_sent_in:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_sent_in:0);return{pliCount:o,nackCount:a,deltaPliCount:o-n[x.VIDEO].total_pli_sent_in,deltaNackCount:a-n[x.VIDEO].total_nack_sent_in}},BT=(c,n,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_received_out:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_received_out:0);return{pliCount:o,nackCount:a,deltaPliCount:o-n[x.VIDEO].total_pli_received_out,deltaNackCount:a-n[x.VIDEO].total_nack_received_out}},GT=c=>({channels:c[V.CHANNELS]||null,clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null,sdp_fmtp_line:c[V.SDP_FMTP_LINE]||null}),WT=c=>({clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null}),KT=(c,n,r)=>{const o=(c[V.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),a=(c[V.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),t=c[V.TIMESTAMP]||Date.now(),s=o-n.data.total_KBytes_in,p=a-n.data.total_KBytes_out,_=r?r.timestamp:null;let d=n.timestamp;!d&&_&&(d=_);const g=d?t-d:0,T=g>0?s*.008*1024/g*1e3:0,E=g>0?p*.008*1024/g*1e3:0;return{total_KBytes_received:o,total_KBytes_sent:a,delta_KBytes_received:s,delta_KBytes_sent:p,kbs_speed_received:T,kbs_speed_sent:E}},YT=c=>{const n=c[V.AVAILABLE_INCOMING_BITRATE]/1024||0,r=c[V.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:r}},zT=(c,n,r,o)=>{if(!c)return[];switch(c[V.TYPE]){case Wt.CANDIDATE_PAIR:let a=!1;if(c[V.NOMINATED]&&c[V.STATE]===x.SUCCEEDED&&(a=!0,Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c),V.SELECTED in c&&!c[V.SELECTED]&&(a=!1)),a){const s=c[V.LOCAL_CANDIDATE_ID],p=c[V.REMOTE_CANDIDATE_ID],_=KT(c,n,o),d=YT(c),g=LT(c,"data",o,n);return[{type:ne.NETWORK,value:{local_candidate_id:s}},{type:ne.NETWORK,value:{remote_candidate_id:p}},{type:ne.DATA,value:{total_KBytes_in:_.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:_.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:_.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:_.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:_.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:_.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:d.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:d.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case Wt.LOCAL_CANDIDATE:if(c[V.ID]===n.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:VT(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[V.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:FT(c)}}];break;case Wt.REMOTE_CANDIDATE:if(c[V.ID]===n.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[V.PROTOCOL]||""}}];break;case Wt.INBOUND_RTP:{Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.INBOUND);p&&(p.timestamp=n.timestamp);const _=ft(s,o,Le.INBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=m_(c,x.AUDIO,p,_),g=uo(c,x.AUDIO,p),T=c[V.CODEC_ID]||"";return[{ssrc:s,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:s,type:ne.AUDIO,value:{total_packets_in:d.packetsReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:s,type:ne.AUDIO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=$T(c,p),g=m_(c,x.VIDEO,p,_),T=uo(c,x.VIDEO,p),E=c[V.DECODER_IMPLEMENTATION]||null,y=c[V.CODEC_ID]||null,A=g_(c),R=qT(c,p,_);return[{ssrc:s,type:ne.VIDEO,value:{codec_id_in:y}},{ssrc:s,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:s,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:s,type:ne.VIDEO,value:{decoder_in:E}},{ssrc:s,type:ne.VIDEO,value:{delta_ms_decode_frame_in:d.delta_ms_decode_frame}},{ssrc:s,type:ne.VIDEO,value:{total_frames_decoded_in:d.frames_decoded}},{ssrc:s,type:ne.VIDEO,value:{total_time_decoded_in:d.total_decode_time}},{ssrc:s,type:ne.VIDEO,value:{total_nack_sent_in:R.nackCount}},{ssrc:s,type:ne.VIDEO,value:{delta_nack_sent_in:R.deltaNackCount}},{ssrc:s,type:ne.VIDEO,value:{total_pli_sent_in:R.pliCount}},{ssrc:s,type:ne.VIDEO,value:{delta_pli_sent_in:R.deltaPliCount}},{ssrc:s,type:ne.VIDEO,value:{size_in:A}}]}break}case Wt.OUTBOUND_RTP:{Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.OUTBOUND);p&&(p.timestamp=n.timestamp);const _=ft(s,o,Le.OUTBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=c[V.CODEC_ID]||null,g=d_(c,x.AUDIO,p,_);return[{ssrc:s,type:ne.AUDIO,value:{codec_id_out:d}},{ssrc:s,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:s,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:s,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:s,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=c[V.ENCODER_IMPLEMENTATION]||null,g=c[V.CODEC_ID]||null,T=HT(c,p),E=g_(c),y=jT(c),A=BT(c,p,_),R=d_(c,x.VIDEO,p,_);return[{ssrc:s,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:s,type:ne.VIDEO,value:{total_packets_out:R.packetsSent}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_out:R.deltaPacketsSent}},{ssrc:s,type:ne.VIDEO,value:{total_KBytes_out:R.KBytesSent}},{ssrc:s,type:ne.VIDEO,value:{delta_KBytes_out:R.deltaKBytesSent}},{ssrc:s,type:ne.VIDEO,value:{delta_kbs_out:R.kbsSent}},{ssrc:s,type:ne.VIDEO,value:{encoder_out:d}},{ssrc:s,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:s,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:s,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:s,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:s,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:s,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:s,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:s,type:ne.VIDEO,value:{size_out:E}},{ssrc:s,type:ne.VIDEO,value:{limitation_out:y}}]}break}case Wt.MEDIA_SOURCE:{Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case Wt.TRACK:{Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case Wt.CODEC:const t=[];return Object.keys(n[x.AUDIO]).forEach(s=>{const p=n[x.AUDIO][s];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=GT(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_out:_}})}}),Object.keys(n[x.VIDEO]).forEach(s=>{const p=n[x.VIDEO][s];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=WT(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_out:_}})}}),t;case Wt.REMOTE_INBOUND_RTP:{Pe(Os,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.OUTBOUND),_=ft(s,o,Le.OUTBOUND);if(c[V.KIND]===x.AUDIO){const d=h_(c,x.AUDIO,_,p),g=uo(c,x.AUDIO,p),T=p_(c,x.AUDIO,p,_);return[{ssrc:s,type:ne.AUDIO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ne.AUDIO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ne.AUDIO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ne.AUDIO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:s,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[V.KIND]===x.VIDEO){const d=h_(c,x.VIDEO,_,p),g=uo(c,x.VIDEO,p),T=p_(c,x.VIDEO,p,_);return[{ssrc:s,type:ne.VIDEO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ne.VIDEO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ne.VIDEO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ne.VIDEO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:s,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},co=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),JT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.INBOUND),s=ft(a,r,Le.INBOUND),p=ft(a,o,Le.INBOUND),_=[],d=[],g=t[n].percent_packets_lost_in,T=t[n].delta_jitter_ms_in,E=s&&s[n].delta_jitter_ms_in||null,y=p&&p[n].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),R&&_.push(R),I&&_.push(I),T&&d.push(T),r&&E&&d.push(E),o&&y&&d.push(y);const $=_.length>0?ws(_):100,L=d.length>0?ws(d):10,ae=93.2-g,N=.18*ae*ae-27.9*ae+1126.62,F=($+L)/2,Se=F-177.3<0?0:1,ve=.024*F+.11*(F-177.3)*Se,M=N-ve;return co(M)},XT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.OUTBOUND),s=ft(a,r,Le.OUTBOUND),p=ft(a,o,Le.OUTBOUND),_=[],d=[],g=t[n].percent_packets_lost_out,T=t[n].delta_rtt_ms_out,E=s&&s[n].delta_rtt_ms_out||null,y=p&&p[n].delta_rtt_ms_out||null,A=t[n].delta_jitter_ms_out,R=s&&s[n].delta_jitter_ms_out||null,I=p&&p[n].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),r&&R&&d.push(R),o&&I&&d.push(I);const N=_.length>0?ws(_):100,F=d.length>0?ws(d):10,Se=93.2-g,ve=.18*Se*Se-27.9*Se+1126.62,M=(N+F)/2,D=M-177.3<0?0:1,B=.024*M+.11*(M-177.3)*D,j=ve-B;return co(j)},QT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.INBOUND),s=ft(a,r,Le.INBOUND),p=ft(a,o,Le.INBOUND),_=[],d=[],g=t[n].percent_packets_lost_in/100,T=t[n].delta_jitter_ms_in,E=s&&s[n].delta_jitter_ms_in||null,y=p&&p[n].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),R&&_.push(R),I&&_.push(I),T&&d.push(T),s&&E&&d.push(E),p&&y&&d.push(y);const $=_.length>0?ws(_):100,L=d.length>0?ws(d):10,ae=0,N=19.8,F=29.7,Se=30,ve=($+L)/2+Se,M=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*M,j=93.2-(ae+N*Math.log(1+F*g)+D);return co(j)},ZT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.OUTBOUND),s=ft(a,r,Le.OUTBOUND),p=ft(a,o,Le.OUTBOUND),_=[],d=[],g=t[n].percent_packets_lost_out/100,T=t[n].delta_rtt_ms_out,E=s&&s[n].delta_rtt_ms_out||null,y=p&&p[n].delta_rtt_ms_out||null,A=t[n].delta_jitter_ms_out,R=s&&s[n].delta_jitter_ms_out||null,I=p&&p[n].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),s&&R&&d.push(R),p&&I&&d.push(I);const N=_.length>0?ws(_):100,F=d.length>0?ws(d):10,Se=0,ve=19.8,M=29.7,D=30,B=(N+F)/2+D,j=B-177.3<0?0:1,z=.024*B+.11*(B-177.3)*j,Z=93.2-(Se+ve*Math.log(1+M*g)+z);return co(Z)};class ev{constructor(n,r){this._callbacks={onreport:null,onticket:null},this._id=DT(),this._moduleName=this._id,this._probeId=r,this._config=n,this._exporter=new kT(n),this._state=ms.IDLE,this.registerToPCEvents(),Qs(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,r,o,a){const t=(_,d)=>_===x.AUDIO?d===Wt.INBOUND_RTP?{...o_}:{...a_}:d===Wt.INBOUND_RTP?{...u_}:{...c_},s=RT(r);s.pname=this._config.pname,s.call_id=this._config.cid,s.user_id=this._config.uid,s.count=r?r.count+1:1;let p=null;return n.forEach(_=>{!p&&_.timestamp&&(p=_.timestamp),zT(_,s,s.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=s[g.type][g.ssrc];T||(T=t(g.type,_.type),T.ssrc=g.ssrc,s[g.type][g.ssrc]=T),Object.keys(g.value).forEach(E=>{T[E]=g.value[E]})}else Object.keys(g.value).forEach(T=>{s[g.type][T]=g.value[T]})})}),s.timestamp=p,Object.keys(s[x.AUDIO]).forEach(_=>{const d=s[x.AUDIO][_];d.direction===Le.INBOUND?(d.mos_emodel_in=JT(s,x.AUDIO,r,o,d.ssrc),d.mos_in=QT(s,x.AUDIO,r,o,d.ssrc)):(d.mos_emodel_out=XT(s,x.AUDIO,r,o,d.ssrc),d.mos_out=ZT(s,x.AUDIO,r,o,d.ssrc))}),s}async takeReferenceStats(){return new Promise((n,r)=>{const o=Date.now();setTimeout(async()=>{try{const a=Date.now()-o,t=Date.now(),s=await this._config.pc.getStats(),p=this.analyze(s,null,null,null),_=Date.now();p.experimental.time_to_measure_ms=_-t,p.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(p),Pe(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(a){r(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ms.RUNNING||!this._config.pc)return Pe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),r=await this._config.pc.getStats(),o=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return o.experimental.time_to_measure_ms=a-n,this._exporter.addReport(o),Pe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(o),o}catch(n){return Pn(this._moduleName,`got error ${n}`),null}}async start(){Pe(this._moduleName,"starting"),this.state=ms.RUNNING,this._startedTime=this._exporter.start(),Pe(this._moduleName,"started")}async mute(){this.state=ms.MUTED,Pe(this._moduleName,"muted")}async unmute(){this.state=ms.RUNNING,Pe(this._moduleName,"unmuted")}async stop(n){if(Pe(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ms.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Pe(this._moduleName,"stopped")}registerCallback(n,r,o){n in this._callbacks?(this._callbacks[n]={callback:r,context:o},Pe(this._moduleName,`registered callback '${n}'`)):Pn(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Pe(this._moduleName,`unregistered callback '${n}'`)):Pn(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&_u(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&_u(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,Pe(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,r,o,a){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:r,name:o,description:a})}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{Pn(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const o=n.iceConnectionState;o===Kr.CONNECTED||o===Kr.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Kr.DISCONNECTED||o===Kr.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Kr.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const o=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",o,"ICE gathering state")},n.ontrack=o=>{this.addCustomEvent(new Date().toJSON(),"call",`${o.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 o=r[0],{transport:a}=o;if(a){const{iceTransport:t}=a;t&&(t.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class tv{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||OT(),this._moduleName=this._id,Qs(this._moduleName,"probe created"),this._config=n,this._collector=new ev(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,o,a=new Date().toJSON()){this._collector.addCustomEvent(a,r,n,o)}get isRunning(){return this._collector.state===ms.RUNNING}get isIdle(){return this._collector.state===ms.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){ao(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 Ct="engine ";class sv{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Qs(Ct,`configured for probing every ${this._config.refreshEvery}ms`),Qs(Ct,`configured for starting after ${this._config.startAfter}ms`),Qs(Ct,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Pe(Ct,"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 o=bT(n,r,this._config),a=new tv(o);return this._probes.push(a),Pe(Ct,`${this._probes.length} probes registered`),a}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===ms.RUNNING&&n.stop(),this._probes=this._probes.filter(r=>n.id!==r.id)}async start(){const n=()=>{this._probes.forEach(t=>t.start())},r=async()=>Promise.all(this._probes.map(t=>t.takeReferenceStats())),o=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const t=CT(),s=this._probes.filter(p=>p.isRunning);for(const p of s){const _=await p.collectStats();_&&t.probes.push(_),Pe(Ct,`got probe ${p.id}`),await f_(0)}return t.delta_time_to_measure_probes_ms=Zs(t.probes,"experimental","time_to_measure_ms"),t.delta_KBytes_in=Zs(t.probes,"data","delta_KBytes_in"),t.delta_KBytes_out=Zs(t.probes,"data","delta_KBytes_out"),t.delta_kbs_in=Zs(t.probes,"data","delta_kbs_in"),t.delta_kbs_out=Zs(t.probes,"data","delta_kbs_out"),t.total_time_decoded_in=Zs(t.probes,"video","total_time_decoded_in"),t.total_time_encoded_out=Zs(t.probes,"video","total_time_encoded_out"),t};for(Pe(Ct,"starting to collect"),n(),Pe(Ct,"generating reference reports..."),await r(),Pe(Ct,"reference reports generated"),this._startedTime=Date.now();o();)if(Pe(Ct,`wait ${this._config.refreshEvery}ms before collecting`),await f_(this._config.refreshEvery),o()){Pe(Ct,"collecting...");const t=Date.now(),s=await a(),p=Date.now();s.delta_time_consumed_to_measure_ms=p-t,this.fireOnReports(s),Pe(Ct,"collected")}Pe(Ct,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const r=o=>{this._probes.forEach(a=>{a.stop(o)})};Qs(Ct,"stop collecting"),r(n)}registerCallback(n,r,o){n in this._callbacks?(this._callbacks[n]={callback:r,context:o},Pe(Ct,`registered callback '${n}'`)):Pn(Ct,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Pe(this._moduleName,`unregistered callback '${n}'`)):Pn(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&_u(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const nv="interface ";class rv{constructor(n){this._config=wT(n),Qs(nv,`welcome to ${this._config.name} version ${this._config.version}`),mT(this._config.verbose||!1),this._engine=new sv(this._config)}setupLogLevel(n){gT(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 iv(c,n){return Object.keys(c).filter(r=>n.includes(r)).reduce((r,o)=>{const a=o;return{...r,[a]:c[a]}},{})}const lv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class ov{constructor(n){this.intervals={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}start(n,r){n&&n.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(n,r))}stop(n){this.clearVolumeInterval(n)}clearVolumeInterval(n){console.log("clearVolumeInterval",n),clearInterval(this.intervals[n]),delete this.intervals[n]}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{clearInterval(this.intervals[n])}),this.intervals={}}beginCalculation(n,r){this.clearVolumeInterval(r);const o=es.createAnalyser(),a=es.createMediaStreamSource(n),t=es.createScriptProcessor(2048,1,1);o.smoothingTimeConstant=.8,o.fftSize=1024,a.connect(o),o.connect(t),t.connect(es.destination),this.intervals[r]=setInterval(()=>{const s=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(s);let p=0;const _=s.length;for(let g=0;g<_;g++)p+=s[g];const d=p/_;this.onChangeFunction(r,d)},this.emitInterval)}}const fo={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},av=0;class uv{constructor(n){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.context=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new ov({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}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 speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(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(fo.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(fo.SELECTED_OUTPUT_DEVICE)||"default";(await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints)).getTracks().forEach(t=>t.stop());const a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(n),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)})}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})}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,r){if(!/^[A-D0-9]+$/g.test(r))throw new Error("Not allowed character in 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(o=>o.enabled=!n),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:r,automatic:o}){const a=this.extendedCalls[n];a._automaticHold=o??!1,await new Promise(p=>{const _=()=>{p()};r?a.hold({},_):a.unhold({},_)}),this.updateCall(a);const s=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(r?n!==p._id:!0));s.length>1&&await this.doConference(s)}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===av).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",o=>{this.triggerAddStream(o,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]=e_(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const o={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...o}},this.context.emit("updateRoom",{room:o,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]:e_(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}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const o={...{...this.callStatus[n.callId]}};n.isMoving!==void 0&&(o.isMoving=n.isMoving),n.isTransferring!==void 0&&(o.isTransferring=n.isTransferring),n.isMerging!==void 0&&(o.isMerging=n.isMerging),this.callStatus={...this.callStatus,[n.callId]:{...o}},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})}getActiveStream(){const n=s_(this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(r=>r.enabled=!this.isMuted),this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:o})=>o===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async o=>{const a=this.getActiveStream();o.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(o)}):await this.doConference(r)}setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===n))return;this.setSelectedOutputDevice(n);const r=Object.values(this.extendedCalls);if(r.length===0)return;const o=r.filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?r.forEach(a=>{var t;(t=a.audioTag)==null||t.setSinkId(n),this.updateCall(a)}):await this.doConference(o)}removeRoom(n){const r={...this.activeRooms},o={...r[n]};delete r[n],this.activeRooms={...r},this.context.emit("removeRoom",{room:o,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 roomReconfigure(n){if(n===void 0)return;const r=Object.values(this.extendedCalls).filter(o=>o.roomId===n);if(this.currentActiveRoomId===n?r.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):r.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),r.length===0)this.deleteRoomIfEmpty(n);else if(r.length===1&&this.currentActiveRoomId!==n)r[0].isOnHold().local||await this.holdCall(r[0].id,!0);else if(r.length===1&&this.currentActiveRoomId===n){if(r[0].isOnHold().local&&r[0]._automaticHold&&await this.unholdCall(r[0].id),r[0].connection&&r[0].connection.getSenders()[0]){const o=this.getActiveStream();await r[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(r[0])}}else r.length>1&&await this.doConference(r)}async doConference(n){await r_.forEach(n,async o=>{o._localHold&&await this.unholdCall(o._id)});const r=[];n.forEach(o=>{o!=null&&o.connection.getReceivers().forEach(a=>{r.push(a.track)})}),await r_.forEach(n,async o=>{if(o==null)return;const a=new MediaStream,t=es.createMediaStreamDestination();if(o.connection.getReceivers().forEach(s=>{r.forEach(p=>{a.addTrack(s.track),s.track.id!==p.id&&es.createMediaStreamSource(new MediaStream([p])).connect(t)})}),n[0].roomId===this.currentActiveRoomId){const s=this.getActiveStream();es.createMediaStreamSource(s).connect(t)}o.connection.getSenders()[0]&&(await o.connection.getSenders()[0].replaceTrack(t.stream.getTracks()[0]),this.muteReconfigure(o))})}processCallerMute(n,r){const o=this.extendedCalls[n];o&&o.connection.getReceivers().length&&(o.localMuted=r,o.connection.getReceivers().forEach(a=>{a.track.enabled=!r}),this.updateCall(o))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const r=this.extendedCalls[n];r._status!==8&&r.terminate()}transferCall(n,r){if(r.toString().length===0)return new Error("Target must be passed");const o=this.extendedCalls[n];if(!o._is_confirmed&&!o._is_canceled){const a=`sip:${r}@${this.context.sipDomain}`;o.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:n,isTransferring:!0}),o.refer(`sip:${r}@${this.context.sipDomain}`),this.updateCall(o)}mergeCall(n){const r=Object.values(this.extendedCalls).filter(t=>t.roomId===n);if(r.length!==2)return;const o=r[0],a=r[1];!o||!a||(this.updateCallStatus({callId:o._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o))}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}startCallTimer(n){this.removeTimeInterval(n);const r={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const o=setInterval(()=>{const a={...this.callTime[n]},t=dT(a);this.setCallTime({callId:n,...t})},1e3);this.setTimeInterval(n,o)}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 d,g;const r=n.session;if(this.getActiveCalls[r.id]!==void 0)return;const a=this.getNewRoomId(),t={started:new Date,incomingInProgress:!1,roomId:a};r.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(d=r._remote_identity)==null?void 0:d._uri)==null?void 0:g._user),t.incomingInProgress=!0,this.context.subscribe(ts.CALL_CONFIRMED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(r.id))}),this.context.subscribe(ts.CALL_FAILED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):r.direction==="outgoing"&&(r.once("confirmed",()=>{this.startCallTimer(r.id)}),this.startCallTimer(r.id));const s=r,p=this.hasAutoAnswerHeaders(n),_=s.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);s.roomId=a,s.localMuted=!1,s.autoAnswer=_,_?this.addCall(s,!1):this.addCall(s),this.addCallStatus(r.id),this.addRoom(t),_&&this.answerCall(s._id)}removeCall(n){const r={...this.activeCalls};delete r[n],this.activeCalls={...r};const o={...this.extendedCalls};delete o[n],this.extendedCalls={...o},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const r=this.extendedCalls[n._id];this.stopVUMeter("origin"),r.connection.getSenders().forEach(a=>{a.track.stop()});const o=r.roomId;this.removeCall(n._id),this.roomReconfigure(o)}async newRTCSessionCallback(n){const r=n.session;if(this.isDND){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(r.on("ended",o=>{var t,s;this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(s=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:ts.CALL_ENDED,session:r,event:o});const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),r.on("progress",o=>{var a,t;this.context.logger.log("Session in progress for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:ts.CALL_PROGRESS,session:r,event:o})}),r.on("failed",o=>{var t,s;this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(s=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:ts.CALL_FAILED,session:r,event:o}),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),r.on("confirmed",o=>{var a,t;this.context.logger.log("Session confirmed for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:ts.CALL_CONFIRMED,session:r,event:o}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(n),r.direction==="outgoing"){const o=this.getActiveCalls[r.id].roomId;this.setActiveRoom(o)}}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(fo.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(fo.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 rv(this.metricConfig),o=r.createProbe(n.connection,{cid:n._id}),a=[];let t;o.onreport=s=>{Object.entries(s.audio).forEach(([d,g])=>{g.direction==="inbound"&&!a.includes(d)&&(a.push(d),t=d)});const p=s.audio[t],_=iv(p,lv);_.callId=n._id,this.setCallMetrics(r)},this.context.subscribe(ts.CALL_ENDED,s=>{s._id===n._id&&r.stopAllProbes()}),r.startAllProbes()}setupVUMeter(n,r){this.VUMeter.start(n,r)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){const n=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(r=>r.stop()),this.initialStreamValue=null),this.initialStreamValue=n}async triggerAddStream(n,r){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const o=s_(this.initialStreamValue,this.microphoneInputLevel*2),a=this.isMuted||this.muteWhenJoin;o.getTracks().forEach(s=>s.enabled=!a),this.setActiveStream(o),await r.connection.getSenders()[0].replaceTrack(o.getTracks()[0]);const t=new MediaStream([n.track]);Zg(t,r,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(t,r._id),this.getCallQuality(r),this.updateCall(r)}initCall(n,r){if(this.checkInitialized(),n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=o.id,r&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),o.connection.addEventListener("track",a=>{this.triggerAddStream(a,o)})}async processRoomChange({callId:n,roomId:r}){const o=this.extendedCalls[n].roomId;this.extendedCalls[n].roomId=r;const a=this.extendedCalls[n];return this.updateCall(a),await this.setActiveRoom(r),Promise.all([this.roomReconfigure(o),this.roomReconfigure(r)]).then(()=>{this.deleteRoomIfEmpty(o),this.deleteRoomIfEmpty(r)})}}class cv{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n){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}`,this.sipOptions),console.log("video call")}}class fv{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}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]=t_(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:t_(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,r){const o=this.msrpHistory[r.id]||[];o.push(n),this.msrpHistory={...this.msrpHistory,[r.id]:[...o]},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 o=n;this.addMMSRPSession(o)}triggerMSRPListener({listenerType:n,session:r,event:o}){const a=this.context.listenersList[n];!a||!a.length||a.forEach(t=>{t(r,o)})}removeMMSRPSession(n){const r={...this.activeMessages};delete r[n],this.activeMessages={...r};const o={...this.extendedMessages};delete o[n],this.extendedMessages={...o},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){const r=n.session;r.on("ended",o=>{this.triggerMSRPListener({listenerType:ts.CALL_ENDED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("failed",o=>{this.triggerMSRPListener({listenerType:ts.CALL_FAILED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("confirmed",o=>{this.triggerMSRPListener({listenerType:ts.CALL_CONFIRMED,session:r,event:o}),this.updateMSRPSession(r)}),r.on("newMessage",o=>{this.addMSRPMessage(o,r)}),this.addMessageSession(r)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,r,o){if(n.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(n,o);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,r){const o=this.extendedMessages[n];if(!o)throw new Error(`MSRP session with id ${n} doesn't exist!`);o.sendMSRP(r)}}const hu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class _v extends Jg{constructor(n,r){if(!n.modules.length)throw new Error("options.modules should include at least 1 module");const o={...n.configuration,sockets:n.socketInterfaces.map(a=>new hT.WebSocketInterface(a))};super(o),this.initialized=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],n.pnExtraHeaders&&Object.keys(n.pnExtraHeaders).length&&this.registrator().setExtraContactParams(n.pnExtraHeaders),this.options=n,this.modules=n.modules,r&&eT(r)&&(this.logger=r)}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}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(hu.AUDIO)&&(this.audio=new uv(this)),this.modules.includes(hu.MSRP)&&(this.msrp=new fv(this)),this.modules.includes(hu.VIDEO)&&(this.video=new cv(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.isReconnecting=!1}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.isReconnecting=!0,this.stop(),this.setInitialized(!1),setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}subscribe(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:o}){const a=this.listenersList[n];!a||!a.length||a.forEach(t=>{t(r,o)})}setInitialized(n){this.initialized=n,this.emit("ready",n)}}return _v}();
|