@vkontakte/calls-sdk 2.5.3-dev.d006735.0 → 2.5.3-dev.dbb762f.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/calls-sdk.esm.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
- * @vkontakte/calls-sdk v2.5.3-dev.d006735.0
3
- * Tue, 24 May 2022 20:25:12 GMT
2
+ * @vkontakte/calls-sdk v2.5.3-dev.dbb762f.0
3
+ * Tue, 05 Jul 2022 07:30:23 GMT
4
4
  * https://st.mycdn.me/static/callssdk/2-5-3/doc/
5
5
  */
6
6
 
7
- var Xr=Object.defineProperty;var Ni=Object.getOwnPropertySymbols;var Zr=Object.prototype.hasOwnProperty,ea=Object.prototype.propertyIsEnumerable;var Li=Math.pow,Ui=(a,e,t)=>e in a?Xr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,Bi=(a,e)=>{for(var t in e||(e={}))Zr.call(e,t)&&Ui(a,t,e[t]);if(Ni)for(var t of Ni(e))ea.call(e,t)&&Ui(a,t,e[t]);return a};var c=(a,e,t)=>new Promise((i,r)=>{var n=l=>{try{p(t.next(l))}catch(h){r(h)}},s=l=>{try{p(t.throw(l))}catch(h){r(h)}},p=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,s);p((t=t.apply(a,e)).next())});import zr from"webrtc-adapter";var dt=class{createJoinLink(e){return c(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return c(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return c(this,null,function*(){return""})}log(e){}prepareUserIds(e){return c(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return c(this,null,function*(){})}cleanup(){}};var pt=class{log(e,t,i=!1){}destroy(){}};var z=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var lt=class extends z{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var Vi=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(Vi||{}),Le=Vi;var Fi=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(Fi||{}),xe=Fi;var Hi=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(Hi||{}),zt=Hi;var Gi=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(Gi||{}),Wi=Gi;var ji=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(ji||{}),Qt=ji;function Ki(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function $i(a,e){let t=new Set(a);for(let[i,r]of Object.entries(e))r?t.add(i):t.delete(i);return Array.from(t)}var qi=(N=>(N.CAMERA_PERMISSION="camera",N.MIC_PERMISSION="mic",N.CAMERA_ACCESS="cameralock",N.MIC_ACCESS="miclock",N.MIC_NOT_FOUND="nomic",N.SCREEN_PERMISSION="screenpermission",N.SCREEN_ACCESS="screenlock",N.CONNECTION="connection",N.NETWORK="network",N.UNKNOWN="unknown",N.UNSUPPORTED="unsupported",N.SIGNALING_FAILED="signalingfailed",N.API="api",N.AUTH="auth",N))(qi||{}),Z=qi;var Ji=($=>($.CANCELED="CANCELED",$.REJECTED="REJECTED",$.REMOVED="REMOVED",$.HUNGUP="HUNGUP",$.MISSED="MISSED",$.BUSY="BUSY",$.FAILED="FAILED",$.NETWORK_ERROR="NETWORK_ERROR",$.KILLED="KILLED",$.BANNED="BANNED",$.HAS_ACTIVE_CALL="HAS_ACTIVE_CALL",$.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",$.NOT_FRIENDS="NOT_FRIENDS",$.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",$.UNKNOWN_ERROR="UNKNOWN_ERROR",$.UNSUPPORTED="UNSUPPORTED",$.OLD_VERSION="OLD_VERSION",$.SERVICE_DISABLED="SERVICE_DISABLED",$.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",$.SOCKET_CLOSED="SOCKET_CLOSED",$.ENDED="ENDED",$))(Ji||{}),M=Ji;var Yi=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(Yi||{}),ce=Yi;var zi=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(zi||{}),Ue=zi;var Qi=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(Qi||{}),j=Qi;var Xi=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(Xi||{}),Ne=Xi;var Zi=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(Zi||{}),_e=Zi;var er=(b=>(b.TRANSMITTED_DATA="transmitted-data",b.ACCEPTED_CALL="accepted-call",b.HUNGUP="hungup",b.PARTICIPANT_ADDED="participant-added",b.PARTICIPANT_JOINED="participant-joined",b.CLOSED_CONVERSATION="closed-conversation",b.MEDIA_SETTINGS_CHANGED="media-settings-changed",b.PARTICIPANT_STATE_CHANGED="participant-state-changed",b.RATE_CALL_DATA="rate-call-data",b.FEATURE_SET_CHANGED="feature-set-changed",b.TOPOLOGY_CHANGED="topology-changed",b.PRODUCER_UPDATED="producer-updated",b.CONSUMER_ANSWERED="consumer-answered",b.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",b.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",b.SETTINGS_UPDATE="settings-update",b.VIDEO_QUALITY_UPDATE="video-quality-update",b.REGISTERED_PEER="registered-peer",b.SWITCH_MICRO="switch-micro",b.RECORD_STARTED="record-started",b.RECORD_STOPPED="record-stopped",b.REALLOC_CON="realloc-con",b.AUDIO_ACTIVITY="audio-activity",b.SPEAKER_CHANGED="speaker-changed",b.STALLED_ACTIVITY="stalled-activity",b.CHAT_MESSAGE="chat-message",b.CUSTOM_DATA="custom-data",b.ROLES_CHANGED="roles-changed",b.MUTE_PARTICIPANT="mute-participant",b.PIN_PARTICIPANT="pin-participant",b.OPTIONS_CHANGED="options-changed",b.NETWORK_STATUS="network-status",b.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",b.PROMOTE_PARTICIPANT="promote-participant",b.CHAT_ROOM_UPDATED="chat-room-updated",b.PROMOTION_APPROVED="promotion-approved",b.JOIN_LINK_CHANGED="join-link-changed",b))(er||{}),A=er;var tr=(u=>(u.ERROR="callError",u.DEVICES="callDevices",u.CALL_SPEC_ERROR="callSpecError",u.ICE_CONNECTION_STATE="callIceConnectionState",u.ICE_CONNECTION_TYPE="callIceConnectionType",u.ICE_RESTART="callIceRestart",u.PUSH="callPush",u.OUTGOING_CALL="callStart",u.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",u.JOIN_CONVERSATION="callJoinConversation",u.ACCEPTED_OUTGOING="callAcceptedOutgoing",u.ACCEPT_INCOMING="callAcceptIncoming",u.DECLINE_INCOMING="callDeclineIncoming",u.ACCEPT_CONCURRENT="callAcceptConcurrent",u.HANGUP="callHangup",u.MEDIA_STATUS="callMediaStatus",u.DEVICE_CHANGED="callDeviceChanged",u.SOCKET_ACTION="callSocketAction",u.ADD_PARTICIPANT="callAddParticipant",u.REMOVE_PARTICIPANT="callRemoveParticipant",u.POOR_CONNECTION="callPoorConnection",u.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",u.RELAY_POLICY="callForceRelay",u.PAT_ALLOCATED="patAllocate",u.PAT_DEALLOCATED="patDeallocate",u.PAT_ERROR="patError",u.PAT_WAITING_TIME_ERROR="patWaitingTimeError",u.PAT_OUTDATED_RESPONSE="patOutdatedResponse",u))(tr||{}),g=tr;var ir=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(ir||{}),be=ir;var rr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(rr||{}),ar=rr;function nr(a){switch(a){case 1:return"no-available-tracks";default:return"unknown-error"}}var sr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(sr||{}),ze=sr;function ut(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var or=(t=>(t.USER="USER",t.GROUP="GROUP",t))(or||{}),Q=or;var Xt=class{constructor(){this._items=[]}get length(){return this._items.length}push(e){this._items.push(e)}shift(){return this._items.shift()||null}bisect(){let e=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(e)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(e,t)=>t instanceof Error?String(t):t):""}};var cr=2*1024*1024,ta=512*1024,mt=100*1024,ia=5,Zt="_okcls_logs_session_",ra=3e4,dr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=cr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(Zt)!==0)continue;let i=e.getItem(t);if(!i){ur(t);continue}let r=lr(i);this.add(t,r)}}catch(e){console.error("Storage is blocked",e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(mt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(Zt,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(ur(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>cr||this.length>ia-1||this.size+e>this.available);)this.deleteOldestItem()}};function pr(){return`${Zt}${Date.now()}`}function lr(a){return new Blob([a]).size}function ur(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function ei(){let a=Ge.toString();if(!Se.available||!a)return;let e=lr(a);Se.cleanup(e);try{window.localStorage.setItem(bt,a)}catch(t){if(console.warn("Failed to write log to storage",t),Se.storageSize=Se.size+e,Se.cleanup(mt+e),Se.available>=mt+e){ei();return}if(e>mt){Ge.bisect(),ei();return}Se.storageSize=0;return}e>ta&&(Se.add(bt,e),bt=pr(),Ge.clear(),Se.cleanup(mt))}function ti(){!Se.available||!Ge.length||ei()}function aa(a=!1){let e=[];try{let r=window.localStorage;for(let s of Se.items){let p=r.getItem(s.key);e.push(p)}let n=Ge.toString();n&&e.push(n)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(a)return t;let i=`logs_${Date.now()}.json`;return na(t,i),i}function na(a,e){let t=document.createElement("a"),i=new Blob([a],{type:"text/json"});t.href=URL.createObjectURL(i),t.download=e,t.click()}function mr(a,e){!Se.available||(Ge.push({t:Date.now(),l:a,d:e}),ri||(ri=window.setTimeout(()=>{ri=null,ti()},ra)))}function ii(){Se||(Se=new dr,Ge=new Xt,bt=pr(),window.addEventListener("beforeunload",ti))}var Se,Ge,bt,ri=null;window.__VKCallsSDKLogs__=(a=!1)=>(Se||ii(),ti(),aa(a));import hr from"@vkontakte/libvpx";var ge=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(ge||{});var m=class extends pt{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={};typeof t!="undefined"&&(r.param=t),this._logInternal(e,r,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){m._instance||(m._instance=new m(e,t))}static log(e,t,i=!1){m._instance&&m._instance.log(e,t,i)}static logCustom(e,t,i=!1){m._instance&&m._instance.logCustom(e,t,i)}static destroy(){m._instance&&m._instance.destroy(),m._instance=null}};var Oe=class{constructor(){this._worker=null}_createWorker(s,p){return c(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((l,h)=>{let R=i.join(","),y=new Blob([e,`exports.default(${R});`],{type:"application/javascript; charset=utf-8"}),W=window.URL.createObjectURL(y);this._worker=new Worker(W),this._worker.onmessage=K=>{switch(K.data.type){case ge.READY:l();break;case ge.ERROR:h(K.data.error);break;case ge.FRAME:t(K.data);break;case ge.DEBUG:o.debug(K.data.message);break;case ge.LOG_ERROR:m.log(g.ERROR,K.data.message);break}},this._sendToWorker(ge.INIT,r,n)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var Qe=class extends Oe{init(e){return c(this,null,function*(){o.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var y=Object.defineProperty;var E=a=>y(a,"__esModule",{value:!0});var M=(a,p)=>{E(a);for(var e in p)y(a,e,{get:p[e],enumerable:!0})};var D={};M(D,{default:()=>V});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var V=(a,p)=>{let e=null,n=null,g=!0;function b(){return a({locateFile:p}).then(r=>n=r)}function s(r,m,l,R,x){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(x),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let d=e.getImageBuffer();if(!d){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let c=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(d.byteLength);if(i.set(d),R){let o=new ImageData(i,c,f);createImageBitmap(o,0,0,c,f).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:i.buffer,width:c,height:f},[i.buffer])}b().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return D;})();\n',t=>{if(t.error)o.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i)}else e(t.data)},[hr,hr.getUrl])})}decodeFrame(e,t,i,r){let n="ImageBitmap"in window;this._sendToWorker(ge.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:n,debug:o.enabled()},[t.buffer])}destroy(){this._removeWorker(),o.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var We=class extends Oe{init(e){return c(this,null,function*(){o.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var l=Object.defineProperty;var f=e=>l(e,"__esModule",{value:!0});var E=(e,d)=>{f(e);for(var a in d)l(e,a,{get:d[a],enumerable:!0})};var y={};E(y,{default:()=>g});var c=(a=>(a.VP9="vp09.00.50.08",a.VP8="vp8",a))(c||{}),o=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(o||{});var g=()=>{let e=null,d=!0;function a(){self.postMessage({type:o.READY})}function p(r,m,t,n=!1){if(!e||d!==t){if(!n){self.postMessage({type:o.DEBUG,message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}d=t,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${t?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${t?"VP9":"VP8"}`}),e=new VideoDecoder({output:s=>{("createImageBitmap"in s?s.createImageBitmap():createImageBitmap(s)).then(i=>{self.postMessage({type:o.FRAME,data:i}),i.close()}).finally(()=>s.close())},error:s=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:t?c.VP9:c.VP8})}let u=new EncodedVideoChunk({type:n?"key":"delta",timestamp:r,data:m});e.decode(u)}self.onmessage=r=>{switch(r.data.type){case o.INIT:a();break;case o.FRAME:p(r.data.timestamp,r.data.data,r.data.isVP9,r.data.keyFrame);break}}};return y;})();\n',t=>{t.error?o.warn("WebCodecsDecoder",t.error):e(t.data)})})}decodeFrame(e,t,i,r=!1){this._sendToWorker(ge.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),o.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window&&"ImageBitmap"in window&&"createImageBitmap"in window}};var ai="_okcls_",Xe=(()=>{try{let a=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(a,a),t=e.getItem(a)===a,e.removeItem(a),t?e:null}catch(a){return null}})();function oa(a){let e=Xe?Xe.getItem(ai+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function ca(a,e){try{Xe&&Xe.setItem(ai+a,JSON.stringify(e))}catch(t){}}function da(a){Xe&&Xe.removeItem(ai+a)}var ni;(i=>{function a(r){return oa(r)||null}i.get=a;function e(r,n){ca(r,n)}i.set=e;function t(r){da(r)}i.remove=t})(ni||(ni={}));var Be=ni;import ht from"big-integer";function _r(a,e){if(a.isAudioEnabled!==e.isAudioEnabled||a.isVideoEnabled!==e.isVideoEnabled||a.isScreenSharingEnabled!==e.isScreenSharingEnabled||a.videoStreams.length!==e.videoStreams.length)return!1;for(let t of a.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function fe(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}var gr=a=>a.stop(),fr=a=>a.getTracks().forEach(gr),si=a=>a.getVideoTracks().forEach(gr),Sr=a=>a.getVideoTracks()[0].clone();var O=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(M).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,O)}};var ve=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(ve||{}),le=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(le||{}),oi=class extends z{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=fe();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return c(this,arguments,function*(e=[ce.AUDIO],t=!0){if(this._stream)return;let i=e.includes(ce.VIDEO),r=e.includes(ce.AUDIO);if(!C.isBrowserSupported())throw new O(Z.UNSUPPORTED);try{this._stream=yield C.getUserMedia(i,r,t),this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(n=>n.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=r&&this._stream.getAudioTracks().filter(n=>n.enabled).length>0||!1}catch(n){throw new O(n)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t,i,r){let n=this.getStream(),s=this._getSendAudioTrack(),p=this.getSendVideoTrack(i);if(!n||!s&&!p&&!t)throw new Error("No local stream found");if(s&&!t){if(r){let{codecs:l}=RTCRtpSender.getCapabilities("audio"),h="audio/red",R=48e3,y=l.findIndex(W=>W.mimeType===h&&W.clockRate===R);y>=0&&(l.slice(y,1),l.unshift(l[y]),e.getTransceivers().forEach(W=>W.setCodecPreferences(l)))}e.addTrack(s,n)}p&&!t&&e.addTrack(p,n)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return c(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return c(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=E.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);this._onDeviceChange=()=>c(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),s=n&&n.deviceId,p=this._stream.getVideoTracks()[0],l=p&&p.enabled&&p.getSettings(),h=l&&l.deviceId;if(!s&&!h)return;let R=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!R.find(y=>y.deviceId===s)),!t&&h&&(t=!R.find(y=>y.deviceId===h)),i()}),navigator.mediaDevices.addEventListener("devicechange",this._onDeviceChange)}_destroyDeviceChangeListener(){this._onDeviceChange&&navigator.mediaDevices.removeEventListener("devicechange",this._onDeviceChange)}_changeVideoInput(e=null){return c(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield C.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{d.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),n=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),m.log(g.DEVICE_CHANGED,t),o.log("Video stream changed"),yield this._replaceLocalTrack(n),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(g.ERROR,"change_video"),o.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=Sr(e)),t=this._trackVideoStreamBackup.clone(),si(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),si(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return c(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return c(this,null,function*(){try{if(e=e||(yield C.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),m.log(g.DEVICE_CHANGED,"audio"),o.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(g.ERROR,"change_audio"),o.error("Microphone change failed",t),t}})}_changeScreen(e){return c(this,null,function*(){try{if(e=e||(yield C.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=d.consumerScreenTrack?t:yield this._videoEffect(null,t);m.log(g.DEVICE_CHANGED,"screen"),o.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,d.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=d.consumerScreenDataChannel?C.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(g.ERROR,"screen"),o.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return c(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,n;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(n=this._stream)==null||n.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return c(this,null,function*(){if(!d.videoEffects)return t;try{return m.log(g.DEVICE_CHANGED,`effect_${e}`),d.videoEffects.setEffect(e,t)}catch(i){return o.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){this._destroyDeviceChangeListener(),d.videoEffects&&(this._effect=null,d.videoEffects.destroy()),this._stream&&(fr(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return c(this,null,function*(){return e?this._changeScreen():d.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return c(this,null,function*(){if(!this._stream)return;d.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield C.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=C.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return c(this,null,function*(){if(!this._stream)return;let t;e?t=(yield C.getUserAudio()).getAudioTracks()[0]:t=C.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return c(this,null,function*(){if(!d.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return c(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks()[0];if(!e)throw new Error("Local audio track not found");if(!!e.enabled)return e.applyConstraints({noiseSuppression:d.noiseSuppression})})}videoEffect(e){return c(this,null,function*(){if(!d.videoEffects)throw new Error("Video Effects library is not set");if(!d.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var Ze=":",Mt="d",ci;(xi=>{function a(u,I,D,F,x=!1,q=!1){let _=/[\r\n]+/,G=`\r
8
- `;if(!I&&!D&&!F&&!q)return x?te(u.split(_)).join(G):u;function te(ne){let v=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],P="a=rtcp-fb:111",V=ne.findIndex(J=>J.startsWith(P));return~V&&(ne[V]=ne[V]+G+v.join(G)),ne}function b(ne,v,P){let V=ne.split(" "),J=V.slice(0,3),ee;for(ee=3;ee<V.length;ee++)P.includes(V[ee])&&J.push(V[ee]);for(ee=3;ee<V.length;ee++)!P.includes(V[ee])&&!v.includes(V[ee])&&J.push(V[ee]);return J.join(" ")}function ae(ne,v){let P=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),V,J=[];for(V=0;V<ne.length;++V){let ee=ne[V].match(P);ee&&ee.length===3&&ee[2]===v&&J.push(ee[1])}return J}function pe(ne,v,P,V){let J,ee="m="+v;for(J=0;J<ne.length;++J)if(ne[J].startsWith(ee)){ne[J]=b(ne[J],P,V);break}}let Ce=[],ie=u.split(_);(D||I)&&(Ce=ae(ie,"H264"));let Ae=[];F&&(Ae=ae(ie,"VP9"));let Pt=[];if(q&&(Pt=ae(ie,"red")),D){let ne=Ce.slice(0),v=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),P;for(P=0;P<ie.length;++P){let J=ie[P].match(v);J&&J.length===3&&ne.includes(J[2])&&ne.push(J[1])}let V=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(P=ie.length;P--;){let J=ie[P].match(V);J&&J.length===3&&ne.includes(J[2])&&ie.splice(P,1)}pe(ie,"video",ne,[])}else I&&pe(ie,"video",[],Ce);return F&&pe(ie,"video",[],Ae),q&&Pt.length>0&&pe(ie,"audio",[],Pt),x&&te(ie),ie.join(G)}xi.patchSDP=a;function e(u){return u?`${u.type||"WEB_SOCKET"}_${u.id}`:"_"}xi.getPeerIdString=e;function t(u,I){return u&&u.id===I.id&&(u.type||"WEB_SOCKET")===(I.type||"WEB_SOCKET")}xi.comparePeerId=t;function i(u){return c(this,null,function*(){return!u||!u.getStats?Promise.resolve(null):u.getStats(null).then(I=>{let D=null,F=null;if(I.forEach(x=>{x.type==="transport"&&x.selectedCandidatePairId?F=I.get(x.selectedCandidatePairId):x.type==="candidate-pair"&&x.state==="succeeded"&&!F&&(!x.hasOwnProperty("selected")||x.selected)&&(F=x)}),F&&F.localCandidateId){let x=I.get(F.localCandidateId);x&&(D={type:x.candidateType,ip:x.ip||x.ipAddress,port:x.port||x.portNumber})}return D}).catch(()=>null)})}xi.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function s(u,I){let D=String(u);return n.test(D)?(o.warn(`Already composite id [${u}] type supplied [${I}]`),D):I===Q.GROUP?"g"+D:I===Q.USER?"u"+D:(o.warn(`Unknown type [${I}] for id [${u}]`),D.match(r)?"u"+D:D)}xi.composeUserId=s;function p(u,I,D){let F=s(u,I);return l(F,D)}xi.composeParticipantId=p;function l(u,I){return I?u+Ze+Mt+I:u}xi.compose=l;function h(u){return p(u.id,u.idType||Q.USER,u.deviceIdx||0)}xi.composeId=h;function R(u){return u.participant?h(u.participant):p(u.participantId,u.participantType||Q.USER,u.deviceIdx||0)}xi.composeMessageId=R;function y(u){let I=String(u),D=I.match(n);return D?{id:Number(D[2]),type:D[1]==="g"?Q.GROUP:Q.USER}:(o.warn(`Unsupported compositeId [${u}]`),{id:Number(I),type:Q.USER})}xi.decomposeId=y;function W(u){let I=u.split(Ze+Mt);return{compositeUserId:I[0],deviceIdx:I.length>1?parseInt(I[1],10):0}}xi.decomposeParticipantId=W;function K(){var _,G;let u=(G=(_=window.crypto)==null?void 0:_.randomUUID)==null?void 0:G.call(_);if(u)return u;let I="0123456789abcdefghijklmnopqrstuvwxyz".split(""),D=new Array(36),F=0,x,q;for(q=0;q<36;q++)q===8||q===13||q===18||q===23?D[q]="-":q===14?D[q]="4":(F<=2&&(F=33554432+Math.random()*16777216|0),x=F&15,F=F>>4,D[q]=I[q===19?x&3|8:x]);return D.join("")}xi.uuid=K;function N(u,I){let D;function F(){let x=this,q=arguments;D&&window.clearTimeout(D),D=window.setTimeout(()=>{u.apply(x,q)},I)}return F}xi.throttle=N;function he(u){let I="",D=u.split(`
9
- `);for(let _ of D)if(_.startsWith("a=fingerprint")){let G=_.split(" ");if(G.length===2){I=G[1];break}}if(!I)return ht.minusOne;let F=I.split(":"),x=ht.zero;for(let _=Math.min(7,F.length-1);_>=0;_--){let G=ht(F[_],16);x=x.shiftLeft(8).or(G)}return((_,G)=>{let te=G.value;if(typeof te=="bigint")return ht(BigInt.asIntN(_,te));let b=ht.one.shiftLeft(_),ae=G.and(b.subtract(1));return ae.greaterOrEquals(b.subtract(ae))?ae.subtract(b):ae})(64,x)}xi.sdpFingerprint=he;function De(u){return c(this,null,function*(){return new Promise(I=>window.setTimeout(I,u))})}xi.delay=De;function de(u,I,D){let F=[];return u.getSenders().forEach(x=>He(I,x,x.track,D,F)),F}xi.applySettings=de;function He(u,I,D,F,x){if(u&&D&&D.kind===le.video){let q=D.getSettings();if(q){let _=u.maxBitrateK?u.maxBitrateK*1024:null,G=q.width,te=q.height,b=G&&te&&u.maxDimension?Math.max(1,Math.max(G,te)/u.maxDimension):null,ae=u.maxFramerate?u.maxFramerate:null,pe=u.degradationPreference?u.degradationPreference:"balanced",Ce=F[D.id];if(Ce&&Ce.bitrate===_&&Ce.scaleResolutionDownBy===b&&Ce.maxFramerate===ae&&Ce.degradationPreference===pe){x[D.id]=Ce;return}x[D.id]={bitrate:_,scaleResolutionDownBy:b,maxFramerate:ae,degradationPreference:pe};let ie=I.getParameters();ie.encodings||(ie.encodings=[{}]),ie.encodings.forEach(Ae=>{_?Ae.maxBitrate=_:delete Ae.maxBitrate,b?Ae.scaleResolutionDownBy=b:delete Ae.scaleResolutionDownBy,ae?Ae.maxFramerate=ae:delete Ae.maxFramerate}),ie.degradationPreference=pe,I.setParameters(ie)}}}xi.applyVideoTrackSettings=He;function oe(u,I){Array.isArray(I)||(I=[I]);for(let D of I)if(u.includes(D))return!0;return!1}xi.includesOneOf=oe;function Pe(u){var I;return Object.entries(((I=u.participantState)==null?void 0:I.state)||{}).reduce((D,[F,x])=>(u.participantState&&(D[F]={ts:u.participantState.stateUpdateTs[F],state:x}),D),{})}xi.mapParticipantState=Pe;function $(u){return Object.entries(u).reduce((I,[D,{state:F}])=>(I[D]=F,I),{})}xi.mapLegacyParticipantState=$;function ct(u){return u.map(I=>{let D={uid:I.externalId,mediaSettings:I.mediaSettings,status:I.status,muteStates:I.muteStates,unmuteOptions:I.unmuteOptions};return d.participantStateMapped&&(D.participantState=I.participantState),D})}xi.mapSharedParticipants=ct;function Ai(u,I){let D=Object.keys(u),F=Object.keys(I);if(D.length!==F.length)return!1;for(let x of D)if(!F.hasOwnProperty(x)||u[x].state!==I[x].state||u[x].ts!==I[x].ts)return!1;return!0}xi.isEqualParticipantState=Ai;function Oi(u,I){let D=Object.keys(u),F=Object.keys(I);if(D.length!==F.length)return!1;for(let x of D)if(!I.hasOwnProperty(x)||u[x]!==I[x])return!1;return!0}xi.isObjectsEquals=Oi;function ki(u,I){if(u.length!==I.length)return!1;for(let D of u)if(I.indexOf(D)<0)return!1;return!0}xi.isArraysEquals=ki;function wi(u){return!Object.keys(u).length}xi.isEmptyObject=wi})(ci||(ci={}));var E=ci;var je=null,di=null,Dt=[],At=[],pi=[],_t=null,gt=null,li=null,ui=!1,mi=!1,Ot,et,kt,vr=!1,Er=!1,hi=null,_i="",wt=[],gi=null,Tr=navigator.appVersion,pa=navigator.appName,Ee=navigator.userAgent,Ir=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(Ir||{}),ft=class{constructor(e,t=!1,i=d.videoMaxWidth,r=d.videoMaxHeight){let n=!1;if(e){n={noiseSuppression:d.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let p;gt&&(p=gt.deviceId),typeof e=="string"&&(p=e),p&&(n.deviceId={ideal:p})}let s=!1;if(t){s={width:{min:d.videoMinWidth,max:i,ideal:i},height:{min:d.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:d.videoAspectRatio},frameRate:{ideal:d.videoFrameRate}};let p;_t&&(p=_t.deviceId),typeof t=="string"&&(p=t),p&&(s.deviceId={ideal:p}),d.videoFacingMode&&(s.facingMode={ideal:d.videoFacingMode})}this.audio=n,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},Cr=class extends ft{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=d.screenFrameRate}};function la(){return c(this,null,function*(){je=null,yield xt()})}function ua(){je=null,xt().then(()=>T.onDeviceChange())}function xt(){return c(this,null,function*(){return je||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!di&&navigator.mediaDevices.addEventListener&&(di=E.throttle(ua,1e3),navigator.mediaDevices.addEventListener("devicechange",di)),je=navigator.mediaDevices.enumerateDevices().then(a=>{Dt=a.filter(r=>r.kind==="videoinput"?(r.label&&(ui=!0),!0):!1),At=a.filter(r=>r.kind==="audioinput"?(r.label?mi=!0:Ke.isMobile()&&Ke.browserName()==="Firefox"&&(mi=ui),!0):!1),pi=a.filter(r=>r.kind==="audiooutput");let e=Be.get("videoinput"),t=Be.get("audioinput"),i=Be.get("audiooutput");return _t=Dt.find(r=>r.deviceId===e)||null,gt=At.find(r=>r.deviceId===t)||null,li=pi.find(r=>r.deviceId===i)||null,je=Promise.resolve(a),a}).catch(()=>(je=null,[]))))})}function ma(){return c(this,null,function*(){return Ke.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(vr=!0),/^a=mid:0$/m.test(t.sdp)&&(Er=!0),a()}).catch(a)}):Promise.resolve()})}function Nt(a,e){return c(this,null,function*(){o.debug("Try to get media",a.getNative());let t=Ke.hasPermissions(a.isVideo());!t&&!e&&T.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield la()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?Z.CAMERA_PERMISSION:Z.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?Z.CAMERA_ACCESS:Z.MIC_ACCESS;break}if(a.canSimplify())return Nt(a.simplify(),e);let r=e||Z.UNKNOWN;throw T.onPermissionsError(r),r}})}function ha(a){return c(this,null,function*(){o.debug("Try to get screen",a.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(a.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(o.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw Z.SCREEN_PERMISSION;default:throw Z.SCREEN_ACCESS}}})}function Lt(){return wt.length||(wt=(()=>{let a,e=!1,t=0,i="0",r=Ee.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return a=/\brv[ :]+(\d+)/g.exec(Ee),["IE",a&&a[1]||"Unknown",e,t,i];if(r[1]==="Safari"){if(a=Ee.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(a=Ee.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,Number(a[1]),i];if(a=Ee.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t,i];if(a=Ee.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t,i];if(a=Ee.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t,i]}if(r[1]==="Chrome"){if(e=!0,t=Number(r[2]),a=Ee.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t,i];if(a=Ee.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t,i];if(a=Ee.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t,i];if(a=Ee.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t,i]}return a=Ee.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),a&&a[2]!==void 0&&(i=a[2]),[r[2]?r[1]:pa,a&&a[1]||r[2]||Tr,e,t,i]})()),wt}var Ke;(q=>{function a(){return c(this,null,function*(){return yield ma(),xt()})}q.init=a;function e(){return Dt}q.getCameras=e;function t(){return At}q.getMicrophones=t;function i(){return pi}q.getOutput=i;function r(){return Dt.length>0}q.hasCamera=r;function n(){return At.length>0}q.hasMicrophone=n;function s(){return _t}q.getSavedCamera=s;function p(){return gt}q.getSavedMicrophone=p;function l(){return li}q.getSavedOutput=l;function h(){return ui}q.hasCameraPermission=h;function R(){return mi}q.hasMicrophonePermission=R;function y(_=!1){return R()?r()&&_?h():!0:!1}q.hasPermissions=y;function W(_=!1,G=!0,te=!0){return c(this,null,function*(){let b=n()&&G,ae=r()&&_,pe;if(!b&&!ae)pe=new MediaStream;else try{pe=yield Nt(new ft(b,ae))}catch(Ce){pe=new MediaStream}return!pe.getVideoTracks().length&&te&&pe.addTrack(He()),!pe.getAudioTracks().length&&te&&pe.addTrack(de()),pe})}q.getUserMedia=W;function K(){return c(this,null,function*(){return ha(new Cr(window.screen.width,window.screen.height))})}q.getScreenMedia=K;function N(_,G=!1){return c(this,null,function*(){let te=G?d.videoEffectMaxWidth:d.videoMaxWidth,b=G?d.videoEffectMaxHeight:d.videoMaxHeight;return Nt(new ft(!1,_||!0,te,b))})}q.getUserVideo=N;function he(_){return c(this,null,function*(){return Nt(new ft(_||!0,!1))})}q.getUserAudio=he;function De(_,G){return c(this,null,function*(){let b=(yield xt()).find(ae=>ae.kind===_&&ae.deviceId===G);return b?(_==="videoinput"?_t=b:_==="audioinput"?gt=b:_==="audiooutput"&&(li=b),Be.set(_,G),b):null})}q.saveDeviceId=De;function de(){if(!kt||kt.readyState==="ended"){let _=F(),G=_.createMediaStreamDestination(),te=_.createGain();te.gain.value=1e-5,te.connect(G),te.connect(_.destination);let b=_.createOscillator();b.type="sine",b.frequency.value=0,b.connect(te),b.start(),kt=G.stream.getAudioTracks()[0]}return Object.assign(kt.clone(),{enabled:!1})}q.getSilentMediaTrack=de;function He(_=d.videoMinWidth,G=d.videoMinHeight){return et||(et=document.createElement("canvas"),et.getContext("2d")),et.width=_,et.height=G,(!Ot||Ot.readyState==="ended")&&(Ot=et.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(Ot.clone(),{enabled:!1})}q.getBlackMediaTrack=He;function oe(){if(u()==="Edge"&&Number(I())<70)return!1;try{let _=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&_.RTCPeerConnection&&_.RTCIceCandidate&&_.RTCSessionDescription&&_.HTMLCanvasElement&&_.HTMLCanvasElement.prototype.captureStream&&_.RTCRtpSender&&_.RTCRtpSender.prototype.replaceTrack&&_.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(_){return!1}}q.isBrowserSupported=oe;function Pe(){return!!navigator.mediaDevices.getDisplayMedia}q.isScreenCapturingSupported=Pe;function $(){return vr}q.canVP8=$;function ct(){return Er}q.isUnifiedPlan=ct;function Ai(){let _=q.browserName()==="Safari"&&q.browserVersion()==="15"&&q.browserSubVersion()==="1",G=q.browserName()==="Opera"&&q.os()==="Windows";return _||G}q.isBrokenH264=Ai;function Oi(){return!(q.baseChromeVersion()&&q.isMobile())}q.canPreferH264=Oi;function ki(){return"setCodecPreferences"in window.RTCRtpTransceiver.prototype}q.canPreferRed=ki;function wi(){return _i||(_i=(()=>{let _={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let G in _)if(_.hasOwnProperty(G)&&_[G].test(Ee))return G;return"Unknown"})()),_i}q.os=wi;function xi(){return hi===null&&(hi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Tr)),hi}q.isMobile=xi;function u(){return Lt()[0]}q.browserName=u;function I(){return Lt()[1]}q.browserVersion=I;function D(){return Lt()[3]}q.baseChromeVersion=D;function F(){return gi||(gi=new(window.AudioContext||window.webkitAudioContext)),gi}q.getAudioContext=F;function x(){return Lt()[4]}q.browserSubVersion=x})(Ke||(Ke={}));var C=Ke;import{BitStream as _a}from"bit-buffer";var ga=65536,$e=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(o.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%ga!==e.sequence){o.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:n}=$e.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:n})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((n,s)=>n+s.data.byteLength,0),i=new Uint8Array(t),r=0;for(let n of e)i.set(new Uint8Array(n.data),r),r+=n.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new _a(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),s=i.readBits(1)<<1|r;return s===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,s>=2&&i.index++,i.readBits(3)!==7?(i.index++,(s===1||s===3)&&(i.index+=3)):(s===1||s===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var St=class extends $e{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;o.debug(`StreamBuilder started for participant [${e}]`),this._useImageBitmap="ImageBitmap"in window,We.isBrowserSupported()?this._decoder=new We:this._decoder=new Qe,this._decoder.init(i=>this._drawImage(i)).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}_drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._removeStream(),o.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(C.browserName()==="Safari"&&Number(C.browserVersion())>=15)}};var Ut=1,fa=1,yr=0,Rr=11,Pr=1,br=2,Mr=4,Dr=8;function Ar(a,e,t,i,r,n,s){let p=0;e&&(p|=Pr),t&&(p|=br),i&&(p|=Mr),s||(p|=Dr);let l=new ArrayBuffer(Rr),h=new DataView(l);if(h.setUint8(0,Ut),h.setUint16(1,r),h.setUint32(3,a),h.setUint8(7,n?1:0),h.setUint16(8,yr),h.setUint8(10,p),!s)return l;let R=new Uint8Array(l.byteLength+s.byteLength);return R.set(new Uint8Array(l),0),R.set(new Uint8Array(s),l.byteLength),R.buffer}function Or(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,s=e.getUint16(8),p=e.getUint8(10),l=!!(p&Pr),h=!!(p&br),R=!!(p&Mr),y=!!(p&Dr);if(t!==Ut)throw new Error(`Unexpected protocol version. Got ${t}, expected ${Ut}`);return{timestamp:r,start:l,end:h,keyframe:R,sequence:i,isVP9:n,ssrc:s,eos:y,data:a.slice(Rr)}}function kr(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==Ut||e.getUint8(1)!==fa||e.getUint16(2)!==yr)}import*as S from"simple-ebml-builder";var Sa=Li(2,15)-1,fi=1,va=5,Ea=5;var Bt=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),o.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=Bt._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return S.build(e[0])}else return new Uint8Array;let t=e.reduce((n,s)=>n+s.countSize(),0),i=new Uint8Array(t),r=0;for(let n of e){let s=S.build(n);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var n,s,p;((n=this._mediaSource)==null?void 0:n.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let e=(p=this._sourceBuffer)==null?void 0:p.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-va);r-i>Ea&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},Me=class extends $e{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;o.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return S.element(S.ID.EBML,[S.element(S.ID.EBMLVersion,S.number(1)),S.element(S.ID.EBMLReadVersion,S.number(1)),S.element(S.ID.EBMLMaxIDLength,S.number(4)),S.element(S.ID.EBMLMaxSizeLength,S.number(8)),S.element(S.ID.DocType,S.string("webm")),S.element(S.ID.DocTypeVersion,S.number(2)),S.element(S.ID.DocTypeReadVersion,S.number(2))])}static _genSegmentHeader(e,t,i){let r=S.element(S.ID.Info,[S.element(S.ID.TimecodeScale,S.number(1e6)),S.element(S.ID.MuxingApp,S.string("vk-webm-builder")),S.element(S.ID.WritingApp,S.string("vk-webm-builder"))]),n=[S.element(S.ID.PixelWidth,S.number(e)),S.element(S.ID.PixelHeight,S.number(t))],s=S.element(S.ID.Tracks,S.element(S.ID.TrackEntry,[S.element(S.ID.TrackNumber,S.number(fi)),S.element(S.ID.TrackUID,S.number(fi)),S.element(S.ID.TrackType,S.number(1)),S.element(S.ID.FlagLacing,S.number(0)),S.element(S.ID.DefaultDuration,S.number(1e9)),S.element(S.ID.CodecID,S.string(`V_${i.toUpperCase()}`)),S.element(S.ID.Video,n)]));return S.unknownSizeElement(S.ID.Segment,[r,s])}static _genClusterHeader(e){return S.unknownSizeElement(S.ID.Cluster,[S.element(S.ID.Timecode,S.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new Bt(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){o.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>o.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,o.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),o.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=Me._genWebmHeader();this._mediaBuffer.append(s);let p=Me._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(p)}let r=Math.round(i-this._clusterStartTime);if(r>Sa&&(this._clusterStartTime=i,r=0),r===0){o.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=Me._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let n=S.element(S.ID.SimpleBlock,[S.vintEncodedNumber(fi),S.bytes(Me._intToU16BE(r)),S.number((e.keyframe?1:0)<<7),S.bytes(e.frameData)]);this._mediaBuffer.append(n,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),o.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var tt=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};o.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=n=>this._onDataChannelMessage(n.data)}_onDataChannelMessage(e){var n,s;let t=Or(e),i=(s=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){o.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];if(!r){let p=l=>this._onStream(i,l);d.screenShareWebmBuilder&&Me.isBrowserSupported()?r=new Me(i,p):r=new St(i,p),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,o.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(We.isBrowserSupported()||Qe.isBrowserSupported())&&(St.isBrowserSupported()||Me.isBrowserSupported())}};import wr from"@vkontakte/libvpx";var Ta=1e3,vt=class extends Oe{constructor(e,t){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return c(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=p=>t(),r.onerror=()=>i(new Error("Video element error"));let n=r.play(),s=()=>i(new Error("Autoplay is disabled"));n?n.catch(s):s()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return c(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return c(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;o.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var u=Object.defineProperty;var b=o=>u(o,"__esModule",{value:!0});var g=(o,n)=>{b(o);for(var t in n)u(o,t,{get:n[t],enumerable:!0})};var y={};g(y,{default:()=>R});var e=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(e||{});var R=(o,n)=>{let t;function m(a,r){return o({locateFile:n}).then(s=>{if(t=new s.VpxEncoder,t.debug(r),!t.init(a?s.VpxType.VP9:s.VpxType.VP8))throw self.postMessage({type:e.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");t.setMaxQuantizer(10),t.setTargetBitrate(1024)})}function E(a,r,s,i){let c=t.allocateImage(a,r);if(!c){self.postMessage({type:e.FRAME,error:"No buffer data"});return}c.set(new Uint8Array(s));let f=Math.round(performance.now()),l=150;if(!t.encode(f,l,i)){self.postMessage({type:e.FRAME,error:"Encode failed"});return}let p=t.readFrame();if(!p){self.postMessage({type:e.FRAME,error:"No encoded data"});return}t.readFrame()&&(self.postMessage({type:e.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:e.LOG_ERROR,message:"LibVPxEncoder-drop"}));let d=new Uint8Array(p.byteLength);d.set(p),self.postMessage({type:e.FRAME,frameType:i?"key":"delta",timestamp:f,duration:l,data:d.buffer},[d.buffer])}self.onmessage=a=>{switch(a.data.type){case e.INIT:m(a.data.isVP9,a.data.debug).then(()=>self.postMessage({type:e.READY})).catch(r=>self.postMessage({type:e.ERROR,error:String(r)}));break;case e.FRAME:E(a.data.width,a.data.height,a.data.imageData,a.data.keyFrame);break}}};return y;})();
10
- `,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength})},[wr,wr.getUrl],{isVP9:this.isVP9(),debug:o.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(ge.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},Ta),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),o.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var it=class extends Oe{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return c(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;o.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var b=Object.defineProperty;var g=i=>b(i,"__esModule",{value:!0});var F=(i,n)=>{g(i);for(var r in n)b(i,r,{get:n[r],enumerable:!0})};var A={};F(A,{default:()=>h});var l=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(l||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,n,r,c,s,f,t,a=null,p=0,u=!1;function V(e){n=e.readable,r=n.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&E(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),n.cancel();return}a=R,E(R,e)}}))}function E(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
11
- `,r=>{var n;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(n=r.data)==null?void 0:n.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:d.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(ge.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),o.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var Ia=16*1024,Ca=11,xr=Ia-Ca,ya=65536,Si=0,rt=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;o.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,n)=>{if(!this._destroyed){if(!r){o.warn("requestFrame failed, keyFrame: "+this._needKeyframe,n),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{o.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};it.isBrowserSupported()?this._encoder=new it(e,i):this._encoder=new vt(e,i),this._datachannel.onmessage=r=>{kr(r.data)&&(o.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>o.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,n){let s=Ar(e,t,i,r,Si,this._encoder.isVP9(),n);return Si=(Si+1)%ya,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return c(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let n=e.data.slice(t,t+xr),s=e.data.byteLength<=t+n.byteLength,p=this._wrapHeader(e.timestamp,!t,s,e.type==="key",n);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(p)}catch(l){o.warn("Error send data to DataChannel",l),r();return}s||window.setTimeout(()=>this._sendChunk(e,t+xr,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),o.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return it.isBrowserSupported()||vt.isBrowserSupported()}};var X=class{static get sessionKey(){return X._sessionKey}static set sessionKey(e){X._sessionKey=e}static get sessionSecretKey(){return X._sessionSecretKey}static set sessionSecretKey(e){X._sessionSecretKey=e}static get accessToken(){return X._accessToken}static set accessToken(e){X._accessToken=e}static isEmpty(){return!X._sessionKey||!X._sessionSecretKey}};var f=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(f._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(f._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(f._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(X.accessToken=e.apiAuth.accessToken,X.sessionKey=e.apiAuth.sessionKey,X.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(f._params,e)}static get(e){return f._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.5.3-dev.d006735.0"}static get debug(){return undefined}static get protocolVersion(){return f._params.joinFromMultipleDevices?6:5}static get platform(){return f._params.platform}static set platform(e){f._params.platform=e}static get clientType(){return f._params.clientType}static set clientType(e){f._params.clientType=e}static get device(){return f._params.device}static get apiKey(){return f._params.apiKey}static get apiEnv(){return f._params.apiEnv}static get apiEndpoint(){switch(f.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return f._params.apiEnv}}static get authToken(){return f._params.authToken}static set authToken(e){f._params.authToken=e}static get anonymToken(){return f._params.anonymToken}static set anonymToken(e){f._params.anonymToken=e}static get domain(){return f._params.domain}static get iceServers(){return f._params.iceServers}static set iceServers(e){f._params.iceServers=e}static get wssBase(){return f._params.wssBase}static set wssBase(e){f._params.wssBase=e}static get wssToken(){return f._params.wssToken}static set wssToken(e){f._params.wssToken=e}static get signalingReconnectDelay(){return f._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return f._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return f._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return f._params.waitConnectionDelay}static get waitResponseDelay(){return f._params.waitResponseDelay}static get waitMessageDelay(){return f._params.waitMessageDelay}static get waitAnotherTabDelay(){return f._params.waitAnotherTabDelay}static get debugLog(){return f._params.debugLog}static get forceRelayPolicy(){return f._params.forceRelayPolicy}static set forceRelayPolicy(e){f._params.forceRelayPolicy=e}static get videoMinWidth(){return f._params.videoMinWidth}static get videoMaxWidth(){return f._params.videoMaxWidth}static set videoMaxWidth(e){f._params.videoMaxWidth=e}static get videoMinHeight(){return f._params.videoMinHeight}static get videoMaxHeight(){return f._params.videoMaxHeight}static set videoMaxHeight(e){f._params.videoMaxHeight=e}static get videoAspectRatio(){return f._params.videoAspectRatio}static get videoFrameRate(){return f._params.videoFrameRate}static get videoFacingMode(){return f._params.videoFacingMode}static get screenFrameRate(){return f._params.screenFrameRate}static get videoEffects(){return f._params.videoEffects}static set videoEffects(e){f._params.videoEffects=e}static get videoEffectMaxWidth(){return f._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){f._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return f._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){f._params.videoEffectMaxHeight=e}static get voiceParams(){return f._params.voiceParams}static get specListenerParams(){return f._params.specListenerParams}static get iceRestartWaitTime(){return f._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return f._params.transportConnectionWaitTime}static get statisticsInterval(){return f._params.statisticsInterval}static set statisticsInterval(e){f._params.statisticsInterval=e}static get networkStatisticsInterval(){return f._params.networkStatisticsInterval}static get perfStatReportEnabled(){return f._params.perfStatReportEnabled}static get callStatReportEnabled(){return f._params.callStatReportEnabled}static get producerNotificationDataChannel(){return f._params.producerNotificationDataChannel&&tt.isBrowserSupported()}static get producerCommandDataChannel(){return f._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return f._params.consumerScreenDataChannel&&rt.isBrowserSupported()}static get producerScreenDataChannel(){return f._params.producerScreenDataChannel&&f.producerNotificationDataChannel}static get screenShareWebmBuilder(){return f._params.screenShareWebmBuilder}static get noiseSuppression(){return f._params.noiseSuppression}static set noiseSuppression(e){f._params.noiseSuppression=e}static get preferH264(){return f._params.preferH264}static get preferVP9(){return f._params.preferVP9}static get audioNack(){return f._params.audioNack}static get consumerScreenTrack(){return f._params.consumerScreenTrack&&f.consumerScreenDataChannel}static get producerScreenTrack(){return f._params.producerScreenTrack&&f.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=f._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return f._params.movieShare&&f.videoTracksCount>0}static get videoTracksCount(){return f.producerNotificationDataChannel?f._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return f._params.breakVideoPayloadTypes}static get filteredMessages(){return f._params.filteredMessages}static get serverAudioRed(){return f._params.serverAudioRed}static get p2pAudioRed(){return f._params.p2pAudioRed}static get batchParticipantsOnStart(){return f._params.batchParticipantsOnStart}static get participantStateMapped(){return f._params.participantStateMapped}},d=f;d._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,serverAudioRed:!1,p2pAudioRed:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,participantStateMapped:!0,joinFromMultipleDevices:!0};var Y=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))(Y||{});function U(a,...e){let t=d.get(a);t&&setTimeout(t,0,...e)}function ke(a){return Object.assign({},a)}function at(a){return a.slice()}var vi;(ne=>{function a(v,P){U("onLocalStream",v,ke(P))}ne.onLocalStream=a;function e(v,P){U("onScreenStream",v,ke(P))}ne.onScreenStream=e;function t(v,P){U("onLocalStreamUpdate",ke(v),P)}ne.onLocalStreamUpdate=t;function i(v){U("onLocalStatus",v)}ne.onLocalStatus=i;function r(v,P){U("onRemoteStream",v,P)}ne.onRemoteStream=r;function n(v,P,V){U("onRemoteLive",v,P,V)}ne.onRemoteLive=n;function s(v,P){U("onRemoteScreenStream",v,P)}ne.onRemoteScreenStream=s;function p(v,P,V,J){U("onConversation",v,ke(P),ke(V),J)}ne.onConversation=p;function l(v,P){U("onRemoteMediaSettings",v,ke(P))}ne.onRemoteMediaSettings=l;function h(v,P){U("onRemoteParticipantState",v,ke(P))}ne.onRemoteParticipantState=h;function R(v,P,V=null){U("onRemoteStatus",v,P,V)}ne.onRemoteStatus=R;function y(v,P,V=null){U("onParticipantStatus",v,P,V)}ne.onParticipantStatus=y;function W(){U("onPermissionsRequested")}ne.onPermissionsRequested=W;function K(v){U("onPermissionsError",v)}ne.onPermissionsError=K;function N(v){U("onRemoteRemoved",v)}ne.onRemoteRemoved=N;function he(v,P,V){U("onCallState",v,P,ke(V))}ne.onCallState=he;function De(v,P){U("onDeviceSwitched",v,P)}ne.onDeviceSwitched=De;function de(v,P,V,J=!1,ee=!1,Yt=null,Qr=null){U("onMuteStates",ke(v),at(P),at(V),J,ee,Yt,Qr)}ne.onMuteStates=de;function He(v,P){U("onRolesChanged",v,at(P))}ne.onRolesChanged=He;function oe(v){U("onLocalRolesChanged",at(v))}ne.onLocalRolesChanged=oe;function Pe(v,P){U("onPinnedParticipant",v,P)}ne.onPinnedParticipant=Pe;function $(v){U("onLocalPin",v)}ne.onLocalPin=$;function ct(v){U("onOptionsChanged",at(v))}ne.onOptionsChanged=ct;function Ai(){U("onCallAccepted")}ne.onCallAccepted=Ai;function Oi(){U("onRateNeeded")}ne.onRateNeeded=Oi;function ki(v){U("onSpeakerChanged",v)}ne.onSpeakerChanged=ki;function wi(v){U("onVolumesDetected",at(v))}ne.onVolumesDetected=wi;function xi(v,P){U("onLocalVolume",v,P)}ne.onLocalVolume=xi;function u(v,P){U("onJoinStatus",v,P)}ne.onJoinStatus=u;function I(v,P){U("onHangup",v,P)}ne.onHangup=I;function D(v){U("onMultipartyChatCreated",ke(v))}ne.onMultipartyChatCreated=D;function F(){U("onDeviceChange")}ne.onDeviceChange=F;function x(v){U("onFingerprintChange",v)}ne.onFingerprintChange=x;function q(){U("onTokenExpired")}ne.onTokenExpired=q;function _(v,P,V=!1){U("onChatMessage",v,P,V)}ne.onChatMessage=_;function G(v,P,V=!1){U("onCustomData",v,P,V)}ne.onCustomData=G;function te(v,P,V,J,ee,Yt){U("onRecordStarted",v,P,V,J,ee,Yt)}ne.onRecordStarted=te;function b(){U("onRecordStopped")}ne.onRecordStopped=b;function ae(v){U("onLocalNetworkStatusChanged",v)}ne.onLocalNetworkStatusChanged=ae;function pe(v){U("onNetworkStatusChanged",v)}ne.onNetworkStatusChanged=pe;function Ce(v,...P){U("onDebugMessage",v,...P)}ne.onDebugMessage=Ce;function ie(v,P){let V=Object.assign({},v,{memory:P});U("onStatistics",V)}ne.onStatistics=ie;function Ae(){U("onAutoplayError")}ne.onAutoplayError=Ae;function Pt(v,P,V){U("onChatRoomUpdated",v,P,V)}ne.onChatRoomUpdated=Pt})(vi||(vi={}));var T=vi;var Nr=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(Nr||{}),Ei;(oe=>{let a="📞",e=(Pe,...$)=>{T.onDebugMessage(Pe,...$)},t=!1,i=(Pe,$)=>(...ct)=>{Pe(...ct),mr($,ct)},r=console.debug.bind(console,a),n=console.log.bind(console,a),s=console.warn.bind(console,a),p=console.error.bind(console,a),l=e.bind(null,"DEBUG"),h=e.bind(null,"LOG"),R=e.bind(null,"WARN"),y=e.bind(null,"ERROR");oe.debug=l,oe.log=h,oe.warn=R,oe.error=y;function De(){return t}oe.enabled=De;function de(Pe){t=Pe,d.debugLog&&ii(),Pe?(oe.debug=d.debugLog?i(r,"DEBUG"):r,oe.log=d.debugLog?i(n,"LOG"):n,oe.warn=d.debugLog?i(s,"WARN"):s,oe.error=d.debugLog?i(p,"ERROR"):p):(oe.debug=d.debugLog?i(l,"DEBUG"):l,oe.log=d.debugLog?i(h,"LOG"):h,oe.warn=d.debugLog?i(R,"WARN"):R,oe.error=d.debugLog?i(y,"ERROR"):y)}oe.toggle=de;function He(Pe,...$){switch(Pe){case"DEBUG":oe.debug(...$);break;case"LOG":oe.log(...$);break;case"WARN":oe.warn(...$);break;case"ERROR":oe.error(...$);break}}oe.send=He})(Ei||(Ei={}));var o=Ei;var nt=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(nt||{}),ue;(p=>{function a(l){return l.length?typeof l[0]=="object"?l:l.map(h=>e(h)):[]}p.fromIds=a;function e(l,h="USER"){return{id:l,type:h}}p.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}p.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}p.toString=i;function r(l,h="USER"){return i(e(l,h))}p.fromIdToString=r;function n(l){try{return JSON.parse(l)}catch(h){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}p.fromString=n;function s(l,h){return l.id===h.id&&l.type===h.type}p.compare=s})(ue||(ue={}));var me;(r=>{function a(n,s="USER",p=0){return{id:n,type:s,deviceIdx:p}}r.fromId=a;function e(n){return`{"id":"${n.id}","type":"${n.type}","deviceIdx":"${n.deviceIdx}"}`}r.toString=e;function t(n,s){return Object.assign({deviceIdx:s},ue.fromSignaling(n))}r.fromSignaling=t;function i(n){return n&&typeof n=="object"?n.deviceIdx:0}r.getDeviceIdx=i})(me||(me={}));var Te=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(Te||{}),Lr="s",Ur="m";function Ve(a){return a.participantId+(a.mediaType?Ze+Lr+a.mediaType:"")+(a.streamName?Ze+Ur+a.streamName:"")}function Et(a){let e=a.split(Ze),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i=null,r,n=0;for(let p of e)switch(p.charAt(0)){case Lr:i=Ra(p.slice(1));break;case Ur:r=p.slice(1);break;case Mt:n=Number.parseInt(p.slice(1),10);break;default:throw new Error("Unexpected parameter type "+p.charAt(0)+" in stream description "+a)}return{participantId:E.compose(t,n),mediaType:i,streamName:r}}function Ra(a){for(let e of Object.keys(Te))if(e===a)return Te[e];return null}function Ti(a,e){return a===null||e===null?a===null&&e===null:!(a.maxDimension!==e.maxDimension||a.maxBitrateK!==e.maxBitrateK||a.maxFramerate!==e.maxFramerate||a.degradationPreference!==e.degradationPreference)}function Vt(a,e){return!(!Ti(a.camera,e.camera)||!Ti(a.screenSharing,e.screenSharing))}function Ii(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function Br(a){try{return btoa(JSON.stringify(a))}catch(e){o.warn("WaitingParticipant: failed convert to string",a,e)}return null}function Vr(a){try{return JSON.parse(atob(a))}catch(e){o.warn("WaitingParticipant: failed convert from string",a,e)}return null}var Tt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,m.log(g.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,m.log(g.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(o.log("Failed to fix RV"),m.log(g.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),m.log(g.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,o.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===le.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Ft=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(!((s=this._output)==null?void 0:s.audioTrack))return;let e=C.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{o.warn("Error on play audio"),T.onAutoplayError()},r=p=>{t.srcObject=new MediaStream([p]),t.load();let l=t.play();l?l.catch(i):i()},n=()=>{var l;o.debug("Recover audio playback");let p=(l=this._output)==null?void 0:l.audioTrack;p?r(p):o.warn("Broken audio track")};t.onpause=n,t.onstalled=n,t.onerror=n,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return c(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=C.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw m.log(g.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var Pa=90,ba=3,Ht=class extends z{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),T.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>Pa?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=ba)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var Ma=44100,It=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=C.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=Ma/this._fftBins.length,t=Math.ceil(d.voiceParams.minFreq/e),i=Math.floor(d.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((n,s)=>n+s,0)/e.length/255,r=this._lastSmoothedLevel*d.voiceParams.smoothing+i*(1-d.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var Gt=class extends z{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&T.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,d.voiceParams.interval)};this._interval=window.setTimeout(t,d.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,ve.SOURCE_CHANGED,r=>{r.kind===le.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new It("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var Fr="videochat-epi",Da=5e3,Aa=3e4,qe=class extends z{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,w.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Fr)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return c(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&d.perfStatReportEnabled&&this._previousTimestamp+Da<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),d.callStatReportEnabled&&this._previousCallStatReportTimestamp+Aa<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return c(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(Fr,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,n)=>(n.kind==="video"?(n.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+n.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+n.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=n.framesDropped,r.nack_sent+=n.nackCount,r.pli_sent+=n.pliCount,r.fir_sent+=n.firCount):(n.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+n.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+n.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=n.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=n.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=n.removedSamplesForAcceleration,r.concealed_audio_samples+=n.concealedSamples,r.silent_concealed_audio_samples+=n.silentConcealedSamples,r.audio_concealment_events+=n.concealmentEvents),r),t),e.outbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.nack_received+=n.nackCount,r.pli_received+=n.pliCount,r.fir_received+=n.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,n=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,p=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,l=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,h=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=n/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=p/r*1e3,i.concealed_silent_audio_samples=l/r*1e3,i.concealment_audio_avg_size=p/h,i.total_audio_energy=t.total_audio_energy}m.logCustom("callStat",i),o.log("Sent call stats",i),this._previousCallStatReport=t}};var Oa=1e3;function se(a,e,t=0){return e in a&&a[e]?a[e]:t}function Hr(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function Fe(a,e){return t=>t[a]===e}function ka(a){return(e,t)=>e[a]-t[a]}function Wt(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function wa(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function xa(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Ci(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=xa(t[1])?Ci(t[1]):t[1],e),{})}function Na(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function La(a){return c(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...a.getReceivers().map(t=>t.getStats())),e.push(...a.getSenders().map(t=>t.getStats()))):e.push(a.getStats()),Promise.all(e).then(Na).then(wa)})}function Ua(a){let e=a.filter(Fe("type","candidate-pair")).sort(ka("priority")).find(Hr(Fe("nominated",!0),Fe("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=a.find(Fe("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=a.find(Fe("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),Ci(t)}function Ba(a,e){let t=Wt("id",a),i=a.filter(Hr(Fe("type","inbound-rtp"),Fe("type","outbound-rtp")));C.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,s)=>{if(!n[s.ssrc])n[s.ssrc]=s;else{let p=Object.assign({},n[s.ssrc],s),l=n[s.ssrc].isRemote?s:n[s.ssrc];p.id=l.id,p.type=l.type,delete p.isRemote,delete p.remoteId,n[p.ssrc]=p}return n},{})));let r={};if(C.browserName()==="Safari"){let n=a.filter(Fe("type","track"));r=Wt("trackIdentifier",n)}return i.map(n=>{let s=Number(n.ssrc),p=n.mediaType||n.kind,l=n.trackId,h=n.type,R=n.codecId;if(C.browserName()==="Safari"){let W=/^.+_([\d]+)$/.exec(n.id);if(W&&(s=parseInt(W[1],10)),p=n.id.indexOf("Audio")>0?"audio":"video",e[s]){let K=p+"-"+e[s];r[K]&&(l=r[K].id)}}if(!h||!s||!p)return null;let y={ssrc:s,type:h,kind:p,bytesReceived:se(n,"bytesReceived"),bytesSent:se(n,"bytesSent"),jitter:se(n,"jitter"),packetsLost:se(n,"packetsLost"),packetsReceived:se(n,"packetsReceived"),packetsSent:se(n,"packetsSent"),fractionLost:se(n,"fractionLost"),pliCount:se(n,"pliCount"),firCount:se(n,"firCount"),nackCount:se(n,"nackCount"),userId:e[s]};if(p==="video"){let W=se(n,"framesDecoded"),K=se(n,"totalInterFrameDelay"),N=se(n,"totalSquaredInterFrameDelay");y.interframeDelayVariance=(N-K*K/W)/W}if(p==="audio"&&(y.totalSamplesReceived=se(n,"totalSamplesReceived"),y.concealedSamples=se(n,"concealedSamples"),y.insertedSamplesForDeceleration=se(n,"insertedSamplesForDeceleration"),y.removedSamplesForAcceleration=se(n,"removedSamplesForAcceleration"),y.silentConcealedSamples=se(n,"silentConcealedSamples"),y.concealmentEvents=se(n,"concealmentEvents"),y.totalAudioEnergy=se(n,"totalAudioEnergy")),R&&t[R]){let W=t[R];y.clockRate=W.clockRate,y.mimeType=W.mimeType}if(l&&t[l]){let W=t[l];y.frameHeight=W.frameHeight,y.frameWidth=W.frameWidth,y.framesDecoded=W.framesDecoded,y.framesReceived=W.framesReceived,y.framesDropped=W.framesDropped}return Ci(y)}).filter(n=>!!n)}function Va(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=Wt("ssrc",a.rtps),i=Wt("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let s=t[n],p=i[n];if(!(!s||!p)){if(s.bytesReceived&&s.bytesReceived>p.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-p.bytesReceived)/r)),s.bytesSent&&s.bytesSent>p.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-p.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>p.packetsReceived||s.packetsLost>p.packetsLost){let l=s.packetsLost-p.packetsLost,h=s.packetsReceived-p.packetsReceived;s.packetLoss=parseFloat((100*l/(l+h)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&p.framesDropped&&s.framesDropped>p.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-p.framesDropped)/r).toFixed(0)))}}),a}function Ct(i,r){return c(this,arguments,function*(a,e,t={}){let n=yield La(a),s={timestamp:Date.now(),transport:Ua(n),rtps:Ba(n,t)};return e?Va(s,e):(yield E.delay(Oa),Ct(a,s,t))})}var jt=.8,Je=class extends z{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=L.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=n,this._perfStatReporter=new qe(this,i,!0),this.subscribe(this._signaling,_e.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ve.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ve.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:d.iceServers,iceTransportPolicy:d.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,d.p2pAudioRed&&C.canPreferRed()),this._applySettings()}catch(s){m.log(g.ERROR,"addTrack-direct"),o.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===L.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==L.IDLE&&e!==L.CLOSED&&e!==L.FAILED&&this._startStatInterval()}open(e=null){return c(this,null,function*(){if(this._isOpen){o.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(o.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,d.p2pAudioRed&&C.canPreferRed()),this._applySettings()}catch(i){m.log(g.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(L.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(w.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Vt(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(w.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(o.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(L.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(L.CLOSED)),this._triggerEvent(w.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(w.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case A.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case A.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case A.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((n=e.data.sdk)==null?void 0:n.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=E.getPeerIdString(e.peerId);E.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){o.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw m.log(g.ERROR,"addIceCandidate-direct"),o.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else o.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return c(this,null,function*(){if(!this._remoteCandidates[e]){o.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){o.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw m.log(g.ERROR,"setRemoteDescription-direct"),o.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){o.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(w.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(w.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return c(this,null,function*(){e.candidate&&this._signaling.ready&&(o.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(o.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>c(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(o.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===L.IDLE||e===L.OPENED?this._setState(L.CONNECTING):this._setState(L.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),m.log(g.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(L.CONNECTED),this._stopReconnection(),E.getPeerConnectionHostInfo(this._pc).then(e=>{e&&m.log(g.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(L.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(o.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},d.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(o.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(Ie.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(m.log(g.ICE_RESTART),o.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):o.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,o.error("Ice restart failed",{participantId:this._participantId}),m.log(g.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return c(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return o.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw o.error("Unable to create offer",i,{participantId:this._participantId}),m.log(g.ERROR,"createOffer-direct"),i}).then(i=>c(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=Je._patchDescription(i),o.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw o.error("Unable to set local description",i,{participantId:this._participantId}),m.log(g.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return c(this,null,function*(){return o.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw o.error("Unable to create answer",e,{participantId:this._participantId}),m.log(g.ERROR,"createAnswer-direct"),e}).then(e=>c(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=Je._patchDescription(e),o.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw o.error("Unable to set local description",e,{participantId:this._participantId}),m.log(g.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!C.baseChromeVersion();return e.sdp=E.patchSDP(e.sdp,d.preferH264&&C.canPreferH264(),C.isBrokenH264(),d.preferVP9,t&&d.audioNack,d.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{o.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),m.log(g.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Ct(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:Ie.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:Ie.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(w.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,d.statisticsInterval)})};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=de=>de.rtt<=this._networkLimits.goodNet.rtt&&de.loss<=this._networkLimits.goodNet.loss,i=de=>de.rtt>=this._networkLimits.badNet.rtt||de.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((de,He)=>Math.max(de,He.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-jt)+r*jt,loss:this._lastNetworkStat.loss*(1-jt)+n*jt},p=i(s),l=t(s),h=i(this._remoteNetworkStat),R=t(this._remoteNetworkStat),y=i(this._lastNetworkStat),W=t(this._lastNetworkStat),he=p||h?.2:l&&R?1:0,De=Date.now();if((y!==p||W!==l||De-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(de=>{o.warn("Unable to send [bad-net]",de)})),he){let de={};de[this._participantId]=de[""]=he,this._triggerEvent(w.NETWORK_STATUS,de)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=E.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(T.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=E.applySettings(this._pc,e,this._prevConsumerSettings))}};var Gr=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Gr||{}),yt=Gr;import{decode as st}from"messagepack";var yi=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var n,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let p=st(r);return Object.entries(p).forEach(([N,he])=>{let De=Et(N);this.streamDescriptionByCompactId.set(he,De)}),null;case 2:case 4:let l=st(r),h=[];for(let N of l){let he=this.getStreamDescription(N);he&&h.push(he.participantId)}return i===2?{type:"notification",notification:A.AUDIO_ACTIVITY,activeParticipants:h}:{type:"notification",notification:A.STALLED_ACTIVITY,stalledParticipants:h};case 3:let R=st(r);return{type:"notification",notification:A.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(R))==null?void 0:n.participantId};case 5:let y=st(r);return{type:"notification",notification:A.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:y[0],maxDimension:y[1]}};case 6:let W=st(r),K={};for(let[N,he]of Object.entries(W)){let De=(s=this.getStreamDescription(Number(N)))==null?void 0:s.participantId;De&&(K[De]=he/100)}return{type:"notification",notification:A.NETWORK_STATUS,statuses:K};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return o.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=st(e),i=[];for(let[r,n]of Object.entries(t)){let s=n[0],p=n[1],l=n[2],h;if(s!==null){if(h=this.getStreamDescription(s),!h){o.error(`could not uncompress participant ID ${s}`);continue}}else h=null;if(l===null){o.error("unexpected null sequenceNumber",r,n);continue}let R=be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,y=p?p>>>0:null;i.push({participantStreamDescription:h,streamId:R,rtpTimestamp:y,sequenceNumber:l})}return{type:"notification",notification:A.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Fa=90,Ha=4294967295,ye=class extends z{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=L.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,_e.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ve.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ve.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,ve.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new qe(this,e),this._serverSettings=i,o.debug("ServerTransport: Created")}getState(){return this._state||L.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==L.IDLE&&e!==L.CLOSED&&e!==L.FAILED&&this._startStatInterval()}open(e=!1){if(this._isOpen){o.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(o.error("ServerTransport: Closed",e),this._setState(L.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(L.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Vt(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,ye._closeDataChannel(this._producerNotification),ye._closeDataChannel(this._producerCommand),ye._closeDataChannel(this._producerScreen),ye._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(w.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){o.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let n=r.readyState;n==="open"?(o.debug(`[${t}] data channel opened`),r.onerror=s=>{o.error(`[${t}] data channel error`,s)},i(r)):o.error(`[${t}] data channel open failed, state [${n}]`)}}_openConnection(e=!1){o.debug("ServerTransport: Open single connection");let t={};C.baseChromeVersion()&&(t.sdpSemantics=ye._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=E.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=ye._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,yt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new yi,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,yt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,yt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,d.serverAudioRed&&C.canPreferRed()),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){o.error("ServerTransport: Unable to add media source tracks",i),m.log(g.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,yt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(L.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==L.OPENED&&(this._setState(L.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(w.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(w.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(w.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(w.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
- `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!d.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new rt(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!d.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new tt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(w.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(w.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!d.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==le.video)return;let r=!this._disabledSenders.has(i),n=e.maxDimension!==0;if(r&&!n){o.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(C.getBlackMediaTrack()).catch(p=>{o.error("Could not disable video upload",p)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&n&&s){o.log("Enabling video upload"),this._disabledSenders.delete(i);let p=i.track;p.enabled=s.enabled,i.replaceTrack(s).then(()=>p.stop()).catch(l=>{o.error("Could not enable video upload",l)})}E.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(w.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,d.statisticsInterval)};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return c(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Ct(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(w.REMOTE_DATA_STATS,{inbound:{topology:Ie.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:Ie.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=be.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(w.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:qe.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:d.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:d.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:d.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:d.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:ye._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount,red:d.serverAudioRed};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return c(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,o.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(o.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw o.error("[single] unable to set remote offer",i),m.log(g.ERROR,"setRemoteDescription-single"),i}).then(()=>c(this,null,function*(){if(o.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw o.error("[single] unable to create answer",i),m.log(g.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=E.patchSDP(i.sdp,!1,C.isBrokenH264(),!1),i)).then(i=>c(this,null,function*(){if(o.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw o.error("[single] unable to set local answer",i),m.log(g.ERROR,"setLocalDescription-single"),i}).then(i=>c(this,null,function*(){o.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),o.debug("[single] remote offer has been processed")})).catch(i=>{o.warn("[single] unable to send local answer",i),m.log(g.ERROR,"acceptProducer")}).then(()=>c(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){o.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return c(this,null,function*(){if(!!this._isOpen)switch(e.notification){case A.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case A.REALLOC_CON:this._reconnect();break;case A.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case A.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case A.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case A.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return c(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),d.breakVideoPayloadTypes&&(o.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){o.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent(w.REMOTE_TRACK_REMOVED,i.id,i,n.track)}),i.getTracks().find(n=>n.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(w.REMOTE_TRACK_ADDED,i.id,i,t.track)):o.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){o.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(o.debug("[single] connection state changed",{state:e.connectionState},t),m.log(g.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===L.IDLE||i===L.OPENED?this._setState(L.CONNECTING):e.iceConnectionState==="checking"&&this._setState(L.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(L.RECONNECTING);break;case"connected":this._setState(L.CONNECTED),E.getPeerConnectionHostInfo(e).then(r=>{r&&m.log(g.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(d.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{o.error("ServerTransport: Unable to replace track",r),m.log(g.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=C.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(C.browserName(),Number(C.browserVersion()))}getStreamWaitingTimeMs(e,t){if(!this._pc)return m.log(g.PAT_WAITING_TIME_ERROR,"noConnection"),o.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return m.log(g.PAT_WAITING_TIME_ERROR,"noReceiver"),o.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return o.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return m.log(g.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),o.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let p=t-s&Ha,l=Math.ceil(p/Fa);return Math.min(100,Math.max(0,l))}};var w=(N=>(N.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",N.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",N.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",N.REMOTE_ALL_STALL="REMOTE_ALL_STALL",N.REMOTE_DATA_STATS="REMOTE_DATA_STATS",N.STATE_CHANGED="STATE_CHANGED",N.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",N.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",N.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",N.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",N.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",N.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",N.NETWORK_STATUS="NETWORK_STATUS",N.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",N))(w||{}),L=(p=>(p.IDLE="IDLE",p.OPENED="OPENED",p.CONNECTING="CONNECTING",p.RECONNECTING="RECONNECTING",p.CONNECTED="CONNECTED",p.CLOSED="CLOSED",p.FAILED="FAILED",p))(L||{}),Ie=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(Ie||{}),Ri=class extends z{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,_e.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){o.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,i=!1){let r=!1;for(let n of e){if(this._opened.indexOf(n)!==-1){o.warn(`The participant [${n}] has already had opened transport`);continue}if(this._allocated.indexOf(n)===-1){o.warn(`The participant [${n}] has no allocated transport`);continue}this._opened.push(n),r=!0}!r||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),o.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&o.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===A.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===A.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(o.log(`Topology changed ${this._topology} -> ${e.topology}`),m.log(g.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],n=e.offerToDeviceIdxs||[],s=i.length&&r.length?E.composeParticipantId(i[0],r[0],n[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){o.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&o.warn("Topology changed to DIRECT, but the allocated participants count more then one");let p=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=s===p;this._directTransport=this._createDirectTransport(p,l)}this._opened.indexOf(p)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new Je(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._dtListeners&&this._dtListeners.length>0&&o.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new ye(this._signaling,this._mediaSource,this._serverSettings);return this._stListeners&&this._stListeners.length>0&&o.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("ACTIVE_PARTICIPANTS_NO_SIGNAL",this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;d.noiseSuppression!==e&&(d.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent("ACTIVE_PARTICIPANTS_NO_SIGNAL")}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(m.log(g.PAT_WAITING_TIME_ERROR,"wrongTopology"),o.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(m.log(g.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Ye=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(Ye||{}),Pi=class extends z{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,w.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,w.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,w.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,w.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===le.audio&&((r=this._detector)==null||r.destroy(),this._detector=new It(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,d.voiceParams.interval)};this._interval=window.setTimeout(n,d.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===le.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===be.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var bi=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(bi||{}),Mi=class extends z{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,Ye.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,w.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,w.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,w.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>d.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*d.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent("SPEAKER_CHANGED",e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var Kt=class extends z{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,w.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,Ye.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===L.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),d.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),d.specListenerParams.volumeTimeout))),t===L.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==L.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Ga=1e3,Wa=1e4;var ja=15,B=class extends z{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=j.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;m.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),m.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new Ft,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Ga))}static current(){return B._current}static hangupAfterInit(){B._activationMutex&&!B._current&&(B._delayedHangup=!0)}static id(){var e,t;return((t=(e=B._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,s=!1){return c(this,null,function*(){if(B._activationMutex)throw m.log(g.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new O(M.FAILED);B._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let p=this._mediaSource.getMediaSettings();t===xe.CHAT||e.length>1?this._logWithMediaSettings(g.OUTGOING_MULTIPARTY_CALL,p):this._logWithMediaSettings(g.OUTGOING_CALL,p);let l=yield this._startConversation(e,t,Le.OUTGOING,i,r,n,s);if(!this._conversation)throw new O(M.UNKNOWN_ERROR);if(this._participantState=j.ACCEPTED,this._signaling.changeMediaSettings(p),yield this._registerParticipants(l.conversation.participants),this._processConnectionData(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new O(M.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let h=Object.values(this._participants),R;return d.batchParticipantsOnStart&&(R=E.mapSharedParticipants(h)),T.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,R),T.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),B._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(h,Y.WAITING),this._conversation}catch(p){throw this._close(p,"Unable to start conversation"),p}finally{B._activationMutex=!1}})}onJoin(e){return c(this,null,function*(){var t;if(B._activationMutex)throw m.log(g.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new O(M.FAILED);B._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.JOIN_CONVERSATION,r);let n=yield this._joinConversation(e);if(!this._conversation)throw new O(M.UNKNOWN_ERROR);return this._conversation.observer=i,T.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(o.log("In waiting hall"),B._current=this,B._activationMutex=!1,this._signaling.readyToSend(),T.onLocalStatus(Y.WAITING_HALL),this._conversation):this._onJoinPart2(n)}catch(i){throw B._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return c(this,null,function*(){o.debug("Join conversation part 2"),B._activationMutex=!0;try{if(this._participantState=j.ACCEPTED,!this._conversation||!this._mediaSource)throw new O(M.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new O(M.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=E.mapSharedParticipants(t)),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),T.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),B._current=this,d.batchParticipantsOnStart||this._setParticipantsStatus(t,Y.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{B._activationMutex=!1}})}onPush(r){return c(this,arguments,function*(e,t=Q.USER,i){if(B._activationMutex)throw o.warn("Conversation: there is already running activation"),new O(M.REJECTED);B._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new O(M.UNKNOWN_ERROR);if(!n.conversation.participants.find(p=>{var l;return p.state===j.CALLED&&p.id===((l=this._conversation)==null?void 0:l.userId)}))throw o.log("Push rejected (there is an active call)"),m.log(g.PUSH,"rejected"),new O(M.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),m.log(g.PUSH,"accepted"),B._current=this,B._delayedHangup)throw new O(M.CANCELED);B._activationMutex=!1}catch(n){throw B._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Qt.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>E.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return c(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new O(M.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),T.onCallAccepted(),this._state="ACTIVE",this._participantState=j.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return c(this,null,function*(){if(this._state!=="IDLE")throw m.log(g.ERROR,"acceptIncoming"),o.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new O(M.UNKNOWN_ERROR);this._state="PROCESSING",o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=j.ACCEPTED;let i=Object.values(this._participants),r;d.batchParticipantsOnStart&&(r=E.mapSharedParticipants(i)),T.onCallAccepted(),T.onLocalStream(this._mediaSource.getStream(),t),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),T.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(Ue.MUTE)||n.includes(Ue.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),d.batchParticipantsOnStart||this._setParticipantsStatus(i,Y.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return c(this,null,function*(){var e;if(this._state!=="IDLE")throw m.log(g.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",o.debug("Decline incoming call"),this._logWithMediaSettings(g.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=j.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(M.REJECTED)),this._close(new O(M.REJECTED))})}hangup(){return c(this,null,function*(){o.debug("Hangup");let e=this._state==="ACTIVE"?M.HUNGUP:M.CANCELED;m.log(g.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new O(e))):T.onHangup(new O(M.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return c(this,null,function*(){if(!this._signaling.ready){this._close(new O(M.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=M.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(E.composeId(n),n,r)})}removeParticipant(e,t=!1){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let n of e)(n.state===j.CALLED||n.state===j.ACCEPTED)&&(this._transport.isAllocated(n.id)||this._transport.allocate(n.id,t)),n.state===j.ACCEPTED&&i.push(n.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&o.error(t,e),o.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(M.FAILED):m.log(g.ERROR,e.hangup),B._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([M.CANCELED,M.NOT_FRIENDS,M.CALLEE_IS_OFFLINE,M.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===M.REJECTED&&!e.remote){T.onHangup(e,i),this.destroy();return}if(e.hangup===M.HUNGUP&&(!e.remote||this._participantState===j.CALLED)){T.onHangup(e,i),this.destroy();return}if(e.hangup===M.MISSED&&!e.remote){T.onHangup(e,i),this.destroy();return}if(e.hangup===M.SOCKET_CLOSED&&B._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===M.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=j.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),m.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,T.onHangup(e||new O(M.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;o.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),m.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return c(this,null,function*(){let t=yield this._api.getConversationParams(e);o.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let s=r.urls.filter((p,l,h)=>h.indexOf(p)===l);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return d.iceServers=i,d.wssBase=t.endpoint,d.wssToken=t.token,t.client_type&&(d.clientType=t.client_type),t})}_startConversation(e,t,i,r,n="",s=!1,p=!1){return c(this,null,function*(){let l=E.uuid();o.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let h=r.includes(ce.VIDEO),R=yield this._api.startConversation(l,e,t,h,n,s,p);o.debug("Api.startConversation",R),yield this._getConversationParams(R.id);let y=yield this._connectSignaling(Ne.START,R);return yield this._setConversation(R,y,i),y})}_joinConversation(e){return c(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n,observedIds:s}=e;o.debug("Conversation: join",{conversationId:t,joinLink:n,observedIds:s});let p=i.includes(ce.VIDEO),l;if(t)l=yield this._api.joinConversation(t,p,r);else if(n)l=yield this._api.joinConversationByLink(n,p,s);else throw new O(M.UNKNOWN_ERROR);o.debug("Api.joinConversation",l),yield this._getConversationParams(l.id);let h=yield this._connectSignaling(Ne.JOIN,l);return yield this._setConversation(l,h,Le.JOINING),h})}_prepareConversation(r){return c(this,arguments,function*(e,t=Q.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let n=this._api.getUserId();if(!n)throw new O(M.UNKNOWN_ERROR);let p=(yield this._getConversationParams(e)).device_idx||0,l={id:e,peerId:i,endpoint:`${d.wssBase}?userId=${n}&entityType=${t}&deviceIdx=${p}&conversationId=${e}&token=${d.wssToken}`,is_concurrent:!1,p2p_forbidden:!1,device_idx:p},h=yield this._connectSignaling(Ne.ACCEPT,l);return B._current&&(B._current._participantState===j.ACCEPTED||B._current._participantState===j.CALLED)?(o.log("Push rejected (busy)"),m.log(g.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(M.BUSY),Promise.reject({hangup:M.BUSY})):(B._current&&(B._current.destroy(),B._current=null),yield this._setConversation(l,h,Le.INCOMING,t),h)})}_createParticipant(e){return c(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:fe(),participantState:{},state:j.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);if(e.externalId){let i=E.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(i,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return t})}_getParticipantId(e){return c(this,null,function*(){try{let t=E.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new O(M.NETWORK_ERROR),t),t}})}_setConversation(n,s,p){return c(this,arguments,function*(e,t,i,r=Q.USER){let l=t.conversation.participants.map(K=>K.id);yield this._api.prepareUserIds(l);let h=this._api.getUserId(),R=e.device_idx||0;if(!h){let K=(t.conversation.participants||[]).find(N=>E.comparePeerId(N.peerId,t.peerId));if(!K)throw new O(M.UNKNOWN_ERROR);h=Number(K.id),K.idType&&(r=K.idType),K.deviceIdx&&(R=K.deviceIdx),this._api.setUserId(h)}let y=E.composeParticipantId(h,r,R),W=yield this._getParticipantId(y);this._conversation={userId:h,compositeUserId:y,externalId:W,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||Ie.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),m.log(g.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new O(M.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||Ie.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new oi;return this.subscribe(e,ve.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,ve.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new Tt(e),e}_connectSignaling(e,t){return c(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,_e.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,_e.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,_e.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return c(this,null,function*(){if(!!this._conversation)for(let t of e){let i=E.composeId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),T.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===j.HUNGUP||t.state===j.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],M.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&me.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:fe(t.mediaSettings),participantState:E.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?Y.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),T.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){E.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(zt.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Ri(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new Ht,this.subscribe(this._transport,w.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,w.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,w.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,w.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,w.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,w.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,w.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,w.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,w.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,w.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,w.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,w.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Le.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===j.ACCEPTED||t.state===j.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new Pi(this._transport),this.subscribe(this._volumesDetector,Ye.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Mi(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,bi.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Gt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Kt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=C.getCameras().length,t=C.getMicrophones().length;o.debug("Cameras: "+e+(C.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(C.hasMicrophonePermission()?"✔":"✖")),m.log(g.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){m.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===j.CALLED||e.state===j.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===M.HUNGUP?this._setParticipantsStatus([e],Y.HANGUP):this._setParticipantsStatus([e],Y.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Te.CAMERA,stopStream:!0}]),delete this._participants[e.id],T.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){o.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return c(this,null,function*(){o.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===j.ACCEPTED||r.state===j.CALLED)){o.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&me.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:fe(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],Y.WAITING),i?(r.state=j.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=j.CALLED,this._transport.allocate(r.id,!0),m.log(g.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){o.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=ja;i++){let r=E.compose(e,i),n=this._participants[r];n&&t.push(n)}if(!t.length){o.warn(`Participant [${e}] isn't in conversation`);return}if(this._transport)for(let i of t)this._transport.close(i.id);m.log(g.REMOVE_PARTICIPANT)}changeDevice(e){return c(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new Tt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(Z.UNKNOWN)})}toggleScreenCapturing(e){return c(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(Z.UNKNOWN)})}setVideoStream(e,t=!1){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return c(this,null,function*(){if(this._mediaSource)return m.log(g.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return c(this,null,function*(){if(this._mediaSource)return m.log(g.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return c(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let n=typeof r.uid=="object"?r.uid:me.fromId(r.uid),s=me.toString(n);i[s]=r.priority}for(let r of Object.values(this._participants)){let n=me.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return c(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return c(this,null,function*(){let t={};return t[Ve(e)]="kf",this._signaling.updateDisplayLayout(t)})}updateDisplayLayout(e){return c(this,null,function*(){if(e.length<1||!this._signaling.ready)return;o.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:me.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(n);if(!s){let R=me.toString(n);o.log(`Unknown participant external ID ${R}`);continue}let p=E.compose(s,n.deviceIdx),l=Ve({participantId:p,mediaType:r.mediaType,streamName:r.streamName}),h=this._participants[p];h&&(h.lastRequestedLayouts[l]=r),B._isStopStreaming(r)?this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now()):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&d.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=B._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>d.videoTracksCount;){let r=i.next();if(r.done){o.error("Cannot accommodate all streaming requests: tracks available "+d.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]=B._layoutToString({stopStream:!0})}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(o.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Et(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Te.STREAM||i.mediaType===Te.SCREEN)?T.onRemoteLive(r.externalId,i.streamName,null):T.onRemoteStream(r.externalId,null),m.log(g.PAT_DEALLOCATED)):o.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return c(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,n]of Object.entries(t.errorCodeByParticipantId||{})){let s=Et(r),p=this._participants[s.participantId];if(p){let l;typeof n!="number"?(o.warn(`Unexpected error code ${n} received for participant ${s.participantId}`),l=ar.UNKNOWN_ERROR):l=nr(n),i.push({externalId:p.externalId,errorReason:l})}}if(i&&i.length)throw new $t("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+Wa>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=B._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(B._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),t}_onParticipantSourcesUpdate(e){if(this._conversation){o.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return c(this,null,function*(){o.log("Promoted in waiting hall",!e.demote),e.demote?(o.log("Kicked from waiting hall"),this._close(new O(M.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return c(this,arguments,function*(e,t=0,i=[]){o.log(`Chat room updated: ${e}`);let n=[],s=[];i.length&&(i.forEach(p=>{if(p.externalId){let l=ue.fromSignaling(p.externalId);n.push(l),this._api.cacheExternalId(p.id.id,l)}else s.push(E.decomposeId(p.id.id).id)}),s.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(s))),T.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var p,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===Te.SCREEN)return;let i=Ve(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){o.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),m.log(g.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let h=t.participantId,R=this._participants[h];if(!R){m.log(g.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${h}`);return}let y=this._streamByStreamId.get(n);if(!y){m.log(g.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}m.log(g.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let W=(p=e.participantStreamDescription)==null?void 0:p.mediaType;if(W===Te.STREAM||W===Te.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&T.onRemoteLive(R.externalId,e.participantStreamDescription.streamName,y);else{let K=(d.producerScreenTrack?null:R.secondStream)||y;T.onRemoteStream(R.externalId,K)}}else{o.debug(`Waiting for ${s} until stream ${n} for ${i} is switched`);let h=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,h)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Ve(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Ve(i)))return i}else{let i={participantId:t,mediaType:Te.CAMERA};if(this._streamIdByStreamDescription.has(Ve(i)))return i;let r={participantId:t,mediaType:Te.SCREEN};if(this._streamIdByStreamDescription.has(Ve(r)))return r}return o.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?E.includesOneOf(this._conversation.roles,[ze.ADMIN,ze.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!E.includesOneOf(this._conversation.roles,[ze.ADMIN,ze.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return c(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return c(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return c(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=$i(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return c(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Vr(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let s=n.participants||[],p=[],l=[],h=null;return s.length&&(s.forEach(R=>{if(R.externalId){let y=ue.fromSignaling(R.externalId);p.push(y),this._api.cacheExternalId(R.id.id,y)}else l.push(E.decomposeId(R.id.id).id)}),l.length&&!p.length&&(p=yield this._api.getExternalIdsByOkIds(l)),n.hasMore&&(h=Br(s[s.length-1].id))),{participants:p,pageMarker:h,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return c(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return c(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return c(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return c(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return c(this,null,function*(){var p;let n={movieId:e,participantId:(p=this._conversation)==null?void 0:p.compositeUserId};(t||t===0)&&(n.gain=t),i&&(n.offset=i),typeof r!==void 0&&(n.pause=r);let s=yield this._signaling.updateMovie(n);if(s.error)throw new Error(s.error)})}removeMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",n=null){return c(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},p=yield this._signaling.startStream(s);return p.error?Promise.reject(p.message):p})}stopStream(){return c(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return c(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return c(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return c(this,null,function*(){var r;if(e<d.videoMinWidth||t<d.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<d.videoMinWidth||i.effect.height<d.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");d.videoEffectMaxHeight=i.effect.height,d.videoEffectMaxWidth=i.effect.width}return d.videoMaxWidth=e,d.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return c(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return c(this,null,function*(){var t,i;!this._conversation||(o.debug("Local media stream changed",e.mediaSettings),T.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return c(this,null,function*(){var t,i;if(o.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;T.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){o.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&T.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){o.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&(d.participantStateMapped?T.onRemoteParticipantState(i.externalId,i.participantState):T.onRemoteParticipantState(i.externalId,E.mapLegacyParticipantState(i.participantState))))}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(o.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),T.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case A.ACCEPTED_CALL:return this._onAcceptedCall(e);case A.HUNGUP:return this._onHungup(e);case A.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case A.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case A.CLOSED_CONVERSATION:return this._onClosedConversation(e);case A.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case A.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case A.RATE_CALL_DATA:return this._onNeedRate();case A.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case A.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case A.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case A.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case A.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case A.REGISTERED_PEER:return this._onPeerRegistered(e);case A.SWITCH_MICRO:return this._onMicSwitched(e);case A.CHAT_MESSAGE:return this._onChatMessage(e);case A.CUSTOM_DATA:return this._onCustomData(e);case A.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case A.RECORD_STOPPED:return this._onRecordInfo(null);case A.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case A.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case A.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case A.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case A.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case A.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case A.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return c(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let s=E.composeId(n),p=n.roles||[];if(s===this._conversation.compositeUserId){t=fe(n.mediaSettings),ut(this._conversation.roles,p)||this._onRolesChanged(s,p);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let h=fe(n.mediaSettings);_r(h,l.mediaSettings)||this._changeRemoteMediaSettings(s,h);let R=E.mapParticipantState(n),y=l.participantState;E.isEqualParticipantState(R,y)||this._changeRemoteParticipantState(s,R),ut(p,l.roles)||this._onRolesChanged(l.id,p)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],M.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){o.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return c(this,null,function*(){let t=E.composeMessageId(e),i=E.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new O(M.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:fe(e.mediaSettings)}),r=this._participants[t]),r.state=j.ACCEPTED,r.mediaSettings=fe(e.mediaSettings),this._logWithMediaSettings(g.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Le.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){o.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=E.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new O(e.reason,{remote:!0}));return}let i=this._participants[t];if(!i){o.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===M.REJECTED?j.REJECTED:j.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,M.HUNGUP)}_onAddedParticipant(e){return c(this,null,function*(){var r,n;o.debug(`Participant added [${e.participantId}]`);let t=E.composeMessageId(e),i=this._participants[t];if(i&&i.state!==j.HUNGUP&&i.state!==j.REJECTED){o.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&me.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:fe(e.participant.mediaSettings),state:e.participant.state,participantState:E.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=j.CALLED,i.mediaSettings=fe((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=E.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],Y.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return c(this,null,function*(){var r,n;o.debug(`Participant joined [${e.participantId}]`);let t=E.composeMessageId(e),i=this._participants[t];if(i&&i.state===j.ACCEPTED){o.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&me.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:fe(e.participant.mediaSettings),state:e.participant.state,participantState:E.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Le.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=j.ACCEPTED,i.mediaSettings=fe(e.mediaSettings),i.participantState=E.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],Y.CONNECTED):this._setParticipantsStatus([i],Y.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((n=this._conversation)==null?void 0:n.observer))),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new O(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=E.composeMessageId(e);this._changeRemoteMediaSettings(t,fe(e.mediaSettings))}_onParticipantStateChanged(e){let t=E.composeMessageId(e);this._changeRemoteParticipantState(t,E.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),T.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return c(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=fe(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),d.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Ii(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=Ii(this._serverSettings,r),o.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=E.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return c(this,null,function*(){T.onDeviceSwitched(ce.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return c(this,null,function*(){let t=E.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),T.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return c(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=E.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),T.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return c(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getParticipantId(e.initiator);T.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else T.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!ut(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,T.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!ut(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,T.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return c(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){o.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let p=this._participants[e.participantId];p&&(o.debug(`Mute states for participant [${e.participantId}] changed`,i),T.onMuteStates(i,r,n,e.muteAll,e.unmute,p.externalId,s==null?void 0:s.externalId));return}E.isObjectsEquals(this._conversation.muteStates,i)&&E.isArraysEquals(this._conversation.unmuteOptions,r)&&!n.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(n,e.muteAll,e.unmute,t,s)))})}_processMuteState(){return c(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==j.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),p=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),h=Object.entries(s);for(let[R,y]of h)if(!(y!==Ue.MUTE&&y!==Ue.MUTE_PERMANENT)&&(this._isCallAdmin()&&y===Ue.MUTE_PERMANENT&&(s[R]=Ue.MUTE),!(!e.includes(R)||i)))switch(R){case ce.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(T.onDeviceSwitched(ce.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case ce.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(T.onDeviceSwitched(ce.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case ce.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(T.onDeviceSwitched(ce.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}T.onMuteStates(s,p,e,t,i,null,n==null?void 0:n.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?T.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&T.onLocalPin(!0)),this._participants[e]?T.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&T.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!Ki(this._conversation.options,e)&&(this._conversation.options=e,T.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let n;if(i===this._conversation.compositeUserId||i==="")n=this._conversation.networkRating;else if(this._participants[i])n=this._participants[i].networkRating;else continue;if(n!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,T.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;o.log("Received network status update: ",e),T.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){T.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,d.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){o.error("Received remote stream notification for a participant that has no track associated with it",r);return}let n=this._streamIdByStreamDescription.get(r);if(!n||this._streamWaitTimerByStreamDescription.has(r)){o.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(n);if(!s){m.log(g.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}T.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&T.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===Ie.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Wi.ADD_PARTICIPANT);T.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&T.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}T.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(T.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return c(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===L.CONNECTED?i=Y.CONNECTED:t===L.CONNECTING||t===L.OPENED?i=Y.CONNECTING:t===L.RECONNECTING&&(i=Y.RECONNECT),!i)return;let r=e.reduce((n,s)=>{if(s in this._participants){let p=this._participants[s];n.push(p),t===L.CONNECTED&&(p.remoteStream||(p.mediaSettings&&this._changeRemoteMediaSettings(s,p.mediaSettings),this._changeRemoteParticipantState(s,p.participantState)),this._updateDisplayLayoutFromCache(s))}else o.warn(`Participant [${s}] isn't in conversation`);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return c(this,null,function*(){o.debug(`Local transport state has changed: ${e}`),e===L.CONNECTED&&T.onLocalStatus(Y.CONNECTED),e===L.CONNECTING&&T.onLocalStatus(Y.CONNECTING),e===L.RECONNECTING&&T.onLocalStatus(Y.RECONNECT),e===L.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(M.FAILED)),this._close(new O(M.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return c(this,null,function*(){if(e.endsWith(be.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))o.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{o.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(o.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],Y.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(T.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===le.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;T.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),d.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(o.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case le.audio:this._removeAudioTrack(e,t,i);break;case le.video:case le.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==be.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onRemoteActivityNoSignal(){this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)}_onTopologyChanged(e){this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let n=this._participants[r];e||this._lastStalled[r]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,Y.RECONNECT),i.length&&this._setParticipantsStatus(i,Y.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let s=this._participants[n];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let s=this._participants[n];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,Y.RECONNECT),r.length&&this._setParticipantsStatus(r,Y.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!C.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),T.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return c(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==Ie.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,s)=>(s.status!==t&&(s.status=t,d.batchParticipantsOnStart?n.push(s.externalId):T.onParticipantStatus(s.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&T.onRemoteStatus(r,t,i)}},k=B;k._delayedHangup=!1;var $t=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,$t.prototype),this.participantErrors=t}};var qt;function Ka(){return c(this,null,function*(){var a;if(d.apiEnv!=="AUTO")return d.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(a=i==null?void 0:i.Answer[0])==null?void 0:a.data;if(!r)throw new Error("Wrong DNS response");return o.debug("Resolved API endpoint",r),r}catch(e){return o.warn("Failed to resolve API endpoint using DNS, default is used",e),d.apiEndpoint}})}function Wr(){if(!d.apiKey)throw new O(Z.API,{message:"Required argument apiAppKey not passed"})}function Di(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Kr(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${qt}/fb.do`,r)}function jr(i){return c(this,arguments,function*(a,e={},t=!1){qt||(qt=yield Ka());let r=Kr(a,e,t);return $a(r)})}function $a(a){return c(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${qt}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(n){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(a)})})}function Kr(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=d.apiKey),t||(X.sessionKey?e.session_key=X.sessionKey:X.accessToken&&(e.access_token=X.accessToken));for(let[r,n]of Object.entries(e))typeof n=="object"&&(e[r]=JSON.stringify(n));let i="";for(let[r,n]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(n)}`;return i}var Ja=10,Ya=700,za=3e3,Jt=class extends dt{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return c(this,arguments,function*(e,t={},i=!1){let n=s=>c(this,null,function*(){try{return yield jr(e,t,i)}catch(p){if(!p.hasOwnProperty("error_msg")&&(s++,o.debug(`${e} network error, attempt ${s}...`),s<Ja))return yield E.delay(Math.min(s*Ya,za)),n(s);throw o.warn(e,"error",p),p}});return n(0)})}_call(r){return c(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){o.warn("Api call error",n);let s=Z.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=M.SERVICE_DISABLED;break;case 1102:s=M.CALLEE_IS_OFFLINE;break;case 1103:s=M.NOT_FRIENDS;break;case 1104:case 1106:s=M.EXTERNAL_API_ERROR;break}throw new O(s,{message:n.error_msg,code:n.error_code})}})}userId(e){return c(this,null,function*(){let t=E.decomposeId(e).id;return X.isEmpty()?ue.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),ue.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return c(this,null,function*(){X.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return c(this,null,function*(){if(!this._uuid){let t=Be.get("uuid");t||(t=E.uuid(),Be.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:d.appVersion,client_type:"SDK_JS"}};return d.authToken&&(e.session_data.auth_token=d.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),X.sessionKey=t.session_key,X.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&T.onTokenExpired(),new O(Z.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${d.appName}:${d.sdkVersion}`,platform:d.platform,items:e})};Di("log.externalLog",t)}init(){Wr()}joinConversation(e,t=!1,i){return c(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:d.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return c(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1};return t&&(r.payload=t),d.domain&&(r.domainId=d.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,n="",s=!1,p=!1){return c(this,null,function*(){let l={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case xe.USER:l.uids=t.join(",");break;case xe.GROUP:l.gid=t[0];break;case xe.CHAT:l.chatId=t[0];break}return s&&(l.createJoinLink=!0),n&&(l.payload=n),d.domain&&(l.domainId=d.domain),p&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return c(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return c(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return c(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return c(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i){return c(this,null,function*(){let r={joinLink:e,isVideo:t,protocolVersion:d.protocolVersion};return(i==null?void 0:i.length)&&(r.observedIds=i.join(",")),d.anonymToken&&(r.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",r)})}getOkIdsByExternalIds(e){return c(this,null,function*(){let t=ue.fromIds(e),i=[],r={methods:[]},n=[],s=Object.keys(this._externalUidsCache),p=Object.values(this._externalUidsCache);for(let h of t){let R=ue.toString(h),y=p.indexOf(R);y>-1?i.push(Number(s[y])):(n.push(R),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:h.id,anonym:h.type===nt.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((h,R)=>{if(h.ok){let y=Number(h.ok.ok_id);this._externalUidsCache[y]=n[R],i.push(y)}}),i})}getExternalIdsByOkIds(e){return c(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(ue.fromString(this._externalUidsCache[n])):i.push(n);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let n of i)r.hasOwnProperty(n)&&t.push(ue.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=ue.toString(e),n=i.indexOf(r);return n>-1?E.composeUserId(t[n],Q.USER):null}cacheExternalId(e,t){let i=E.decomposeId(e).id;this._externalUidsCache[i]=ue.toString(t)}getConversationParams(e){return c(this,null,function*(){let t={};return d.anonymToken&&(t.anonymToken=d.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:M.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),Di("vchat.hangupConversation",t)}removeHistoryRecords(e){return c(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return c(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,n]of Object.entries(i.external_ids))t[r]=ue.fromIdToString(n,nt.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=ue.fromIdToString(n,nt.ANONYM);return t}catch(i){return t}})}};var $r=(_=>(_.RECOVER="recover",_.ACCEPT_CALL="accept-call",_.ADD_PARTICIPANT="add-participant",_.REMOVE_PARTICIPANT="remove-participant",_.HANGUP="hangup",_.TRANSMIT_DATA="transmit-data",_.ACCEPT_PRODUCER="accept-producer",_.ALLOCATE_CONSUMER="allocate-consumer",_.CHANGE_MEDIA_SETTINGS="change-media-settings",_.CHANGE_PARTICIPANT_STATE="change-participant-state",_.CHANGE_STREAM_PRIORITIES="change-streams-priorities",_.UPDATE_DISPLAY_LAYOUT="update-display-layout",_.REPORT_PERF_STAT="report-perf-stat",_.RECORD_START="record-start",_.RECORD_STOP="record-stop",_.RECORD_SET_ROLE="record-set-role",_.RECORD_GET_STATUS="record-get-status",_.SWITCH_MICRO="switch-micro",_.SWITCH_TOPOLOGY="switch-topology",_.REQUEST_REALLOC="request-realloc",_.CHAT_MESSAGE="chat-message",_.CHAT_HISTORY="chat-history",_.CUSTOM_DATA="custom-data",_.GRANT_ROLES="grant-roles",_.MUTE_PARTICIPANT="mute-participant",_.PIN_PARTICIPANT="pin-participant",_.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",_.CHANGE_OPTIONS="change-options",_.GET_WAITING_HALL="get-waiting-hall",_.PROMOTE_PARTICIPANT="promote-participant",_.REQUEST_TEST_MODE="request-test-mode",_.ADD_MOVIE="add-movie",_.UPDATE_MOVIE="update-movie",_.REMOVE_MOVIE="remove-movie",_))($r||{}),H=$r;var qr="open",Jr=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0,()=>d.movieShare],Qa=10,Re=class extends lt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+d.platform+"&appVersion="+d.appVersion+"&version="+d.protocolVersion+"&device="+d.device+"&capabilities="+Re._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null}static _getCapabilityFlags(){let e=0;for(let t=0;t<Jr.length;t++)Jr[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return c(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){m.log(g.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return c(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=E.decomposeParticipantId(t.participantId),s=E.decomposeId(n.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),n.deviceIdx&&(t.deviceIdx=n.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return c(this,arguments,function*(e,t={},i=0){let n=s=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===qr&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){m.log(g.SOCKET_ACTION,"not_opened"),o.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(m.log(g.SOCKET_ACTION,"invalid_state"),o.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,p)=>{let l=(R,y=!1)=>{!i||y?p(R):(o.debug("Resending a signaling message",e,h.sequence),i--,n(h))},h={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};n(h)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return c(this,null,function*(){return this._send(H.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return c(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return c(this,null,function*(){return this._send(H.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return c(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return c(this,null,function*(){return this._send(H.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return c(this,null,function*(){return this._send(H.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},Qa)})}changeParticipantState(e){return c(this,null,function*(){return this._send(H.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return c(this,null,function*(){return this._send(H.ADD_PARTICIPANT,Bi({participantId:e},t))})}removeParticipant(e,t=!1){return c(this,null,function*(){return this._send(H.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return c(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(H.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return c(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(H.ACCEPT_PRODUCER,i)})}changePriorities(e){return c(this,null,function*(){return this._send(H.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return c(this,null,function*(){return this._send(H.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return c(this,null,function*(){return this._send(H.ADD_MOVIE,e)})}updateMovie(e){return c(this,null,function*(){return this._send(H.UPDATE_MOVIE,e)})}removeMovie(e){return c(this,null,function*(){return this._send(H.REMOVE_MOVIE,e)})}startStream(e){return c(this,null,function*(){return this._send(H.RECORD_START,e)})}stopStream(){return c(this,null,function*(){return this._send(H.RECORD_STOP)})}recordSetRole(e,t){return c(this,null,function*(){return this._send(H.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return c(this,null,function*(){return this._send(H.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return c(this,null,function*(){return this._send(H.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return c(this,null,function*(){return this._send(H.REQUEST_REALLOC)})}reportPerfStat(e){return c(this,null,function*(){return this._send(H.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return c(this,null,function*(){return this._send(H.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return c(this,null,function*(){return this._send(H.CHAT_HISTORY,{count:e})})}customData(e,t){return c(this,null,function*(){return this._send(H.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return c(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(H.GRANT_ROLES,r)})}muteParticipant(e,t,i){return c(this,null,function*(){return this._sendRaw(H.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return c(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(H.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return c(this,null,function*(){return this._send(H.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return c(this,null,function*(){return this._send(H.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return c(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(H.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return c(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(H.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ne.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),o.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){o.debug("Socket opened"),m.log(g.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){m.log(g.SOCKET_ACTION,"parse_error"),o.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(o.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(_e.RECONNECT,e),e.conversation.topology&&this._triggerEvent(_e.NOTIFICATION,{type:"notification",notification:A.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(_e.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(m.log(g.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(m.log(g.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new O(M.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(_e.NOTIFICATION,{notification:A.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new O(Z.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(m.log(g.SOCKET_ACTION,"unknown_message"),o.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(_e.FAILED,e)}_onError(e){m.log(g.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){m.log(g.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Re.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(Re.RECONNECT_MAX_DELAY,Re.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),m.log(g.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ne.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],m.log(g.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Re.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),n=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==qr){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}Re._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Re.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(n))}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Re.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(n))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new O(Z.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Re.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{o.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Ne.RETRY)},Re.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},we=Re;we.RECONNECT_DELAY=d.signalingReconnectDelay,we.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,we.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,we.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,we.WAIT_RESPONSE_DELAY=d.waitResponseDelay,we.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var Yr=(t=>(t.KING="KING",t.PAWN="PAWN",t))(Yr||{}),Xa=Yr;var ot,re,Rt=null,Pu={getCameras:C.getCameras,getMicrophones:C.getMicrophones,getOutput:C.getOutput,hasCamera:C.hasCamera,hasMicrophone:C.hasMicrophone,getSavedCamera:C.getSavedCamera,getSavedMicrophone:C.getSavedMicrophone,getSavedOutput:C.getSavedOutput,hasCameraPermission:C.hasCameraPermission,hasMicrophonePermission:C.hasMicrophonePermission,hasPermissions:C.hasPermissions,getUserMedia:C.getUserMedia,getUserVideo:C.getUserVideo,getUserAudio:C.getUserAudio,saveDeviceId:C.saveDeviceId,isBrowserSupported:C.isBrowserSupported,isScreenCapturingSupported:C.isScreenCapturingSupported,os:C.os,isMobile:C.isMobile,browserName:C.browserName,browserVersion:C.browserVersion,baseChromeVersion:C.baseChromeVersion,getAudioContext:C.getAudioContext};function Za(a){re=a}function en(a){ot=a}function bu(a){Rt=a}function Mu(a){d.videoEffects=a}function Du(a){return c(this,null,function*(){if(d.set(a),C.browserName()==="Sferum"&&(d.platform=`SFERUM:${C.browserVersion()}`),re||Za(new Jt),ot||en(()=>new we),d.debug&&(zr.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${d.sdkVersion}`,a),yield C.init(),!C.isBrowserSupported())throw new O(Z.UNSUPPORTED);re.init()})}function Au(n){return c(this,arguments,function*(a,e=[ce.AUDIO],t="",i=!1,r=!1){let s=[],p=[];if(Array.isArray(a)?s=a.length?a:[]:a&&(s=[a]),s.length&&(p=yield re.getOkIdsByExternalIds(s),!p.length))throw new O(M.CALLEE_IS_OFFLINE);return tn(p,xe.USER,e,t,i,r)})}function tn(s){return c(this,arguments,function*(a,e=xe.USER,t,i="",r=!1,n=!1){if(k.current())throw o.error("There is already active call"),new O(M.FAILED);return new k(re,ot(),Rt).onStart(a,e,t,i,r,n)})}function Ou(a){return c(this,null,function*(){return rn(a)})}function rn(i){return c(this,arguments,function*(a,e=Q.USER,t){if(a===k.id())throw new Error("Push has already been processed");return new k(re,ot(),Rt).onPush(a,e,t)})}function ku(a){return c(this,null,function*(){return a&&(d.authToken=a),re.authorize()})}function wu(){return c(this,arguments,function*(a=[ce.AUDIO]){let e=k.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function xu(){return c(this,null,function*(){let a=k.current();if(a)return a.decline()})}function Nu(t){return c(this,arguments,function*(a,e=[ce.AUDIO]){return an(a,e)})}function an(a,e,t){return c(this,null,function*(){if(k.current())throw o.error("There is already active call"),new O(M.FAILED);return new k(re,ot(),Rt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function Lu(r){return c(this,arguments,function*(a,e=[ce.AUDIO],t,i){if(k.current())throw o.error("There is already active call"),new O(M.FAILED);return t&&(d.anonymToken=t),new k(re,ot(),Rt).onJoin({joinLink:a,mediaOptions:e,observedIds:i})})}function Uu(){return c(this,null,function*(){let a=k.current();if(a)return a.hangup();k.hangupAfterInit()})}function Bu(a,e){return c(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return nn(t[0],e)})}function nn(a,e){return c(this,null,function*(){let t=k.current();t&&(yield t.addParticipant(E.composeUserId(a,Q.USER),e))})}function Vu(a,e=!1){return c(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);return sn(t[0],e)})}function sn(a,e=!1){return c(this,null,function*(){let t=k.current();t&&(yield t.removeParticipant(E.composeUserId(a,Q.USER),e))})}function Fu(a,e){return c(this,null,function*(){let t=yield C.saveDeviceId(a,e),i=k.current();return t&&i?i.changeDevice(a):Promise.reject()})}function Hu(a){return c(this,null,function*(){let e=k.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function Gu(a,e=!1){return c(this,null,function*(){let t=k.current();t&&(yield t.setVideoStream(a,e))})}function Wu(a){return c(this,null,function*(){let e=k.current();e&&(yield e.toggleLocalVideo(a))})}function ju(a){return c(this,null,function*(){let e=k.current();e&&(yield e.toggleLocalAudio(a))})}function Ku(a,e,t){return c(this,null,function*(){let i=k.current();if(i)return i.setLocalResolution(a,e,t)})}function $u(a){return c(this,null,function*(){let e=k.current();e&&(yield e.changePriorities(a))})}function qu(a){return c(this,null,function*(){let e=k.current();e&&(yield e.changeParticipantState(a))})}function Ju(a){return c(this,null,function*(){let e=k.current();e&&(yield e.updateDisplayLayout(a))})}function Yu(a,e,t=!1){return c(this,null,function*(){let i=yield re.getOkIdsByExternalIds([a]);return on(i[0],e,t)})}function on(a,e,t=!1){return c(this,null,function*(){let i=k.current();i&&(yield i.grantRoles(E.composeUserId(a,Q.USER),e,t))})}function zu(){return c(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield re.getOkIdsByExternalIds([a]))[0]),cn(i,e,t,me.getDeviceIdx(a))})}function cn(){return c(this,arguments,function*(a=null,e,t=[],i=0){let r=k.current();if(r){let n=a?E.composeParticipantId(a,Q.USER,i):null;yield r.muteParticipant(n,e,t)}})}function Qu(a,e=!1){return c(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);return dn(t[0],e,me.getDeviceIdx(a))})}function dn(a,e=!1,t=0){return c(this,null,function*(){let i=k.current();i&&(yield i.pinParticipant(E.composeParticipantId(a,Q.USER,t),e))})}function Xu(a){return c(this,null,function*(){let e=k.current();e&&(yield e.updateMediaModifiers(a))})}function Zu(a){return c(this,null,function*(){let e=k.current();e&&(yield e.changeOptions(a))})}function em(a,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield re.getOkIdsByExternalIds([e]))[0]),pn(a,t)})}function pn(a,e=null){return c(this,null,function*(){let t=k.current();if(t){let i=e?E.composeUserId(e,Q.USER):null;yield t.chatMessage(a,i)}})}function tm(a=10){return c(this,null,function*(){let e=k.current();if(e)return e.chatHistory(a)})}function im(a,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield re.getOkIdsByExternalIds([e]))[0]),ln(a,t,me.getDeviceIdx(e))})}function ln(a,e=null,t=0){return c(this,null,function*(){let i=k.current();if(i){let r=e?E.composeParticipantId(e,Q.USER,t):null;yield i.customData(a,r)}})}function rm(a="",e=!1){return c(this,null,function*(){return(yield re.createConversation(E.uuid(),a,e)).join_link})}function am(){return c(this,null,function*(){let a=k.current();return a?a.createJoinLink():Promise.reject()})}function nm(){return c(this,null,function*(){let a=k.current();return a?a.removeJoinLink():Promise.reject()})}function sm(a,e){return c(this,null,function*(){return re.getAnonymTokenByLink(a,e)})}function om(a){let e=k.current();e&&e.setVolume(a)}function cm(a){d.forceRelayPolicy=a}function dm(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return c(this,null,function*(){let n=k.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function pm(){return c(this,null,function*(){let a=k.current();return a?a.stopStream():Promise.reject()})}function lm(a,e){return c(this,null,function*(){let t=k.current();if(t){let i=yield re.getOkIdsByExternalIds([a]),r=me.getDeviceIdx(a);return t.recordSetRole(E.composeParticipantId(i[0],Q.USER,r),e)}return Promise.reject()})}function um(){return c(this,null,function*(){let a=k.current();return a?a.getStreamInfo():Promise.reject()})}function mm(a){return c(this,null,function*(){let e=k.current();return e?e.addMovie(a):Promise.reject()})}function hm(a,e,t,i){return c(this,null,function*(){let r=k.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function _m(a){return c(this,null,function*(){let e=k.current();return e?e.removeMovie(a):Promise.reject()})}function gm(a){d.statisticsInterval=a;let e=k.current();if(e)return e.updateStatisticsInterval()}function fm(a){zr.disableLog(!a),o.toggle(a)}function Sm(a,...e){!d.debugLog||o.send(a,"[external]",...e)}function vm(a){return c(this,null,function*(){let e=k.current();if(e)return e.videoEffect(a)})}function Em(a){return c(this,null,function*(){let e=k.current();e&&(yield e.setAudioStream(a))})}function Tm(a=null,e,t=!1){return c(this,null,function*(){let i=k.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(a,e,t)})}function Im(a,e=!1){return c(this,null,function*(){let t=k.current();if(!t)throw new Error("Conversation not found");let i=yield re.getOkIdsByExternalIds([a]);return t.promoteParticipant(E.composeUserId(i[0],Q.USER),e)})}function Cm(a){return c(this,null,function*(){yield re.removeHistoryRecords(a)})}export{Jt as Api,dt as BaseApi,pt as BaseLogger,lt as BaseSignaling,Le as CallDirection,xe as CallType,zt as ChatRoomEventType,Qt as ConversationOption,Nr as DebugMessageType,nt as ExternalIdType,Ir as FacingMode,Z as FatalError,O as HangupReason,M as HangupType,ce as MediaOption,le as MediaTrackKind,Te as MediaType,Ue as MuteState,j as ParticipantState,Y as ParticipantStatus,Xa as RecordRole,we as Signaling,H as SignalingCommandType,Ne as SignalingConnectionType,A as SignalingNotification,ze as UserRole,Q as UserType,E as Utils,wu as acceptCall,mm as addMovie,Bu as addParticipant,nn as addParticipantInternal,ku as authorize,Pu as browser,tn as callInternal,Au as callTo,Hu as captureScreen,Zu as changeConversationOptions,Fu as changeDevice,qu as changeParticipantState,$u as changePriorities,vm as changeVideoEffect,tm as chatHistory,em as chatMessage,pn as chatMessageInternal,am as createJoinLink,im as customData,ln as customDataInternal,fm as debug,Sm as debugMessage,xu as declineCall,cm as forceRelayPolicy,sm as getAnonymTokenByLink,um as getStreamInfo,Tm as getWaitingHall,Yu as grantRoles,on as grantRolesInternal,Uu as hangup,Du as init,Nu as joinCall,Lu as joinCallByLink,an as joinCallInternal,zu as muteParticipant,cn as muteParticipantInternal,Qu as pinParticipant,dn as pinParticipantInternal,Ou as processPush,rn as processPushInternal,Im as promoteParticipant,lm as recordSetRole,Cm as removeHistoryRecords,nm as removeJoinLink,_m as removeMovie,Vu as removeParticipant,sn as removeParticipantInternal,Za as setApi,Em as setAudioStream,Ku as setLocalResolution,bu as setLogger,Xu as setMediaModifiers,en as setSignalingFactory,gm as setStatisticsInterval,Mu as setVideoEffects,Gu as setVideoStream,om as setVolume,rm as startConversation,dm as startStream,pm as stopStream,ju as toggleLocalAudio,Wu as toggleLocalVideo,Ju as updateDisplayLayout,hm as updateMovie};
7
+ var na=Object.defineProperty;var Gi=Object.getOwnPropertySymbols;var sa=Object.prototype.hasOwnProperty,oa=Object.prototype.propertyIsEnumerable;var Wi=Math.pow,ji=(n,e,t)=>e in n?na(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ki=(n,e)=>{for(var t in e||(e={}))sa.call(e,t)&&ji(n,t,e[t]);if(Gi)for(var t of Gi(e))oa.call(e,t)&&ji(n,t,e[t]);return n};var c=(n,e,t)=>new Promise((i,r)=>{var a=l=>{try{p(t.next(l))}catch(m){r(m)}},s=l=>{try{p(t.throw(l))}catch(m){r(m)}},p=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);p((t=t.apply(n,e)).next())});import ra from"webrtc-adapter";var ft=class{createJoinLink(e){return c(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return c(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return c(this,null,function*(){return""})}log(e){}prepareUserIds(e){return c(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return c(this,null,function*(){})}cleanup(){}};var St=class{log(e,t,i=!1){}destroy(){}};var q=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var vt=class extends q{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var $i=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))($i||{}),je=$i;var qi=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(qi||{}),He=qi;var Ji=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(Ji||{}),ai=Ji;var Yi=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(Yi||{}),zi=Yi;var Qi=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(Qi||{}),ni=Qi;function Xi(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}function Zi(n,e){let t=new Set(n);for(let[i,r]of Object.entries(e))r?t.add(i):t.delete(i);return Array.from(t)}var er=(H=>(H.CAMERA_PERMISSION="camera",H.MIC_PERMISSION="mic",H.CAMERA_ACCESS="cameralock",H.MIC_ACCESS="miclock",H.MIC_NOT_FOUND="nomic",H.SCREEN_PERMISSION="screenpermission",H.SCREEN_ACCESS="screenlock",H.CONNECTION="connection",H.NETWORK="network",H.UNKNOWN="unknown",H.UNSUPPORTED="unsupported",H.SIGNALING_FAILED="signalingfailed",H.API="api",H.AUTH="auth",H))(er||{}),re=er;var tr=(j=>(j.CANCELED="CANCELED",j.REJECTED="REJECTED",j.REMOVED="REMOVED",j.HUNGUP="HUNGUP",j.MISSED="MISSED",j.BUSY="BUSY",j.FAILED="FAILED",j.NETWORK_ERROR="NETWORK_ERROR",j.KILLED="KILLED",j.BANNED="BANNED",j.HAS_ACTIVE_CALL="HAS_ACTIVE_CALL",j.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",j.NOT_FRIENDS="NOT_FRIENDS",j.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",j.UNKNOWN_ERROR="UNKNOWN_ERROR",j.UNSUPPORTED="UNSUPPORTED",j.OLD_VERSION="OLD_VERSION",j.SERVICE_DISABLED="SERVICE_DISABLED",j.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",j.SOCKET_CLOSED="SOCKET_CLOSED",j.ENDED="ENDED",j.KILLED_WITHOUT_DELETE="KILLED_WITHOUT_DELETE",j))(tr||{}),P=tr;var ir=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(ir||{}),ue=ir;var rr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(rr||{}),Ke=rr;var ar=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(ar||{}),G=ar;var nr=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(nr||{}),Ge=nr;var sr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(sr||{}),ve=sr;var or=(A=>(A.TRANSMITTED_DATA="transmitted-data",A.ACCEPTED_CALL="accepted-call",A.HUNGUP="hungup",A.PARTICIPANT_ADDED="participant-added",A.PARTICIPANT_JOINED="participant-joined",A.CLOSED_CONVERSATION="closed-conversation",A.MEDIA_SETTINGS_CHANGED="media-settings-changed",A.PARTICIPANT_STATE_CHANGED="participant-state-changed",A.RATE_CALL_DATA="rate-call-data",A.FEATURE_SET_CHANGED="feature-set-changed",A.TOPOLOGY_CHANGED="topology-changed",A.PRODUCER_UPDATED="producer-updated",A.CONSUMER_ANSWERED="consumer-answered",A.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",A.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",A.SETTINGS_UPDATE="settings-update",A.VIDEO_QUALITY_UPDATE="video-quality-update",A.REGISTERED_PEER="registered-peer",A.SWITCH_MICRO="switch-micro",A.RECORD_STARTED="record-started",A.RECORD_STOPPED="record-stopped",A.REALLOC_CON="realloc-con",A.AUDIO_ACTIVITY="audio-activity",A.SPEAKER_CHANGED="speaker-changed",A.STALLED_ACTIVITY="stalled-activity",A.CHAT_MESSAGE="chat-message",A.CUSTOM_DATA="custom-data",A.ROLES_CHANGED="roles-changed",A.MUTE_PARTICIPANT="mute-participant",A.PIN_PARTICIPANT="pin-participant",A.OPTIONS_CHANGED="options-changed",A.NETWORK_STATUS="network-status",A.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",A.PROMOTE_PARTICIPANT="promote-participant",A.CHAT_ROOM_UPDATED="chat-room-updated",A.PROMOTION_APPROVED="promotion-approved",A.JOIN_LINK_CHANGED="join-link-changed",A.MOVIE_UPDATE_NOTIFICATION="movie-update-notification",A))(or||{}),O=or;var cr=(h=>(h.ERROR="callError",h.DEVICES="callDevices",h.CALL_SPEC_ERROR="callSpecError",h.ICE_CONNECTION_STATE="callIceConnectionState",h.ICE_CONNECTION_TYPE="callIceConnectionType",h.ICE_RESTART="callIceRestart",h.PUSH="callPush",h.OUTGOING_CALL="callStart",h.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",h.JOIN_CONVERSATION="callJoinConversation",h.ACCEPTED_OUTGOING="callAcceptedOutgoing",h.ACCEPT_INCOMING="callAcceptIncoming",h.DECLINE_INCOMING="callDeclineIncoming",h.ACCEPT_CONCURRENT="callAcceptConcurrent",h.HANGUP="callHangup",h.MEDIA_STATUS="callMediaStatus",h.DEVICE_CHANGED="callDeviceChanged",h.SOCKET_ACTION="callSocketAction",h.ADD_PARTICIPANT="callAddParticipant",h.REMOVE_PARTICIPANT="callRemoveParticipant",h.POOR_CONNECTION="callPoorConnection",h.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",h.RELAY_POLICY="callForceRelay",h.PAT_ALLOCATED="patAllocate",h.PAT_DEALLOCATED="patDeallocate",h.PAT_ERROR="patError",h.PAT_WAITING_TIME_ERROR="patWaitingTimeError",h.PAT_OUTDATED_RESPONSE="patOutdatedResponse",h))(cr||{}),_=cr;var dr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(dr||{}),we=dr;var pr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(pr||{}),lr=pr;function ur(n){switch(n){case 1:return"no-available-tracks";default:return"unknown-error"}}var mr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(mr||{}),rt=mr;function Et(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}var hr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(hr||{}),X=hr;var si=class{constructor(){this._items=[]}get length(){return this._items.length}push(e){this._items.push(e)}shift(){return this._items.shift()||null}bisect(){let e=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(e)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(e,t)=>t instanceof Error?String(t):t):""}};var _r=2*1024*1024,ca=512*1024,Tt=100*1024,da=5,oi="_okcls_logs_session_",pa=3e4,gr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=_r;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(oi)!==0)continue;let i=e.getItem(t);if(!i){vr(t);continue}let r=Sr(i);this.add(t,r)}}catch(e){console.error("Storage is blocked",e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(Tt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(oi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(vr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>_r||this.length>da-1||this.size+e>this.available);)this.deleteOldestItem()}};function fr(){return`${oi}${Date.now()}`}function Sr(n){return new Blob([n]).size}function vr(n){try{window.localStorage.removeItem(n)}catch(e){console.error("Failed to remove log from storage",e)}}function ci(){let n=Ye.toString();if(!ye.available||!n)return;let e=Sr(n);ye.cleanup(e);try{window.localStorage.setItem(xt,n)}catch(t){if(console.warn("Failed to write log to storage",t),ye.storageSize=ye.size+e,ye.cleanup(Tt+e),ye.available>=Tt+e){ci();return}if(e>Tt){Ye.bisect(),ci();return}ye.storageSize=0;return}e>ca&&(ye.add(xt,e),xt=fr(),Ye.clear(),ye.cleanup(Tt))}function di(){!ye.available||!Ye.length||ci()}function la(n=!1){let e=[];try{let r=window.localStorage;for(let s of ye.items){let p=r.getItem(s.key);e.push(p)}let a=Ye.toString();a&&e.push(a)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(n)return t;let i=`logs_${Date.now()}.json`;return ua(t,i),i}function ua(n,e){let t=document.createElement("a"),i=new Blob([n],{type:"text/json"});t.href=URL.createObjectURL(i),t.download=e,t.click()}function Er(n,e){!ye.available||(Ye.push({t:Date.now(),l:n,d:e}),li||(li=window.setTimeout(()=>{li=null,di()},pa)))}function pi(){ye||(ye=new gr,Ye=new si,xt=fr(),window.addEventListener("beforeunload",di))}var ye,Ye,xt,li=null;window.__VKCallsSDKLogs__=(n=!1)=>(ye||pi(),di(),la(n));import Tr from"@vkontakte/libvpx";var Ee=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(Ee||{});var u=class extends St{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={};typeof t!="undefined"&&(r.param=t),this._logInternal(e,r,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){u._instance||(u._instance=new u(e,t))}static log(e,t,i=!1){u._instance&&u._instance.log(e,t,i)}static logCustom(e,t,i=!1){u._instance&&u._instance.logCustom(e,t,i)}static destroy(){u._instance&&u._instance.destroy(),u._instance=null}};var Ue=class{constructor(){this._worker=null}_createWorker(s,p){return c(this,arguments,function*(e,t,i=[],r={},a=[]){return new Promise((l,m)=>{let C=i.join(","),R=new Blob([e,`exports.default(${C});`],{type:"application/javascript; charset=utf-8"}),B=window.URL.createObjectURL(R);this._worker=new Worker(B),this._worker.onmessage=M=>{switch(M.data.type){case Ee.READY:l();break;case Ee.ERROR:m(M.data.error);break;case Ee.FRAME:t(M.data);break;case Ee.DEBUG:o.debug(M.data.message);break;case Ee.LOG_ERROR:u.log(_.ERROR,M.data.message);break}},this._sendToWorker(Ee.INIT,r,a)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var at=class extends Ue{init(e){return c(this,null,function*(){o.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var b=Object.defineProperty;var E=a=>b(a,"__esModule",{value:!0});var M=(a,p)=>{E(a);for(var e in p)b(a,e,{get:p[e],enumerable:!0})};var V={};M(V,{default:()=>D});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var D=(a,p)=>{let e=null,n=null,g=!0;function y(){return a({locateFile:p}).then(r=>n=r)}function s(r,m,l,R,x){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(x),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let d=e.getImageBuffer();if(!d){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let c=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(d.byteLength);if(i.set(d),R){let o=new ImageData(i,c,f);createImageBitmap(o,0,0,c,f).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:i.buffer,width:c,height:f},[i.buffer])}y().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return V;})();\n',t=>{if(t.error)o.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i)}else e(t.data)},[Tr,Tr.getUrl])})}decodeFrame(e,t,i,r){let a="ImageBitmap"in window;this._sendToWorker(Ee.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:a,debug:o.enabled()},[t.buffer])}destroy(){this._removeWorker(),o.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var We=class extends Ue{init(e){return c(this,null,function*(){o.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var l=Object.defineProperty;var u=e=>l(e,"__esModule",{value:!0});var m=(e,a)=>{u(e);for(var d in a)l(e,d,{get:a[d],enumerable:!0})};var g={};m(g,{default:()=>E});var s=(d=>(d.VP9="vp09.00.50.08",d.VP8="vp8",d))(s||{}),t=(o=>(o.INIT="init",o.READY="ready",o.FRAME="frame",o.ERROR="error",o.DEBUG="debug",o.LOG_ERROR="log_error",o))(t||{});var E=()=>{let e=null,a=!0;function d(){self.postMessage({type:t.READY})}function i(r,p,o,n=!1){if(!e||a!==o){if(!n){self.postMessage({type:t.DEBUG,message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}a=o,e?self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec changed to ${o?"VP9":"VP8"}`}):(self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec ${o?"VP9":"VP8"}`}),e=new VideoDecoder({output:c=>{self.postMessage({type:t.FRAME,data:c},[c]),c.close()},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:t.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:o?s.VP9:s.VP8})}let f=new EncodedVideoChunk({type:n?"key":"delta",timestamp:r,data:p});e.decode(f)}self.onmessage=r=>{switch(r.data.type){case t.INIT:d();break;case t.FRAME:i(r.data.timestamp,r.data.data,r.data.isVP9,r.data.keyFrame);break}}};return g;})();\n',t=>{t.error?o.warn("WebCodecsDecoder",t.error):e(t.data)})})}decodeFrame(e,t,i,r=!1){this._sendToWorker(Ee.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),o.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window}};import{BitStream as ha}from"bit-buffer";var _a=65536,ze=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(o.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%_a!==e.sequence){o.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:a}=ze.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:a})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((a,s)=>a+s.data.byteLength,0),i=new Uint8Array(t),r=0;for(let a of e)i.set(new Uint8Array(a.data),r),r+=a.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new ha(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),s=i.readBits(1)<<1|r;return s===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,s>=2&&i.index++,i.readBits(3)!==7?(i.index++,(s===1||s===3)&&(i.index+=3)):(s===1||s===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var ui="_okcls_",nt=(()=>{try{let n=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(n,n),t=e.getItem(n)===n,e.removeItem(n),t?e:null}catch(n){return null}})();function ga(n){let e=nt?nt.getItem(ui+n):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function fa(n,e){try{nt&&nt.setItem(ui+n,JSON.stringify(e))}catch(t){}}function Sa(n){nt&&nt.removeItem(ui+n)}var mi;(i=>{function n(r){return ga(r)||null}i.get=n;function e(r,a){fa(r,a)}i.set=e;function t(r){Sa(r)}i.remove=t})(mi||(mi={}));var $e=mi;function Ir(n,e){if(n.isAudioEnabled!==e.isAudioEnabled||n.isVideoEnabled!==e.isVideoEnabled||n.isScreenSharingEnabled!==e.isScreenSharingEnabled||n.videoStreams.length!==e.videoStreams.length)return!1;for(let t of n.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function Te(n){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},n||{})}var Cr=n=>n.stop(),yr=n=>n.getTracks().forEach(Cr),hi=n=>n.getVideoTracks().forEach(Cr),Rr=n=>n.getVideoTracks()[0].clone();var k=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(P).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,k)}};var Pe=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(Pe||{}),de=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(de||{}),_i=class extends q{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=Te();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return c(this,arguments,function*(e=[ue.AUDIO],t=!0){if(this._stream)return;let i=e.includes(ue.VIDEO),r=e.includes(ue.AUDIO);if(!y.isBrowserSupported())throw new k(re.UNSUPPORTED);try{this._stream=yield y.getUserMedia(i,r,t),this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(a=>a.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=r&&this._stream.getAudioTracks().filter(a=>a.enabled).length>0||!1}catch(a){throw new k(a)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t,i,r){let a=this.getStream(),s=this._getSendAudioTrack(),p=this.getSendVideoTrack(i);if(!a||!s&&!p&&!t)throw new Error("No local stream found");if(s&&!t){if(r){let{codecs:l}=RTCRtpSender.getCapabilities("audio"),m="audio/red",C=48e3,R=l.findIndex(B=>B.mimeType===m&&B.clockRate===C);if(R>=0){let B=[];B.push(l[R]);for(let M=0;M<l.length;M++)M!==R&&B.push(l[M]);e.getTransceivers().forEach(M=>M.setCodecPreferences(B))}}e.addTrack(s,a)}p&&!t&&e.addTrack(p,a)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return c(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return c(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=I.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);this._onDeviceChange=()=>c(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],a=r&&r.enabled&&r.getSettings(),s=a&&a.deviceId,p=this._stream.getVideoTracks()[0],l=p&&p.enabled&&p.getSettings(),m=l&&l.deviceId;if(!s&&!m)return;let C=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!C.find(R=>R.deviceId===s)),!t&&m&&(t=!C.find(R=>R.deviceId===m)),i()}),navigator.mediaDevices.addEventListener("devicechange",this._onDeviceChange)}_destroyDeviceChangeListener(){this._onDeviceChange&&navigator.mediaDevices.removeEventListener("devicechange",this._onDeviceChange)}_changeVideoInput(e=null){return c(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield y.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{d.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),a=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),u.log(_.DEVICE_CHANGED,t),o.log("Video stream changed"),yield this._replaceLocalTrack(a),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(_.ERROR,"change_video"),o.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=Rr(e)),t=this._trackVideoStreamBackup.clone(),hi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),hi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return c(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return c(this,null,function*(){try{if(e=e||(yield y.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),u.log(_.DEVICE_CHANGED,"audio"),o.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(_.ERROR,"change_audio"),o.error("Microphone change failed",t),t}})}_changeScreen(e){return c(this,null,function*(){try{if(e=e||(yield y.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=d.consumerScreenTrack?t:yield this._videoEffect(null,t);u.log(_.DEVICE_CHANGED,"screen"),o.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,d.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=d.consumerScreenDataChannel?y.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(_.ERROR,"screen"),o.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return c(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,a;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(a=this._stream)==null||a.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return c(this,null,function*(){if(!d.videoEffects)return t;try{return u.log(_.DEVICE_CHANGED,`effect_${e}`),d.videoEffects.setEffect(e,t)}catch(i){return o.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){this._destroyDeviceChangeListener(),d.videoEffects&&(this._effect=null,d.videoEffects.destroy()),this._stream&&(yr(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return c(this,null,function*(){return e?this._changeScreen():d.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return c(this,null,function*(){if(!this._stream)return;d.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield y.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=y.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return c(this,null,function*(){if(!this._stream)return;let t;e?t=(yield y.getUserAudio()).getAudioTracks()[0]:t=y.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return c(this,null,function*(){if(!d.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return c(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks()[0];if(!e)throw new Error("Local audio track not found");if(!!e.enabled)return e.applyConstraints({noiseSuppression:d.noiseSuppression})})}videoEffect(e){return c(this,null,function*(){if(!d.videoEffects)throw new Error("Video Effects library is not set");if(!d.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var st=":",Nt="d",gi;(Hi=>{function n(T,h,b,V,x=!1,K=!1){let J=/[\r\n]+/,f=`\r
8
+ `;if(!h&&!b&&!V&&!K)return x?Y(T.split(J)).join(f):T;function Y(ce){let Le=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],he="a=rtcp-fb:111",ne=ce.findIndex(Q=>Q.startsWith(he));return~ne&&(ce[ne]=ce[ne]+f+Le.join(f)),ce}function _e(ce,Le,he){let ne=ce.split(" "),Q=ne.slice(0,3),le;for(le=3;le<ne.length;le++)he.includes(ne[le])&&Q.push(ne[le]);for(le=3;le<ne.length;le++)!he.includes(ne[le])&&!Le.includes(ne[le])&&Q.push(ne[le]);return Q.join(" ")}function z(ce,Le){let he=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),ne,Q=[];for(ne=0;ne<ce.length;++ne){let le=ce[ne].match(he);le&&le.length===3&&le[2]===Le&&Q.push(le[1])}return Q}function A(ce,Le,he,ne){let Q,le="m="+Le;for(Q=0;Q<ce.length;++Q)if(ce[Q].startsWith(le)){ce[Q]=_e(ce[Q],he,ne);break}}let ge=[],te=T.split(J);(b||h)&&(ge=z(te,"H264"));let Fe=[];V&&(Fe=z(te,"VP9"));let ke=[];if(K&&(ke=z(te,"red")),b){let ce=ge.slice(0),Le=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),he;for(he=0;he<te.length;++he){let Q=te[he].match(Le);Q&&Q.length===3&&ce.includes(Q[2])&&ce.push(Q[1])}let ne=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(he=te.length;he--;){let Q=te[he].match(ne);Q&&Q.length===3&&ce.includes(Q[2])&&te.splice(he,1)}A(te,"video",ce,[])}else h&&A(te,"video",[],ge);return V&&A(te,"video",[],Fe),K&&ke.length>0&&A(te,"audio",[],ke),x&&Y(te),te.join(f)}Hi.patchSDP=n;function e(T){return T?`${T.type||"WEB_SOCKET"}_${T.id}`:"_"}Hi.getPeerIdString=e;function t(T,h){return T&&T.id===h.id&&(T.type||"WEB_SOCKET")===(h.type||"WEB_SOCKET")}Hi.comparePeerId=t;function i(T){return c(this,null,function*(){return!T||!T.getStats?Promise.resolve(null):T.getStats(null).then(h=>{let b=null,V=null;if(h.forEach(x=>{x.type==="transport"&&x.selectedCandidatePairId?V=h.get(x.selectedCandidatePairId):x.type==="candidate-pair"&&x.state==="succeeded"&&!V&&(!x.hasOwnProperty("selected")||x.selected)&&(V=x)}),V&&V.localCandidateId){let x=h.get(V.localCandidateId);x&&(b={type:x.candidateType,ip:x.ip||x.ipAddress,port:x.port||x.portNumber})}return b}).catch(()=>null)})}Hi.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,a=/^([gu])([0-9]+)$/;function s(T,h){let b=String(T);return a.test(b)?(o.warn(`Already composite id [${T}] type supplied [${h}]`),b):h===X.GROUP?"g"+b:h===X.USER?"u"+b:(o.warn(`Unknown type [${h}] for id [${T}]`),b.match(r)?"u"+b:b)}Hi.composeUserId=s;function p(T,h,b){let V=s(T,h);return l(V,b)}Hi.composeParticipantId=p;function l(T,h){return h?T+st+Nt+h:T}Hi.compose=l;function m(T){return p(T.id,T.idType||X.USER,T.deviceIdx||0)}Hi.composeId=m;function C(T){return T.participant?m(T.participant):p(T.participantId,T.participantType||X.USER,T.deviceIdx||0)}Hi.composeMessageId=C;function R(T){let h=String(T),b=h.match(a);return b?{id:Number(b[2]),type:b[1]==="g"?X.GROUP:X.USER}:(o.warn(`Unsupported compositeId [${T}]`),{id:Number(h),type:X.USER})}Hi.decomposeId=R;function B(T){let h=T.split(st+Nt);return{compositeUserId:h[0],deviceIdx:h.length>1?parseInt(h[1],10):0}}Hi.decomposeParticipantId=B;function M(){var J,f;let T=(f=(J=window.crypto)==null?void 0:J.randomUUID)==null?void 0:f.call(J);if(T)return T;let h="0123456789abcdefghijklmnopqrstuvwxyz".split(""),b=new Array(36),V=0,x,K;for(K=0;K<36;K++)K===8||K===13||K===18||K===23?b[K]="-":K===14?b[K]="4":(V<=2&&(V=33554432+Math.random()*16777216|0),x=V&15,V=V>>4,b[K]=h[K===19?x&3|8:x]);return b.join("")}Hi.uuid=M;function H(T,h){let b;function V(){let x=this,K=arguments;b&&window.clearTimeout(b),b=window.setTimeout(()=>{T.apply(x,K)},h)}return V}Hi.throttle=H;function ee(T){if(!window.BigInt)return null;let h="",b=T.split(`
9
+ `);for(let K of b)if(K.startsWith("a=fingerprint")){let J=K.split(" ");if(J.length===2){h=J[1];break}}if(!h)return BigInt(-1);let V=h.split(":"),x=BigInt(0);for(let K=Math.min(7,V.length-1);K>=0;K--){let J=BigInt(parseInt(V[K],16));x<<=BigInt(8),x|=J}return BigInt.asIntN(64,x)}Hi.sdpFingerprint=ee;function Ce(T){return c(this,null,function*(){return new Promise(h=>window.setTimeout(h,T))})}Hi.delay=Ce;function ae(T,h,b){let V=[];return T.getSenders().forEach(x=>Ve(h,x,x.track,b,V)),V}Hi.applySettings=ae;function Ve(T,h,b,V,x){var K;if(T&&b&&b.kind===de.video){let J=b.getSettings();if(J){let f=T.maxBitrateK?T.maxBitrateK*1024:null,Y=J.width,_e=J.height,z=Y&&_e&&T.maxDimension?Math.max(1,Math.max(Y,_e)/T.maxDimension):null,A=T.maxFramerate?T.maxFramerate:null,ge=T.degradationPreference?T.degradationPreference:"balanced",te=V[b.id];if(te&&te.bitrate===f&&te.scaleResolutionDownBy===z&&te.maxFramerate===A&&te.degradationPreference===ge){x[b.id]=te;return}x[b.id]={bitrate:f,scaleResolutionDownBy:z,maxFramerate:A,degradationPreference:ge};let Fe=h.getParameters();Fe.encodings||(Fe.encodings=[{}]),Fe.encodings.forEach(ke=>{f?ke.maxBitrate=f:delete ke.maxBitrate,z?ke.scaleResolutionDownBy=z:delete ke.scaleResolutionDownBy,A?ke.maxFramerate=A:delete ke.maxFramerate}),Fe.degradationPreference=ge,(K=h.setParameters)==null||K.call(h,Fe)}}}Hi.applyVideoTrackSettings=Ve;function se(T,h){Array.isArray(h)||(h=[h]);for(let b of h)if(T.includes(b))return!0;return!1}Hi.includesOneOf=se;function Re(T){var h;return Object.entries(((h=T.participantState)==null?void 0:h.state)||{}).reduce((b,[V,x])=>(T.participantState&&(b[V]={ts:T.participantState.stateUpdateTs[V],state:x}),b),{})}Hi.mapParticipantState=Re;function be(T){let h=T.map(b=>({uid:b.externalId,mediaSettings:b.mediaSettings,status:b.status,muteStates:b.muteStates,unmuteOptions:b.unmuteOptions,participantState:b.participantState}));return d.filterObservers?h.filter(b=>!b.uid.observer):h}Hi.mapSharedParticipants=be;function j(T,h){let b=Object.keys(T),V=Object.keys(h);if(b.length!==V.length)return!1;for(let x of b)if(!V.hasOwnProperty(x)||T[x].state!==h[x].state||T[x].ts!==h[x].ts)return!1;return!0}Hi.isEqualParticipantState=j;function Bi(T,h){let b=Object.keys(T),V=Object.keys(h);if(b.length!==V.length)return!1;for(let x of b)if(!h.hasOwnProperty(x)||T[x]!==h[x])return!1;return!0}Hi.isObjectsEquals=Bi;function Vi(T,h){if(T.length!==h.length)return!1;for(let b of T)if(h.indexOf(b)<0)return!1;return!0}Hi.isArraysEquals=Vi;function Fi(T){return!Object.keys(T).length}Hi.isEmptyObject=Fi})(gi||(gi={}));var I=gi;var Qe=null,fi=null,Lt=[],Ut=[],Si=[],It=null,Ct=null,vi=null,Ei=!1,Ti=!1,Bt,ot,Vt,br=!1,Pr=!1,Ii=null,Ci="",Ft=[],yi=null,Mr=navigator.appVersion,va=navigator.appName,Me=navigator.userAgent,Dr=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(Dr||{}),yt=class{constructor(e,t=!1,i=d.videoMaxWidth,r=d.videoMaxHeight){let a=!1;if(e){a={noiseSuppression:d.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let p;Ct&&(p=Ct.deviceId),typeof e=="string"&&(p=e),p&&(a.deviceId={ideal:p})}let s=!1;if(t){s={width:{min:d.videoMinWidth,max:i,ideal:i},height:{min:d.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:d.videoAspectRatio},frameRate:{ideal:d.videoFrameRate}};let p;It&&(p=It.deviceId),typeof t=="string"&&(p=t),p&&(s.deviceId={ideal:p}),d.videoFacingMode&&(s.facingMode={ideal:d.videoFacingMode})}this.audio=a,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},Ar=class extends yt{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=d.screenFrameRate}};function Ea(){return c(this,null,function*(){Qe=null,yield Ht()})}function Ta(){Qe=null,Ht().then(()=>S.onDeviceChange())}function Ht(){return c(this,null,function*(){return Qe||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!fi&&navigator.mediaDevices.addEventListener&&(fi=I.throttle(Ta,1e3),navigator.mediaDevices.addEventListener("devicechange",fi)),Qe=navigator.mediaDevices.enumerateDevices().then(n=>{Lt=n.filter(r=>r.kind==="videoinput"?(r.label&&(Ei=!0),!0):!1),Ut=n.filter(r=>r.kind==="audioinput"?(r.label?Ti=!0:Xe.isMobile()&&Xe.browserName()==="Firefox"&&(Ti=Ei),!0):!1),Si=n.filter(r=>r.kind==="audiooutput");let e=$e.get("videoinput"),t=$e.get("audioinput"),i=$e.get("audiooutput");return It=Lt.find(r=>r.deviceId===e)||null,Ct=Ut.find(r=>r.deviceId===t)||null,vi=Si.find(r=>r.deviceId===i)||null,Qe=Promise.resolve(n),n}).catch(()=>(Qe=null,[]))))})}function Ia(){return c(this,null,function*(){return Xe.isBrowserSupported()?new Promise(n=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(br=!0),/^a=mid:0$/m.test(t.sdp)&&(Pr=!0),n()}).catch(n)}):Promise.resolve()})}function Gt(n,e){return c(this,null,function*(){o.debug("Try to get media",n.getNative());let t=Xe.hasPermissions(n.isVideo());!t&&!e&&S.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(n.getNative());return t||(yield Ea()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=n.isVideo()?re.CAMERA_PERMISSION:re.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=n.isVideo()?re.CAMERA_ACCESS:re.MIC_ACCESS;break}if(n.canSimplify())return Gt(n.simplify(),e);let r=e||re.UNKNOWN;throw S.onPermissionsError(r),r}})}function Ca(n){return c(this,null,function*(){o.debug("Try to get screen",n.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(n.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(o.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw re.SCREEN_PERMISSION;default:throw re.SCREEN_ACCESS}}})}function Wt(){return Ft.length||(Ft=(()=>{let n,e=!1,t=0,i="0",r=Me.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return n=/\brv[ :]+(\d+)/g.exec(Me),["IE",n&&n[1]||"Unknown",e,t,i];if(r[1]==="Safari"){if(n=Me.match(/\bEdge\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t,i];if(n=Me.match(/\bCriOS\/(\d+)/),n)return["Chrome",n[1],!0,Number(n[1]),i];if(n=Me.match(/\bFxiOS\/(\d+)/),n)return["Firefox",n[1],!1,t,i];if(n=Me.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1],!1,t,i];if(n=Me.match(/\bOPT\/(\d+)/),n)return["Opera",n[1],!1,t,i]}if(r[1]==="Chrome"){if(e=!0,t=Number(r[2]),n=Me.match(/\bOPR\/(\d+)/),n)return["Opera",n[1]||"Unknown",e,t,i];if(n=Me.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1]||"Unknown",e,t,i];if(n=Me.match(/\bSferum\/((\d+)(?:\.\d+)*)/),n)return["Sferum",n[1]||"Unknown",e,t,i];if(n=Me.match(/\bEdge?\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t,i];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t,i]}return n=Me.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),n&&n[2]!==void 0&&(i=n[2]),[r[2]?r[1]:va,n&&n[1]||r[2]||Mr,e,t,i]})()),Ft}var Xe;(J=>{function n(){return c(this,null,function*(){return yield Ia(),Ht()})}J.init=n;function e(){return Lt}J.getCameras=e;function t(){return Ut}J.getMicrophones=t;function i(){return Si}J.getOutput=i;function r(){return Lt.length>0}J.hasCamera=r;function a(){return Ut.length>0}J.hasMicrophone=a;function s(){return It}J.getSavedCamera=s;function p(){return Ct}J.getSavedMicrophone=p;function l(){return vi}J.getSavedOutput=l;function m(){return Ei}J.hasCameraPermission=m;function C(){return Ti}J.hasMicrophonePermission=C;function R(f=!1){return C()?r()&&f?m():!0:!1}J.hasPermissions=R;function B(f=!1,Y=!0,_e=!0){return c(this,null,function*(){let z=a()&&Y,A=r()&&f,ge;if(!z&&!A)ge=new MediaStream;else try{ge=yield Gt(new yt(z,A))}catch(te){ge=new MediaStream}return!ge.getVideoTracks().length&&_e&&ge.addTrack(Ve()),!ge.getAudioTracks().length&&_e&&ge.addTrack(ae()),ge})}J.getUserMedia=B;function M(){return c(this,null,function*(){return Ca(new Ar(window.screen.width,window.screen.height))})}J.getScreenMedia=M;function H(f,Y=!1){return c(this,null,function*(){let _e=Y?d.videoEffectMaxWidth:d.videoMaxWidth,z=Y?d.videoEffectMaxHeight:d.videoMaxHeight;return Gt(new yt(!1,f||!0,_e,z))})}J.getUserVideo=H;function ee(f){return c(this,null,function*(){return Gt(new yt(f||!0,!1))})}J.getUserAudio=ee;function Ce(f,Y){return c(this,null,function*(){let z=(yield Ht()).find(A=>A.kind===f&&A.deviceId===Y);return z?(f==="videoinput"?It=z:f==="audioinput"?Ct=z:f==="audiooutput"&&(vi=z),$e.set(f,Y),z):null})}J.saveDeviceId=Ce;function ae(){if(!Vt||Vt.readyState==="ended"){let f=x(),Y=f.createMediaStreamDestination(),_e=f.createGain();_e.gain.value=1e-5,_e.connect(Y),_e.connect(f.destination);let z=f.createOscillator();z.type="sine",z.frequency.value=0,z.connect(_e),z.start(),Vt=Y.stream.getAudioTracks()[0]}return Object.assign(Vt.clone(),{enabled:!1})}J.getSilentMediaTrack=ae;function Ve(f=d.videoMinWidth,Y=d.videoMinHeight){return ot||(ot=document.createElement("canvas"),ot.getContext("2d")),ot.width=f,ot.height=Y,(!Bt||Bt.readyState==="ended")&&(Bt=ot.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(Bt.clone(),{enabled:!1})}J.getBlackMediaTrack=Ve;function se(){if(h()==="Edge"&&Number(b())<70)return!1;try{let f=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&f.RTCPeerConnection&&f.RTCIceCandidate&&f.RTCSessionDescription&&f.HTMLCanvasElement&&f.HTMLCanvasElement.prototype.captureStream&&f.RTCRtpSender&&f.RTCRtpSender.prototype.replaceTrack&&f.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(f){return!1}}J.isBrowserSupported=se;function Re(){return!!navigator.mediaDevices.getDisplayMedia}J.isScreenCapturingSupported=Re;function be(){return br}J.canVP8=be;function j(){return Pr}J.isUnifiedPlan=j;function Bi(){let f=J.browserName()==="Safari"&&J.browserVersion()==="15"&&J.browserSubVersion()==="1",Y=J.browserName()==="Opera"&&J.os()==="Windows";return f||Y}J.isBrokenH264=Bi;function Vi(){return!(J.baseChromeVersion()&&J.isMobile())}J.canPreferH264=Vi;function Fi(){var f;return((f=window.RTCRtpTransceiver)==null?void 0:f.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}J.canPreferRed=Fi;function Hi(){return Ci||(Ci=(()=>{let f={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let Y in f)if(f.hasOwnProperty(Y)&&f[Y].test(Me))return Y;return"Unknown"})()),Ci}J.os=Hi;function T(){return Ii===null&&(Ii=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Mr)),Ii}J.isMobile=T;function h(){return Wt()[0]}J.browserName=h;function b(){return Wt()[1]}J.browserVersion=b;function V(){return Wt()[3]}J.baseChromeVersion=V;function x(){return yi||(yi=new(window.AudioContext||window.webkitAudioContext)),yi}J.getAudioContext=x;function K(){return Wt()[4]}J.browserSubVersion=K})(Xe||(Xe={}));var y=Xe;var ct=class{constructor(e){this._onStream=e}drawFrame(e){return c(this,null,function*(){throw new Error("Method `drawFrame` is not supported by this implementation")})}drawImage(e){throw new Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Rt=class extends ct{constructor(e){super(e);this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;o.debug("CanvasRenderer started"),this._useImageBitmap="ImageBitmap"in window}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}drawFrame(e){return c(this,null,function*(){let t="createImageBitmap"in e?yield e.createImageBitmap():yield createImageBitmap(e);this.drawImage(t),t.close()})}drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}destroy(){this._removeStream(),o.debug("CanvasRenderer destroyed")}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(y.browserName()==="Safari"&&Number(y.browserVersion())===15)}};var dt=class extends ct{constructor(e){super(e);o.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:de.video}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}drawFrame(e){return c(this,null,function*(){yield this._writer.write(e)})}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),o.debug("TrackGeneratorRenderer destroyed")}static isBrowserSupported(){return"VideoFrame"in window&&"MediaStreamTrackGenerator"in window&&We.isBrowserSupported()}};var bt=class extends ze{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];o.debug(`StreamBuilder started for participant [${e}]`),dt.isBrowserSupported()?this._renderer=new dt(t):this._renderer=new Rt(t),We.isBrowserSupported()?this._decoder=new We:this._decoder=new at;let i=r=>c(this,null,function*(){"VideoFrame"in window&&r instanceof VideoFrame?yield this._renderer.drawFrame(r):this._renderer.drawImage(r)});this._decoder.init(i).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._renderer.destroy(),o.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return Rt.isBrowserSupported()||dt.isBrowserSupported()}};var jt=1,ya=1,Or=0,kr=11,wr=1,xr=2,Nr=4,Lr=8;function Ur(n,e,t,i,r,a,s){let p=0;e&&(p|=wr),t&&(p|=xr),i&&(p|=Nr),s||(p|=Lr);let l=new ArrayBuffer(kr),m=new DataView(l);if(m.setUint8(0,jt),m.setUint16(1,r),m.setUint32(3,n),m.setUint8(7,a?1:0),m.setUint16(8,Or),m.setUint8(10,p),!s)return l;let C=new Uint8Array(l.byteLength+s.byteLength);return C.set(new Uint8Array(l),0),C.set(new Uint8Array(s),l.byteLength),C.buffer}function Br(n){let e=new DataView(n),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),a=e.getUint8(7)===1,s=e.getUint16(8),p=e.getUint8(10),l=!!(p&wr),m=!!(p&xr),C=!!(p&Nr),R=!!(p&Lr);if(t!==jt)throw new Error(`Unexpected protocol version. Got ${t}, expected ${jt}`);return{timestamp:r,start:l,end:m,keyframe:C,sequence:i,isVP9:a,ssrc:s,eos:R,data:n.slice(kr)}}function Vr(n){if(!n||!n.byteLength||n.byteLength!==4)return!1;let e=new DataView(n);return!(e.getUint8(0)!==jt||e.getUint8(1)!==ya||e.getUint16(2)!==Or)}import*as v from"simple-ebml-builder";var Ra=Wi(2,15)-1,Ri=1,ba=5,Pa=5;var Kt=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),o.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=Kt._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return v.build(e[0])}else return new Uint8Array;let t=e.reduce((a,s)=>a+s.countSize(),0),i=new Uint8Array(t),r=0;for(let a of e){let s=v.build(a);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var a,s,p;((a=this._mediaSource)==null?void 0:a.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let e=(p=this._sourceBuffer)==null?void 0:p.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-ba);r-i>Pa&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},xe=class extends ze{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;o.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return v.element(v.ID.EBML,[v.element(v.ID.EBMLVersion,v.number(1)),v.element(v.ID.EBMLReadVersion,v.number(1)),v.element(v.ID.EBMLMaxIDLength,v.number(4)),v.element(v.ID.EBMLMaxSizeLength,v.number(8)),v.element(v.ID.DocType,v.string("webm")),v.element(v.ID.DocTypeVersion,v.number(2)),v.element(v.ID.DocTypeReadVersion,v.number(2))])}static _genSegmentHeader(e,t,i){let r=v.element(v.ID.Info,[v.element(v.ID.TimecodeScale,v.number(1e6)),v.element(v.ID.MuxingApp,v.string("vk-webm-builder")),v.element(v.ID.WritingApp,v.string("vk-webm-builder"))]),a=[v.element(v.ID.PixelWidth,v.number(e)),v.element(v.ID.PixelHeight,v.number(t))],s=v.element(v.ID.Tracks,v.element(v.ID.TrackEntry,[v.element(v.ID.TrackNumber,v.number(Ri)),v.element(v.ID.TrackUID,v.number(Ri)),v.element(v.ID.TrackType,v.number(1)),v.element(v.ID.FlagLacing,v.number(0)),v.element(v.ID.DefaultDuration,v.number(1e9)),v.element(v.ID.CodecID,v.string(`V_${i.toUpperCase()}`)),v.element(v.ID.Video,a)]));return v.unknownSizeElement(v.ID.Segment,[r,s])}static _genClusterHeader(e){return v.unknownSizeElement(v.ID.Cluster,[v.element(v.ID.Timecode,v.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new Kt(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){o.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>o.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,o.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),o.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=xe._genWebmHeader();this._mediaBuffer.append(s);let p=xe._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(p)}let r=Math.round(i-this._clusterStartTime);if(r>Ra&&(this._clusterStartTime=i,r=0),r===0){o.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=xe._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let a=v.element(v.ID.SimpleBlock,[v.vintEncodedNumber(Ri),v.bytes(xe._intToU16BE(r)),v.number((e.keyframe?1:0)<<7),v.bytes(e.frameData)]);this._mediaBuffer.append(a,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),o.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var pt=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};o.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=a=>this._onDataChannelMessage(a.data)}_onDataChannelMessage(e){var a,s;let t=Br(e),i=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){o.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];if(!r){let p=l=>this._onStream(i,l);d.screenShareWebmBuilder&&xe.isBrowserSupported()?r=new xe(i,p):r=new bt(i,p),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,o.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(We.isBrowserSupported()||at.isBrowserSupported())&&(bt.isBrowserSupported()||xe.isBrowserSupported())}};import Fr from"@vkontakte/libvpx";var Ma=1e3,Pt=class extends Ue{constructor(e,t){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return c(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=p=>t(),r.onerror=()=>i(new Error("Video element error"));let a=r.play(),s=()=>i(new Error("Autoplay is disabled"));a?a.catch(s):s()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return c(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return c(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;o.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var u=Object.defineProperty;var b=o=>u(o,"__esModule",{value:!0});var g=(o,n)=>{b(o);for(var t in n)u(o,t,{get:n[t],enumerable:!0})};var y={};g(y,{default:()=>R});var e=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(e||{});var R=(o,n)=>{let t;function m(a,r){return o({locateFile:n}).then(s=>{if(t=new s.VpxEncoder,t.debug(r),!t.init(a?s.VpxType.VP9:s.VpxType.VP8))throw self.postMessage({type:e.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");t.setMaxQuantizer(10),t.setTargetBitrate(1024)})}function E(a,r,s,i){let c=t.allocateImage(a,r);if(!c){self.postMessage({type:e.FRAME,error:"No buffer data"});return}c.set(new Uint8Array(s));let f=Math.round(performance.now()),l=150;if(!t.encode(f,l,i)){self.postMessage({type:e.FRAME,error:"Encode failed"});return}let p=t.readFrame();if(!p){self.postMessage({type:e.FRAME,error:"No encoded data"});return}t.readFrame()&&(self.postMessage({type:e.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:e.LOG_ERROR,message:"LibVPxEncoder-drop"}));let d=new Uint8Array(p.byteLength);d.set(p),self.postMessage({type:e.FRAME,frameType:i?"key":"delta",timestamp:f,duration:l,data:d.buffer},[d.buffer])}self.onmessage=a=>{switch(a.data.type){case e.INIT:m(a.data.isVP9,a.data.debug).then(()=>self.postMessage({type:e.READY})).catch(r=>self.postMessage({type:e.ERROR,error:String(r)}));break;case e.FRAME:E(a.data.width,a.data.height,a.data.imageData,a.data.keyFrame);break}}};return y;})();
10
+ `,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength})},[Fr,Fr.getUrl],{isVP9:this.isVP9(),debug:o.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(Ee.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},Ma),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),o.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var lt=class extends Ue{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return c(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;o.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var E=Object.defineProperty;var g=i=>E(i,"__esModule",{value:!0});var F=(i,l)=>{g(i);for(var r in l)E(i,r,{get:l[r],enumerable:!0})};var A={};F(A,{default:()=>h});var n=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(n||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,l,r,c,s,f,t,a=null,p=0,u=!1;function V(e){l=e.readable,r=l.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&b(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),l.cancel();return}a=R,b(R,e)}}))}function b(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
11
+ `,r=>{var a;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(a=r.data)==null?void 0:a.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:d.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(Ee.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),o.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var Da=16*1024,Aa=11,Hr=Da-Aa,Oa=65536,bi=0,ut=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;o.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,a)=>{if(!this._destroyed){if(!r){o.warn("requestFrame failed, keyFrame: "+this._needKeyframe,a),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{o.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};lt.isBrowserSupported()?this._encoder=new lt(e,i):this._encoder=new Pt(e,i),this._datachannel.onmessage=r=>{Vr(r.data)&&(o.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>o.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,a){let s=Ur(e,t,i,r,bi,this._encoder.isVP9(),a);return bi=(bi+1)%Oa,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return c(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let a=e.data.slice(t,t+Hr),s=e.data.byteLength<=t+a.byteLength,p=this._wrapHeader(e.timestamp,!t,s,e.type==="key",a);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(p)}catch(l){o.warn("Error send data to DataChannel",l),r();return}s||window.setTimeout(()=>this._sendChunk(e,t+Hr,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),o.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return lt.isBrowserSupported()||Pt.isBrowserSupported()}};var Z=class{static get sessionKey(){return Z._sessionKey}static set sessionKey(e){Z._sessionKey=e}static get sessionSecretKey(){return Z._sessionSecretKey}static set sessionSecretKey(e){Z._sessionSecretKey=e}static get accessToken(){return Z._accessToken}static set accessToken(e){Z._accessToken=e}static isEmpty(){return!Z._sessionKey||!Z._sessionSecretKey}};var g=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(g._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(g._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(g._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(Z.accessToken=e.apiAuth.accessToken,Z.sessionKey=e.apiAuth.sessionKey,Z.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(g._params,e)}static get(e){return g._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.5.3-dev.dbb762f.0"}static get debug(){return undefined}static get protocolVersion(){return g._params.joinFromMultipleDevices?6:5}static get platform(){return g._params.platform}static set platform(e){g._params.platform=e}static get clientType(){return g._params.clientType}static set clientType(e){g._params.clientType=e}static get device(){return g._params.device}static get apiKey(){return g._params.apiKey}static get apiEnv(){return g._params.apiEnv}static get apiEndpoint(){switch(g.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return g._params.apiEnv}}static get authToken(){return g._params.authToken}static set authToken(e){g._params.authToken=e}static get anonymToken(){return g._params.anonymToken}static set anonymToken(e){g._params.anonymToken=e}static get domain(){return g._params.domain}static get iceServers(){return g._params.iceServers}static set iceServers(e){g._params.iceServers=e}static get wssBase(){return g._params.wssBase}static set wssBase(e){g._params.wssBase=e}static get wssToken(){return g._params.wssToken}static set wssToken(e){g._params.wssToken=e}static get signalingReconnectDelay(){return g._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return g._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return g._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return g._params.waitConnectionDelay}static get waitResponseDelay(){return g._params.waitResponseDelay}static get waitMessageDelay(){return g._params.waitMessageDelay}static get waitAnotherTabDelay(){return g._params.waitAnotherTabDelay}static get debugLog(){return g._params.debugLog}static get forceRelayPolicy(){return g._params.forceRelayPolicy}static set forceRelayPolicy(e){g._params.forceRelayPolicy=e}static get videoMinWidth(){return g._params.videoMinWidth}static get videoMaxWidth(){return g._params.videoMaxWidth}static set videoMaxWidth(e){g._params.videoMaxWidth=e}static get videoMinHeight(){return g._params.videoMinHeight}static get videoMaxHeight(){return g._params.videoMaxHeight}static set videoMaxHeight(e){g._params.videoMaxHeight=e}static get videoAspectRatio(){return g._params.videoAspectRatio}static get videoFrameRate(){return g._params.videoFrameRate}static get videoFacingMode(){return g._params.videoFacingMode}static get screenFrameRate(){return g._params.screenFrameRate}static get videoEffects(){return g._params.videoEffects}static set videoEffects(e){g._params.videoEffects=e}static get videoEffectMaxWidth(){return g._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){g._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return g._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){g._params.videoEffectMaxHeight=e}static get voiceParams(){return g._params.voiceParams}static get specListenerParams(){return g._params.specListenerParams}static get iceRestartWaitTime(){return g._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return g._params.transportConnectionWaitTime}static get statisticsInterval(){return g._params.statisticsInterval}static set statisticsInterval(e){g._params.statisticsInterval=e}static get networkStatisticsInterval(){return g._params.networkStatisticsInterval}static get perfStatReportEnabled(){return g._params.perfStatReportEnabled}static get callStatReportEnabled(){return g._params.callStatReportEnabled}static get producerNotificationDataChannel(){return g._params.producerNotificationDataChannel&&pt.isBrowserSupported()}static get producerCommandDataChannel(){return g._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return g._params.consumerScreenDataChannel&&ut.isBrowserSupported()}static get producerScreenDataChannel(){return g._params.producerScreenDataChannel&&g.producerNotificationDataChannel}static get screenShareWebmBuilder(){return g._params.screenShareWebmBuilder}static get noiseSuppression(){return g._params.noiseSuppression}static set noiseSuppression(e){g._params.noiseSuppression=e}static get preferH264(){return g._params.preferH264}static get preferVP9(){return g._params.preferVP9}static get audioNack(){return g._params.audioNack}static get consumerScreenTrack(){return g._params.consumerScreenTrack&&g.consumerScreenDataChannel}static get producerScreenTrack(){return g._params.producerScreenTrack&&g.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=g._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return g._params.movieShare&&g.videoTracksCount>0}static get videoTracksCount(){return g.producerNotificationDataChannel?g._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return g._params.breakVideoPayloadTypes}static get filteredMessages(){return g._params.filteredMessages}static get serverAudioRed(){return g._params.serverAudioRed&&y.canPreferRed()}static get p2pAudioRed(){return g._params.p2pAudioRed&&y.canPreferRed()}static get batchParticipantsOnStart(){return g._params.batchParticipantsOnStart}static get filterObservers(){return g._params.filterObservers}static get muteMode(){return g._params.muteMode}static get preserveAudioTracks(){return g._params.preserveAudioTracks}},d=g;d._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,serverAudioRed:!1,p2pAudioRed:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1};var $=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))($||{});function W(n,...e){let t=d.get(n);t&&setTimeout(t,0,...e)}function Ie(n,e,...t){if(d.filterObservers){if(Array.isArray(e)){if(e=e.filter(i=>!i.observer),!e.length)return}else if(e.observer)return}W(n,e,...t)}function Ne(n){return Object.assign({},n)}function mt(n){return n.slice()}var Pi;(vn=>{function n(E,D){W("onLocalStream",E,Ne(D))}vn.onLocalStream=n;function e(E,D){W("onScreenStream",E,Ne(D))}vn.onScreenStream=e;function t(E,D){W("onLocalStreamUpdate",Ne(E),D)}vn.onLocalStreamUpdate=t;function i(E){W("onLocalStatus",E)}vn.onLocalStatus=i;function r(E,D){Ie("onRemoteStream",E,D)}vn.onRemoteStream=r;function a(E,D,ie){Ie("onRemoteLive",E,D,ie)}vn.onRemoteLive=a;function s(E,D,ie){Ie("onLocalLive",E,D,ie)}vn.onLocalLive=s;function p(E,D){Ie("onRemoteLiveUpdate",E,D)}vn.onRemoteLiveUpdate=p;function l(E,D){Ie("onLocalLiveUpdate",E,D)}vn.onLocalLiveUpdate=l;function m(E,D){Ie("onRemoteScreenStream",E,D)}vn.onRemoteScreenStream=m;function C(E,D,ie,gt){Ie("onConversation",E,Ne(D),Ne(ie),gt)}vn.onConversation=C;function R(E,D){Ie("onRemoteMediaSettings",E,Ne(D))}vn.onRemoteMediaSettings=R;function B(E,D){Ie("onLocalMediaSettings",E,Ne(D))}vn.onLocalMediaSettings=B;function M(E,D){Ie("onRemoteParticipantState",E,Ne(D))}vn.onRemoteParticipantState=M;function H(E,D,ie=null){Ie("onRemoteStatus",E,D,ie)}vn.onRemoteStatus=H;function ee(E,D,ie=null){Ie("onParticipantStatus",E,D,ie)}vn.onParticipantStatus=ee;function Ce(){W("onPermissionsRequested")}vn.onPermissionsRequested=Ce;function ae(E){W("onPermissionsError",E)}vn.onPermissionsError=ae;function Ve(E){Ie("onRemoteRemoved",E)}vn.onRemoteRemoved=Ve;function se(E,D,ie){W("onCallState",E,D,Ne(ie))}vn.onCallState=se;function Re(E,D){W("onDeviceSwitched",E,D)}vn.onDeviceSwitched=Re;function be(E,D,ie,gt=!1,ii=!1,ri=null,aa=null){W("onMuteStates",Ne(E),mt(D),mt(ie),gt,ii,ri,aa)}vn.onMuteStates=be;function j(E,D){Ie("onRolesChanged",E,mt(D))}vn.onRolesChanged=j;function Bi(E){W("onLocalRolesChanged",mt(E))}vn.onLocalRolesChanged=Bi;function Vi(E,D){Ie("onPinnedParticipant",E,D)}vn.onPinnedParticipant=Vi;function Fi(E){W("onLocalPin",E)}vn.onLocalPin=Fi;function Hi(E){W("onOptionsChanged",mt(E))}vn.onOptionsChanged=Hi;function T(){W("onCallAccepted")}vn.onCallAccepted=T;function h(){W("onRateNeeded")}vn.onRateNeeded=h;function b(E){Ie("onSpeakerChanged",E)}vn.onSpeakerChanged=b;function V(E){W("onVolumesDetected",mt(E))}vn.onVolumesDetected=V;function x(E,D){W("onLocalVolume",E,D)}vn.onLocalVolume=x;function K(E,D){W("onJoinStatus",E,D)}vn.onJoinStatus=K;function J(E,D){W("onHangup",E,D)}vn.onHangup=J;function f(E){W("onMultipartyChatCreated",Ne(E))}vn.onMultipartyChatCreated=f;function Y(){W("onDeviceChange")}vn.onDeviceChange=Y;function _e(E){W("onFingerprintChange",E)}vn.onFingerprintChange=_e;function z(){W("onTokenExpired")}vn.onTokenExpired=z;function A(E,D,ie=!1){W("onChatMessage",E,D,ie)}vn.onChatMessage=A;function ge(E,D,ie=!1){W("onCustomData",E,D,ie)}vn.onCustomData=ge;function te(E,D,ie,gt,ii,ri){W("onRecordStarted",E,D,ie,gt,ii,ri)}vn.onRecordStarted=te;function Fe(){W("onRecordStopped")}vn.onRecordStopped=Fe;function ke(E){W("onLocalNetworkStatusChanged",E)}vn.onLocalNetworkStatusChanged=ke;function ce(E){W("onNetworkStatusChanged",E)}vn.onNetworkStatusChanged=ce;function Le(E,...D){W("onDebugMessage",E,...D)}vn.onDebugMessage=Le;function he(E,D){let ie=Object.assign({},E,{memory:D});W("onStatistics",ie)}vn.onStatistics=he;function ne(){W("onAutoplayError")}vn.onAutoplayError=ne;function Q(E,D,ie){W("onChatRoomUpdated",E,D,ie)}vn.onChatRoomUpdated=Q;function le(E){W("onRemoteMixedAudioStream",E)}vn.onRemoteMixedAudioStream=le})(Pi||(Pi={}));var S=Pi;var Gr=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(Gr||{}),Mi;(se=>{let n="📞",e=(Re,...be)=>{S.onDebugMessage(Re,...be)},t=!1,i=(Re,be)=>(...j)=>{Re(...j),Er(be,j)},r=console.debug.bind(console,n),a=console.log.bind(console,n),s=console.warn.bind(console,n),p=console.error.bind(console,n),l=e.bind(null,"DEBUG"),m=e.bind(null,"LOG"),C=e.bind(null,"WARN"),R=e.bind(null,"ERROR");se.debug=l,se.log=m,se.warn=C,se.error=R;function Ce(){return t}se.enabled=Ce;function ae(Re){t=Re,d.debugLog&&pi(),Re?(se.debug=d.debugLog?i(r,"DEBUG"):r,se.log=d.debugLog?i(a,"LOG"):a,se.warn=d.debugLog?i(s,"WARN"):s,se.error=d.debugLog?i(p,"ERROR"):p):(se.debug=d.debugLog?i(l,"DEBUG"):l,se.log=d.debugLog?i(m,"LOG"):m,se.warn=d.debugLog?i(C,"WARN"):C,se.error=d.debugLog?i(R,"ERROR"):R)}se.toggle=ae;function Ve(Re,...be){switch(Re){case"DEBUG":se.debug(...be);break;case"LOG":se.log(...be);break;case"WARN":se.warn(...be);break;case"ERROR":se.error(...be);break}}se.send=Ve})(Mi||(Mi={}));var o=Mi;var ht=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(ht||{}),fe;(p=>{function n(l){return l.length?typeof l[0]=="object"?l:l.map(m=>e(m)):[]}p.fromIds=n;function e(l,m="USER"){return{id:l,type:m}}p.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}p.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}p.toString=i;function r(l,m="USER"){return i(e(l,m))}p.fromIdToString=r;function a(l){try{return JSON.parse(l)}catch(m){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}p.fromString=a;function s(l,m){return l.id===m.id&&l.type===m.type}p.compare=s})(fe||(fe={}));var Se;(r=>{function n(a,s="USER",p=0){return{id:a,type:s,deviceIdx:p}}r.fromId=n;function e(a){return`{"id":"${a.id}","type":"${a.type}","deviceIdx":"${a.deviceIdx}"}`}r.toString=e;function t(a,s){return Object.assign({deviceIdx:s},fe.fromSignaling(a))}r.fromSignaling=t;function i(a){return a&&typeof a=="object"?a.deviceIdx:0}r.getDeviceIdx=i})(Se||(Se={}));var De=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(De||{}),Wr="s",jr="m";function qe(n){return n.participantId+(n.mediaType?st+Wr+n.mediaType:"")+(n.streamName?st+jr+n.streamName:"")}function Mt(n){let e=n.split(st),t=e.shift();if(!t)throw new Error("Illegal stream description: "+n);let i=null,r,a=0;for(let p of e)switch(p.charAt(0)){case Wr:i=ka(p.slice(1));break;case jr:r=p.slice(1);break;case Nt:a=Number.parseInt(p.slice(1),10);break;default:throw new Error("Unexpected parameter type "+p.charAt(0)+" in stream description "+n)}return{participantId:I.compose(t,a),mediaType:i,streamName:r}}function ka(n){for(let e of Object.keys(De))if(e===n)return De[e];return null}function Di(n,e){return n===null||e===null?n===null&&e===null:!(n.maxDimension!==e.maxDimension||n.maxBitrateK!==e.maxBitrateK||n.maxFramerate!==e.maxFramerate||n.degradationPreference!==e.degradationPreference)}function $t(n,e){return!(!Di(n.camera,e.camera)||!Di(n.screenSharing,e.screenSharing))}function Ai(n,e){return{camera:Object.assign({},n.camera,e.camera),screenSharing:Object.assign({},n.screenSharing,e.screenSharing)}}function Kr(n){try{return btoa(JSON.stringify(n))}catch(e){o.warn("WaitingParticipant: failed convert to string",n,e)}return null}function $r(n){try{return JSON.parse(atob(n))}catch(e){o.warn("WaitingParticipant: failed convert from string",n,e)}return null}var Dt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,u.log(_.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,u.log(_.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(o.log("Failed to fix RV"),u.log(_.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),u.log(_.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,o.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===de.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var qt=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(d.muteMode||!((s=this._output)==null?void 0:s.audioTrack))return;let e=y.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{o.warn("Error on play audio"),S.onAutoplayError()},r=p=>{t.srcObject=new MediaStream([p]),t.load();let l=t.play();l?l.catch(i):i()},a=()=>{var l;o.debug("Recover audio playback");let p=(l=this._output)==null?void 0:l.audioTrack;p?r(p):o.warn("Broken audio track")};t.onpause=a,t.onstalled=a,t.onerror=a,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return c(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=y.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw u.log(_.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var wa=90,xa=3,Jt=class extends q{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),S.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>wa?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=xa)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var Na=44100,At=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=y.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=Na/this._fftBins.length,t=Math.ceil(d.voiceParams.minFreq/e),i=Math.floor(d.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((a,s)=>a+s,0)/e.length/255,r=this._lastSmoothedLevel*d.voiceParams.smoothing+i*(1-d.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var Yt=class extends q{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&S.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,d.voiceParams.interval)};this._interval=window.setTimeout(t,d.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,Pe.SOURCE_CHANGED,r=>{r.kind===de.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new At("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var qr="videochat-epi",La=5e3,Ua=3e4,Ze=class extends q{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,L.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(qr)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return c(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&d.perfStatReportEnabled&&this._previousTimestamp+La<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),d.callStatReportEnabled&&this._previousCallStatReportTimestamp+Ua<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return c(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(qr,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,a)=>(a.kind==="video"?(a.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+a.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+a.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=a.framesDropped,r.nack_sent+=a.nackCount,r.pli_sent+=a.pliCount,r.fir_sent+=a.firCount):(a.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+a.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+a.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=a.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=a.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=a.removedSamplesForAcceleration,r.concealed_audio_samples+=a.concealedSamples,r.silent_concealed_audio_samples+=a.silentConcealedSamples,r.audio_concealment_events+=a.concealmentEvents),r),t),e.outbound.rtps.reduce((r,a)=>(a.kind==="video"&&(r.nack_received+=a.nackCount,r.pli_received+=a.pliCount,r.fir_received+=a.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,a=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,p=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,l=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,m=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=a/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=p/r*1e3,i.concealed_silent_audio_samples=l/r*1e3,i.concealment_audio_avg_size=p/m,i.total_audio_energy=t.total_audio_energy}u.logCustom("callStat",i),o.log("Sent call stats",i),this._previousCallStatReport=t}};var Ba=1e3;function pe(n,e,t=0){return e in n&&n[e]?n[e]:t}function Jr(...n){return e=>{for(let t of n)if(t(e))return!0;return!1}}function Je(n,e){return t=>t[n]===e}function Va(n){return(e,t)=>e[n]-t[n]}function zt(n,e){return e.reduce((t,i)=>(t[i[n]]=i,t),{})}function Fa(n){let e={},t=[];for(let i of n)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Ha(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Oi(n){return Object.keys(n).filter(e=>n[e]!==void 0).map(e=>[e,n[e]]).reduce((e,t)=>(e[t[0]]=Ha(t[1])?Oi(t[1]):t[1],e),{})}function Ga(n){let e=[];for(let t of n)t.forEach(i=>e.push(i));return e}function Wa(n){return c(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...n.getReceivers().map(t=>t.getStats())),e.push(...n.getSenders().map(t=>t.getStats()))):e.push(n.getStats()),Promise.all(e).then(Ga).then(Fa)})}function ja(n){let e=n.filter(Je("type","candidate-pair")).sort(Va("priority")).find(Jr(Je("nominated",!0),Je("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=n.find(Je("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=n.find(Je("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),Oi(t)}function Ka(n,e){let t=zt("id",n),i=n.filter(Jr(Je("type","inbound-rtp"),Je("type","outbound-rtp")));y.browserName()==="Firefox"&&(i=Object.values(i.reduce((a,s)=>{if(!a[s.ssrc])a[s.ssrc]=s;else{let p=Object.assign({},a[s.ssrc],s),l=a[s.ssrc].isRemote?s:a[s.ssrc];p.id=l.id,p.type=l.type,delete p.isRemote,delete p.remoteId,a[p.ssrc]=p}return a},{})));let r={};if(y.browserName()==="Safari"){let a=n.filter(Je("type","track"));r=zt("trackIdentifier",a)}return i.map(a=>{let s=Number(a.ssrc),p=a.mediaType||a.kind,l=a.trackId,m=a.type,C=a.codecId;if(y.browserName()==="Safari"){let B=/^.+_([\d]+)$/.exec(a.id);if(B&&(s=parseInt(B[1],10)),p=a.id.indexOf("Audio")>0?"audio":"video",e[s]){let M=p+"-"+e[s];r[M]&&(l=r[M].id)}}if(!m||!s||!p)return null;let R={ssrc:s,type:m,kind:p,bytesReceived:pe(a,"bytesReceived"),bytesSent:pe(a,"bytesSent"),jitter:pe(a,"jitter"),packetsLost:pe(a,"packetsLost"),packetsReceived:pe(a,"packetsReceived"),packetsSent:pe(a,"packetsSent"),fractionLost:pe(a,"fractionLost"),pliCount:pe(a,"pliCount"),firCount:pe(a,"firCount"),nackCount:pe(a,"nackCount"),userId:e[s]};if(p==="video"){let B=pe(a,"framesDecoded"),M=pe(a,"totalInterFrameDelay"),H=pe(a,"totalSquaredInterFrameDelay");R.interframeDelayVariance=(H-M*M/B)/B}if(p==="audio"&&(R.totalSamplesReceived=pe(a,"totalSamplesReceived"),R.concealedSamples=pe(a,"concealedSamples"),R.insertedSamplesForDeceleration=pe(a,"insertedSamplesForDeceleration"),R.removedSamplesForAcceleration=pe(a,"removedSamplesForAcceleration"),R.silentConcealedSamples=pe(a,"silentConcealedSamples"),R.concealmentEvents=pe(a,"concealmentEvents"),R.totalAudioEnergy=pe(a,"totalAudioEnergy")),C&&t[C]){let B=t[C];R.clockRate=B.clockRate,R.mimeType=B.mimeType}if(l&&t[l]){let B=t[l];R.frameHeight=B.frameHeight,R.frameWidth=B.frameWidth,R.framesDecoded=B.framesDecoded,R.framesReceived=B.framesReceived,R.framesDropped=B.framesDropped}return Oi(R)}).filter(a=>!!a)}function $a(n,e){if(!e||!e.rtps||!n.rtps)return n;let t=zt("ssrc",n.rtps),i=zt("ssrc",e.rtps),r=(n.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(a=>{let s=t[a],p=i[a];if(!(!s||!p)){if(s.bytesReceived&&s.bytesReceived>p.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-p.bytesReceived)/r)),s.bytesSent&&s.bytesSent>p.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-p.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>p.packetsReceived||s.packetsLost>p.packetsLost){let l=s.packetsLost-p.packetsLost,m=s.packetsReceived-p.packetsReceived;s.packetLoss=parseFloat((100*l/(l+m)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&p.framesDropped&&s.framesDropped>p.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-p.framesDropped)/r).toFixed(0)))}}),n}function Ot(i,r){return c(this,arguments,function*(n,e,t={}){let a=yield Wa(n),s={timestamp:Date.now(),transport:ja(a),rtps:Ka(a,t)};return e?$a(s,e):(yield I.delay(Ba),Ot(n,s,t))})}var Qt=.8,et=class extends q{constructor(e,t,i,r,a){super();this._remoteSDP={};this._remoteCandidates={};this._state=N.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=a,this._perfStatReporter=new Ze(this,i,!0),this.subscribe(this._signaling,ve.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Pe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Pe.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:d.iceServers,iceTransportPolicy:d.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,d.p2pAudioRed),this._applySettings()}catch(s){u.log(_.ERROR,"addTrack-direct"),o.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===N.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==N.IDLE&&e!==N.CLOSED&&e!==N.FAILED&&this._startStatInterval()}open(e=null){return c(this,null,function*(){if(this._isOpen){o.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(o.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,d.p2pAudioRed),this._applySettings()}catch(i){u.log(_.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(N.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={}})}updateSettings(e){$t(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(L.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(o.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(N.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(N.CLOSED)),this._triggerEvent(L.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(L.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,a;switch(e.notification){case O.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case O.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case O.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((a=e.data.sdk)==null?void 0:a.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=I.getPeerIdString(e.peerId);I.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){o.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw u.log(_.ERROR,"addIceCandidate-direct"),o.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else o.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return c(this,null,function*(){if(!this._remoteCandidates[e]){o.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){o.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw u.log(_.ERROR,"setRemoteDescription-direct"),o.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){o.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(L.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(L.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return c(this,null,function*(){e.candidate&&this._signaling.ready&&(o.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(o.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>c(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(o.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===N.IDLE||e===N.OPENED?this._setState(N.CONNECTING):this._setState(N.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),u.log(_.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(N.CONNECTED),this._stopReconnection(),I.getPeerConnectionHostInfo(this._pc).then(e=>{e&&u.log(_.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(N.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(o.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},d.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(o.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(me.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(u.log(_.ICE_RESTART),o.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):o.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,o.error("Ice restart failed",{participantId:this._participantId}),u.log(_.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return c(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return o.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw o.error("Unable to create offer",i,{participantId:this._participantId}),u.log(_.ERROR,"createOffer-direct"),i}).then(i=>c(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=et._patchDescription(i),o.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw o.error("Unable to set local description",i,{participantId:this._participantId}),u.log(_.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return c(this,null,function*(){return o.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw o.error("Unable to create answer",e,{participantId:this._participantId}),u.log(_.ERROR,"createAnswer-direct"),e}).then(e=>c(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=et._patchDescription(e),o.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw o.error("Unable to set local description",e,{participantId:this._participantId}),u.log(_.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=I.patchSDP(e.sdp,d.preferH264&&y.canPreferH264(),y.isBrokenH264(),d.preferVP9,t&&d.audioNack,d.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{o.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),u.log(_.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Ot(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:me.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:me.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(L.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,d.statisticsInterval)})};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=ae=>ae.rtt<=this._networkLimits.goodNet.rtt&&ae.loss<=this._networkLimits.goodNet.loss,i=ae=>ae.rtt>=this._networkLimits.badNet.rtt||ae.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,a=e.inbound.rtps.reduce((ae,Ve)=>Math.max(ae,Ve.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-Qt)+r*Qt,loss:this._lastNetworkStat.loss*(1-Qt)+a*Qt},p=i(s),l=t(s),m=i(this._remoteNetworkStat),C=t(this._remoteNetworkStat),R=i(this._lastNetworkStat),B=t(this._lastNetworkStat),ee=p||m?.2:l&&C?1:0,Ce=Date.now();if((R!==p||B!==l||Ce-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(ae=>{o.warn("Unable to send [bad-net]",ae)})),ee){let ae={};ae[this._participantId]=ae[""]=ee,this._triggerEvent(L.NETWORK_STATUS,ae)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=I.sdpFingerprint(e);if(t===null){o.warn("Fingerprint calculation is unsupported");return}this._fingerprint===null?this._fingerprint=t:(S.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=I.applySettings(this._pc,e,this._prevConsumerSettings))}};var Yr=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Yr||{}),kt=Yr;import{decode as tt}from"messagepack";var ki=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var a,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let p=tt(r);return Object.entries(p).forEach(([H,ee])=>{let Ce=Mt(H);this.streamDescriptionByCompactId.set(ee,Ce)}),null;case 2:case 4:let l=tt(r),m=[];for(let H of l){let ee=this.getStreamDescription(H);ee&&m.push(ee.participantId)}return i===2?{type:"notification",notification:O.AUDIO_ACTIVITY,activeParticipants:m}:{type:"notification",notification:O.STALLED_ACTIVITY,stalledParticipants:m};case 3:let C=tt(r);return{type:"notification",notification:O.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(C))==null?void 0:a.participantId};case 5:let R=tt(r);return{type:"notification",notification:O.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:R[0],maxDimension:R[1]}};case 6:let B=tt(r),M={};for(let[H,ee]of Object.entries(B)){let Ce=(s=this.getStreamDescription(Number(H)))==null?void 0:s.participantId;Ce&&(M[Ce]=ee/100)}return{type:"notification",notification:O.NETWORK_STATUS,statuses:M};case 7:return this._createParticipantSourcesUpdateNotification(r);case 8:{let ee=tt(r).map(Ce=>{var j;let[ae,Ve,se,Re,be]=Ce;return{participantId:(j=this.getStreamDescription(ae))==null?void 0:j.participantId,gain:Ve,pause:se,offset:Re,duration:be}});return{type:"notification",notification:O.MOVIE_UPDATE_NOTIFICATION,data:ee}}default:return o.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=tt(e),i=[];for(let[r,a]of Object.entries(t)){let s=a[0],p=a[1],l=a[2],m;if(s!==null){if(m=this.getStreamDescription(s),!m){o.error(`could not uncompress participant ID ${s}`);continue}}else m=null;if(l===null){o.error("unexpected null sequenceNumber",r,a);continue}let C=we.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,R=p?p>>>0:null;i.push({participantStreamDescription:m,streamId:C,rtpTimestamp:R,sequenceNumber:l})}return{type:"notification",notification:O.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var qa=90,Ja=4294967295,Ae=class extends q{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=N.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,ve.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Pe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Pe.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,Pe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Ze(this,e),this._serverSettings=i,o.debug("ServerTransport: Created")}getState(){return this._state||N.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==N.IDLE&&e!==N.CLOSED&&e!==N.FAILED&&this._startStatInterval()}open(e=!1){if(this._isOpen){o.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(o.error("ServerTransport: Closed",e),this._setState(N.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(N.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){$t(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,Ae._closeDataChannel(this._producerNotification),Ae._closeDataChannel(this._producerCommand),Ae._closeDataChannel(this._producerScreen),Ae._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(L.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){o.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let a=r.readyState;a==="open"?(o.debug(`[${t}] data channel opened`),r.onerror=s=>{o.error(`[${t}] data channel error`,s)},i(r)):o.error(`[${t}] data channel open failed, state [${a}]`)}}_openConnection(e=!1){o.debug("ServerTransport: Open single connection");let t={};y.baseChromeVersion()&&(t.sdpSemantics=Ae._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=I.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Ae._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,kt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new ki,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,kt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,kt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,d.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){o.error("ServerTransport: Unable to add media source tracks",i),u.log(_.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,kt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(N.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==N.OPENED&&(this._setState(N.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(L.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(L.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(L.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(L.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
+ `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${we.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!d.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new ut(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!d.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new pt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(L.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(L.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!d.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==de.video)return;let r=!this._disabledSenders.has(i),a=e.maxDimension!==0;if(r&&!a){o.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(y.getBlackMediaTrack()).catch(p=>{o.error("Could not disable video upload",p)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&a&&s){o.log("Enabling video upload"),this._disabledSenders.delete(i);let p=i.track;p.enabled=s.enabled,i.replaceTrack(s).then(()=>p.stop()).catch(l=>{o.error("Could not enable video upload",l)})}I.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(L.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,d.statisticsInterval)};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return c(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Ot(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(L.REMOTE_DATA_STATS,{inbound:{topology:me.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:me.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=we.AUDIO_MIX,r=this._statBytes[i],a=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(a=!0),r.stalled!==a&&this._triggerEvent(L.REMOTE_ALL_STALL,a)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:a}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Ze.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:d.producerNotificationDataChannel?7:0,producerCommandDataChannelVersion:d.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:d.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:d.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:Ae._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount,red:d.serverAudioRed};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return c(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,o.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(o.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw o.error("[single] unable to set remote offer",i),u.log(_.ERROR,"setRemoteDescription-single"),i}).then(()=>c(this,null,function*(){if(o.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw o.error("[single] unable to create answer",i),u.log(_.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=I.patchSDP(i.sdp,!1,y.isBrokenH264(),!1),i)).then(i=>c(this,null,function*(){if(o.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw o.error("[single] unable to set local answer",i),u.log(_.ERROR,"setLocalDescription-single"),i}).then(i=>c(this,null,function*(){o.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),o.debug("[single] remote offer has been processed")})).catch(i=>{o.warn("[single] unable to send local answer",i),u.log(_.ERROR,"acceptProducer")}).then(()=>c(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){o.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return c(this,null,function*(){if(!!this._isOpen)switch(e.notification){case O.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case O.REALLOC_CON:this._reconnect();break;case O.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case O.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case O.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case O.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return c(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),d.breakVideoPayloadTypes&&(o.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){o.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=a=>{this._triggerEvent(L.REMOTE_TRACK_REMOVED,i.id,i,a.track)}),i.getTracks().find(a=>a.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(L.REMOTE_TRACK_ADDED,i.id,i,t.track)):o.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){o.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(o.debug("[single] connection state changed",{state:e.connectionState},t),u.log(_.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===N.IDLE||i===N.OPENED?this._setState(N.CONNECTING):e.iceConnectionState==="checking"&&this._setState(N.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(N.RECONNECTING);break;case"connected":this._setState(N.CONNECTED),I.getPeerConnectionHostInfo(e).then(r=>{r&&u.log(_.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(d.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{o.error("ServerTransport: Unable to replace track",r),u.log(_.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=y.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(y.browserName(),Number(y.browserVersion()))}getStreamWaitingTimeMs(e,t){if(!this._pc)return u.log(_.PAT_WAITING_TIME_ERROR,"noConnection"),o.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return u.log(_.PAT_WAITING_TIME_ERROR,"noReceiver"),o.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return o.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return u.log(_.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),o.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let p=t-s&Ja,l=Math.ceil(p/qa);return Math.min(100,Math.max(0,l))}};var L=(M=>(M.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",M.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",M.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",M.REMOTE_ALL_STALL="REMOTE_ALL_STALL",M.REMOTE_DATA_STATS="REMOTE_DATA_STATS",M.STATE_CHANGED="STATE_CHANGED",M.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",M.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",M.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",M.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",M.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",M.NETWORK_STATUS="NETWORK_STATUS",M.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",M))(L||{}),N=(p=>(p.IDLE="IDLE",p.OPENED="OPENED",p.CONNECTING="CONNECTING",p.RECONNECTING="RECONNECTING",p.CONNECTED="CONNECTED",p.CLOSED="CLOSED",p.FAILED="FAILED",p))(N||{}),me=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(me||{}),wi=class extends q{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,ve.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){o.log("Update transport settings",e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){o.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,i=!1){let r=!1;for(let a of e){if(this._opened.indexOf(a)!==-1){o.warn(`The participant [${a}] has already had opened transport`);continue}if(this._allocated.indexOf(a)===-1){o.warn(`The participant [${a}] has no allocated transport`);continue}this._opened.push(a),r=!0}!r||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),o.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&o.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===O.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===O.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(o.log(`Topology changed ${this._topology} -> ${e.topology}`),u.log(_.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],a=e.offerToDeviceIdxs||[],s=i.length&&r.length?I.composeParticipantId(i[0],r[0],a[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){o.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&o.warn("Topology changed to DIRECT, but the allocated participants count more then one");let p=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=s===p;this._directTransport=this._createDirectTransport(p,l)}this._opened.indexOf(p)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new et(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._dtListeners&&this._dtListeners.length>0&&o.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new Ae(this._signaling,this._mediaSource,this._serverSettings);return this._stListeners&&this._stListeners.length>0&&o.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;d.noiseSuppression!==e&&(d.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(u.log(_.PAT_WAITING_TIME_ERROR,"wrongTopology"),o.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(u.log(_.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var it=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(it||{}),xi=class extends q{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,L.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,L.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,L.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,L.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===de.audio&&((r=this._detector)==null||r.destroy(),this._detector=new At(e,t),!this._interval)){let a=()=>{this._collectVolumes(),this._interval=window.setTimeout(a,d.voiceParams.interval)};this._interval=window.setTimeout(a,d.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===de.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===we.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e===me.DIRECT&&(this._activeParticipants=null)}};var Ni=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(Ni||{}),Li=class extends q{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i===me.SERVER,this.subscribe(e,it.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,L.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,L.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let a=e[r].smoothed;a>t&&a>d.voiceParams.threshold&&(t=a,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*d.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent("SPEAKER_CHANGED",e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e===me.SERVER}};var Xt=class extends q{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,L.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,it.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===N.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),d.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),d.specListenerParams.volumeTimeout))),t===N.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),u.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==N.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),u.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),u.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Ya=1e3,za=1e4;var Qa=15,U=class extends q{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=G.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;u.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),u.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new qt,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Ya))}static current(){return U._current}static hangupAfterInit(){U._activationMutex&&!U._current&&(U._delayedHangup=!0)}static id(){var e,t;return((t=(e=U._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",a=!1,s=!1){return c(this,null,function*(){if(U._activationMutex)throw u.log(_.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new k(P.FAILED);U._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let p=this._mediaSource.getMediaSettings();t===He.CHAT||e.length>1?this._logWithMediaSettings(_.OUTGOING_MULTIPARTY_CALL,p):this._logWithMediaSettings(_.OUTGOING_CALL,p);let l=yield this._startConversation(e,t,je.OUTGOING,i,r,a,s);if(!this._conversation)throw new k(P.UNKNOWN_ERROR);if(this._participantState=G.ACCEPTED,this._signaling.changeMediaSettings(p),yield this._registerParticipants(l.conversation.participants),this._processConnectionData(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),U._delayedHangup)throw new k(P.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let m=Object.values(this._participants),C;return d.batchParticipantsOnStart&&(C=I.mapSharedParticipants(m)),S.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),S.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,C),S.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),U._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(m,$.WAITING),this._conversation}catch(p){throw this._close(p,"Unable to start conversation"),p}finally{U._activationMutex=!1}})}onJoin(e){return c(this,null,function*(){var t;if(U._activationMutex)throw u.log(_.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new k(P.FAILED);U._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.JOIN_CONVERSATION,r);let a=yield this._joinConversation(e);if(!this._conversation)throw new k(P.UNKNOWN_ERROR);return this._conversation.observer=i,S.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(o.log("In waiting hall"),U._current=this,U._activationMutex=!1,this._signaling.readyToSend(),S.onLocalStatus($.WAITING_HALL),this._conversation):this._onJoinPart2(a)}catch(i){throw U._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return c(this,null,function*(){o.debug("Join conversation part 2"),U._activationMutex=!0;try{if(this._participantState=G.ACCEPTED,!this._conversation||!this._mediaSource)throw new k(P.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),U._delayedHangup)throw new k(P.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=I.mapSharedParticipants(t)),S.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),S.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),U._current=this,d.batchParticipantsOnStart||this._setParticipantsStatus(t,$.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{U._activationMutex=!1}})}onPush(r){return c(this,arguments,function*(e,t=X.USER,i){if(U._activationMutex)throw o.warn("Conversation: there is already running activation"),new k(P.REJECTED);U._activationMutex=!0;try{let a=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new k(P.UNKNOWN_ERROR);if(!a.conversation.participants.find(p=>{var l;return p.state===G.CALLED&&p.id===((l=this._conversation)==null?void 0:l.userId)}))throw o.log("Push rejected (there is an active call)"),u.log(_.PUSH,"rejected"),new k(P.REJECTED);if(yield this._registerParticipants(a.conversation.participants),this._processConnectionData(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),u.log(_.PUSH,"accepted"),U._current=this,U._delayedHangup)throw new k(P.CANCELED);U._activationMutex=!1}catch(a){throw U._activationMutex=!1,this._close(a,"Unable to handle inbound call push"),a}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(ni.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>I.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return c(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new k(P.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),S.onCallAccepted(),this._state="ACTIVE",this._participantState=G.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return c(this,null,function*(){if(this._state!=="IDLE")throw u.log(_.ERROR,"acceptIncoming"),o.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new k(P.UNKNOWN_ERROR);this._state="PROCESSING",o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=G.ACCEPTED;let i=Object.values(this._participants),r;d.batchParticipantsOnStart&&(r=I.mapSharedParticipants(i)),S.onCallAccepted(),S.onLocalStream(this._mediaSource.getStream(),t),S.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),S.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let a=Object.values(this._conversation.muteStates);return(a.includes(Ke.MUTE)||a.includes(Ke.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),d.batchParticipantsOnStart||this._setParticipantsStatus(i,$.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return c(this,null,function*(){var e;if(this._state!=="IDLE")throw u.log(_.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",o.debug("Decline incoming call"),this._logWithMediaSettings(_.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=G.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(P.REJECTED)),this._close(new k(P.REJECTED))})}hangup(){return c(this,null,function*(){o.debug("Hangup");let e=this._state==="ACTIVE"?P.HUNGUP:P.CANCELED;u.log(_.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new k(e))):S.onHangup(new k(P.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return c(this,null,function*(){if(!this._signaling.ready){this._close(new k(P.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=P.UNKNOWN_ERROR);let a=i.participant;yield this._onAddParticipant(I.composeId(a),a,r)})}removeParticipant(e,t=!1){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let a of e)(a.state===G.CALLED||a.state===G.ACCEPTED)&&(this._transport.isAllocated(a.id)||this._transport.allocate(a.id,t)),a.state===G.ACCEPTED&&i.push(a.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&o.error(t,e),o.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(P.FAILED):u.log(_.ERROR,e.hangup),U._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([P.CANCELED,P.NOT_FRIENDS,P.CALLEE_IS_OFFLINE,P.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===P.REJECTED&&!e.remote){S.onHangup(e,i),this.destroy();return}if(e.hangup===P.HUNGUP&&(!e.remote||this._participantState===G.CALLED)){S.onHangup(e,i),this.destroy();return}if(e.hangup===P.MISSED&&!e.remote){S.onHangup(e,i),this.destroy();return}if(e.hangup===P.SOCKET_CLOSED&&U._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===P.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=G.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),u.destroy(),this._conversation=null,U._current=null,U._delayedHangup=!1,S.onHangup(e||new k(P.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;o.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),u.destroy(),this._conversation=null,U._current=null,U._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return c(this,null,function*(){let t=yield this._api.getConversationParams(e);o.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:a}=t;if(a&&i.push(a),r){let s=r.urls.filter((p,l,m)=>m.indexOf(p)===l);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return d.iceServers=i,d.wssBase=t.endpoint,d.wssToken=t.token,t.client_type&&(d.clientType=t.client_type),t})}_addGeoParamsToEndpoint(e,t){return t.isp_as_no&&(e+=`&ispAsNo=${t.isp_as_no}`),t.isp_as_org&&(e+=`&ispAsOrg=${t.isp_as_org}`),t.loc_cc&&(e+=`&locCc=${t.loc_cc}`),t.loc_reg&&(e+=`&locReg=${t.loc_reg}`),e}_startConversation(e,t,i,r,a="",s=!1,p=!1){return c(this,null,function*(){let l=I.uuid();o.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let m=r.includes(ue.VIDEO),C=yield this._api.startConversation(l,e,t,m,a,s,p);o.debug("Api.startConversation",C);let R=yield this._getConversationParams(C.id);C.endpoint=this._addGeoParamsToEndpoint(C.endpoint,R);let B=yield this._connectSignaling(Ge.START,C);return yield this._setConversation(C,B,i),B})}_joinConversation(e){return c(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:a,observedIds:s}=e;o.debug("Conversation: join",{conversationId:t,joinLink:a,observedIds:s});let p=i.includes(ue.VIDEO),l;if(t)l=yield this._api.joinConversation(t,p,r);else if(a)l=yield this._api.joinConversationByLink(a,p,s);else throw new k(P.UNKNOWN_ERROR);o.debug("Api.joinConversation",l),yield this._getConversationParams(l.id);let m=yield this._connectSignaling(Ge.JOIN,l);return yield this._setConversation(l,m,je.JOINING),m})}_prepareConversation(r){return c(this,arguments,function*(e,t=X.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let a=this._api.getUserId();if(!a)throw new k(P.UNKNOWN_ERROR);let s=yield this._getConversationParams(e),p=s.device_idx||0,l=`${d.wssBase}?userId=${a}&entityType=${t}&deviceIdx=${p}&conversationId=${e}&token=${d.wssToken}`;l=this._addGeoParamsToEndpoint(l,s);let m={id:e,peerId:i,endpoint:l,is_concurrent:!1,p2p_forbidden:!1,device_idx:p},C=yield this._connectSignaling(Ge.ACCEPT,m);return U._current&&(U._current._participantState===G.ACCEPTED||U._current._participantState===G.CALLED)?(o.log("Push rejected (busy)"),u.log(_.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(P.BUSY),Promise.reject({hangup:P.BUSY})):(U._current&&(U._current.destroy(),U._current=null),yield this._setConversation(m,C,je.INCOMING,t),C)})}_createParticipant(e){return c(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:Te(),participantState:{},state:G.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[]},e);if(e.externalId){let r=I.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(r,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return((i=t.observedIds)==null?void 0:i.length)&&(t.externalId.observer=!0),t})}_getParticipantId(e){return c(this,null,function*(){try{let t=I.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new k(P.NETWORK_ERROR),t),t}})}_setConversation(a,s,p){return c(this,arguments,function*(e,t,i,r=X.USER){let l=t.conversation.participants.map(M=>M.id);yield this._api.prepareUserIds(l);let m=this._api.getUserId(),C=e.device_idx||0;if(!m){let M=(t.conversation.participants||[]).find(H=>I.comparePeerId(H.peerId,t.peerId));if(!M)throw new k(P.UNKNOWN_ERROR);m=Number(M.id),M.idType&&(r=M.idType),M.deviceIdx&&(C=M.deviceIdx),this._api.setUserId(m)}let R=I.composeParticipantId(m,r,C),B=yield this._getParticipantId(R);this._conversation={userId:m,compositeUserId:R,externalId:B,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||me.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),u.log(_.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new k(P.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||me.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new _i;return this.subscribe(e,Pe.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Pe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new Dt(e),e}_connectSignaling(e,t){return c(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,ve.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,ve.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,ve.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return c(this,null,function*(){if(!!this._conversation)for(let t of e){let i=I.composeId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),S.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===G.HUNGUP||t.state===G.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],P.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&Se.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:Te(t.mediaSettings),participantState:I.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?$.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),S.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){I.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(ai.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new wi(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new Jt,this.subscribe(this._transport,L.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,L.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,L.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,L.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,L.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,L.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,L.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,L.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,L.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,L.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,L.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===je.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===G.ACCEPTED||t.state===G.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new xi(this._transport),this.subscribe(this._volumesDetector,it.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Li(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,Ni.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Yt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Xt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=y.getCameras().length,t=y.getMicrophones().length;o.debug("Cameras: "+e+(y.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(y.hasMicrophonePermission()?"✔":"✖")),u.log(_.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){u.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===G.CALLED||e.state===G.ACCEPTED||this._state==="CLOSE"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),!!this._participants[e.id]&&(t===P.HUNGUP?this._setParticipantsStatus([e],$.HANGUP):this._setParticipantsStatus([e],$.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:De.CAMERA,stopStream:!0}]),delete this._participants[e.id],S.onRemoteRemoved(e.externalId)))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(a=>a.stop()),(i=e.secondStream)==null||i.getTracks().forEach(a=>a.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){o.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return c(this,null,function*(){o.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===G.ACCEPTED||r.state===G.CALLED)){o.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&Se.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:Te(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}),r=this._participants[e]),this._setParticipantsStatus([r],$.WAITING),i?(r.state=G.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=G.CALLED,this._transport.allocate(r.id,!0),u.log(_.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){o.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=Qa;i++){let r=I.compose(e,i),a=this._participants[r];a&&t.push(a)}if(!t.length){o.warn(`Participant [${e}] isn't in conversation`);return}if(this._transport)for(let i of t)this._transport.close(i.id);u.log(_.REMOVE_PARTICIPANT)}changeDevice(e){return c(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new Dt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(re.UNKNOWN)})}toggleScreenCapturing(e){return c(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(re.UNKNOWN)})}setVideoStream(e,t=!1){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return c(this,null,function*(){if(this._mediaSource)return u.log(_.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return c(this,null,function*(){if(this._mediaSource)return u.log(_.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return c(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let a=typeof r.uid=="object"?r.uid:Se.fromId(r.uid),s=Se.toString(a);i[s]=r.priority}for(let r of Object.values(this._participants)){let a=Se.toString(r.externalId);i.hasOwnProperty(a)&&(t[r.id]=i[a])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return c(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return c(this,null,function*(){let t={};return t[qe(e)]="kf",this._signaling.updateDisplayLayout(t)})}updateDisplayLayout(e){return c(this,null,function*(){if(e.length<1||!this._signaling.ready)return;o.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let a=typeof r.uid=="object"?r.uid:Se.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(a);if(!s){let C=Se.toString(a);o.log(`Unknown participant external ID ${C}`);continue}let p=I.compose(s,a.deviceIdx),l=qe({participantId:p,mediaType:r.mediaType,streamName:r.streamName}),m=this._participants[p];m&&(m.lastRequestedLayouts[l]=r),U._isStopStreaming(r)?this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now()):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&d.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=U._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>d.videoTracksCount;){let r=i.next();if(r.done){o.error("Cannot accommodate all streaming requests: tracks available "+d.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]=U._layoutToString({stopStream:!0})}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(o.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Mt(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===De.STREAM||i.mediaType===De.SCREEN)?S.onRemoteLive(r.externalId,i.streamName,null):S.onRemoteStream(r.externalId,null),u.log(_.PAT_DEALLOCATED)):o.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return c(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,a]of Object.entries(t.errorCodeByParticipantId||{})){let s=Mt(r),p=this._participants[s.participantId];if(p){let l;typeof a!="number"?(o.warn(`Unexpected error code ${a} received for participant ${s.participantId}`),l=lr.UNKNOWN_ERROR):l=ur(a),i.push({externalId:p.externalId,errorReason:l})}}if(i&&i.length)throw new Zt("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+za>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=U._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(U._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),t}_onParticipantSourcesUpdate(e){if(this._conversation){o.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return c(this,null,function*(){o.log("Promoted in waiting hall",!e.demote),e.demote?(o.log("Kicked from waiting hall"),this._close(new k(P.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return c(this,arguments,function*(e,t=0,i=[]){o.log(`Chat room updated: ${e}`);let a=[],s=[];i.length&&(i.forEach(p=>{if(p.externalId){let l=fe.fromSignaling(p.externalId);a.push(l),this._api.cacheExternalId(p.id.id,l)}else s.push(I.decomposeId(p.id.id).id)}),s.length&&!a.length&&(a=yield this._api.getExternalIdsByOkIds(s))),S.onChatRoomUpdated(e,t,a)})}_onSharedMovieUpdate(e){o.log(`Shared movie updated: ${e.notification}`);let{compositeUserId:t,externalId:i}=this._conversation,{data:r}=e;for(let a of r)if(a.participantId===t)S.onLocalLiveUpdate(i,a);else{let p=this._participants[a.participantId];p&&S.onRemoteLiveUpdate(p.externalId,a)}}_waitForStreamIfNeeded(e){var p,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===De.SCREEN)return;let i=qe(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){o.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),u.log(_.PAT_OUTDATED_RESPONSE);return}let a=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(a,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let m=t.participantId,C=this._participants[m],{compositeUserId:R,externalId:B}=this._conversation,M=R===m;if(!C&&!M){u.log(_.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${m}`);return}let H=M?B:C.externalId,ee=this._streamByStreamId.get(a);if(!ee){u.log(_.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${a}`);return}u.log(_.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,a);let Ce=(p=e.participantStreamDescription)==null?void 0:p.mediaType;if(Ce===De.STREAM||Ce===De.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&(M?S.onLocalLive(H,e.participantStreamDescription.streamName,ee):S.onRemoteLive(H,e.participantStreamDescription.streamName,ee));else if(!M){let ae=(d.producerScreenTrack?null:C.secondStream)||ee;S.onRemoteStream(C.externalId,ae)}}else{o.debug(`Waiting for ${s} until stream ${a} for ${i} is switched`);let m=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,m)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(qe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(qe(i)))return i}else{let i={participantId:t,mediaType:De.CAMERA};if(this._streamIdByStreamDescription.has(qe(i)))return i;let r={participantId:t,mediaType:De.SCREEN};if(this._streamIdByStreamDescription.has(qe(r)))return r}return o.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?I.includesOneOf(this._conversation.roles,[rt.ADMIN,rt.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!I.includesOneOf(this._conversation.roles,[rt.ADMIN,rt.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return c(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return c(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return c(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Zi(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return c(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=$r(e));let a=yield this._signaling.getWaitingHall(r,t,i);if(a.error)return Promise.reject(a.message);let s=a.participants||[],p=[],l=[],m=null;return s.length&&(s.forEach(C=>{if(C.externalId){let R=fe.fromSignaling(C.externalId);p.push(R),this._api.cacheExternalId(C.id.id,R)}else l.push(I.decomposeId(C.id.id).id)}),l.length&&!p.length&&(p=yield this._api.getExternalIdsByOkIds(l)),a.hasMore&&(m=Kr(s[s.length-1].id))),{participants:p,pageMarker:m,totalCount:a.totalCount||0}})}promoteParticipant(e,t){return c(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return c(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return c(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return c(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(i){return c(this,arguments,function*({movieId:e,gain:t}){let r={movieId:e};(t||t===0)&&(r.gain=t);let a=yield this._signaling.addMovie(r);if(a.error)throw new Error(a.error);return{movieId:a.movieId,streamType:a.streamType}})}updateMovie(e,t,i,r){return c(this,null,function*(){let a={movieId:e};(t||t===0)&&(a.gain=t),i&&(a.offset=i),typeof r!==void 0&&(a.pause=r);let s=yield this._signaling.updateMovie(a);if(s.error)throw new Error(s.error)})}removeMovie(e){return c(this,null,function*(){let t={movieId:e},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",a=null){return c(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:a,streamMovie:!e},p=yield this._signaling.startStream(s);return p.error?Promise.reject(p.message):p})}stopStream(){return c(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return c(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return c(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return c(this,null,function*(){var r;if(e<d.videoMinWidth||t<d.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<d.videoMinWidth||i.effect.height<d.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");d.videoEffectMaxHeight=i.effect.height,d.videoEffectMaxWidth=i.effect.width}return d.videoMaxWidth=e,d.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return c(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return c(this,null,function*(){var t,i;!this._conversation||(o.debug("Local media stream changed",e.mediaSettings),S.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return c(this,null,function*(){var t,i;if(o.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;S.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){o.debug(`Remote media settings changed [${e}]`,t);let{compositeUserId:i,externalId:r}=this._conversation,a=e===i,s=this._participants[e];!s&&!a||(a||(s.mediaSettings=t),this._state==="ACTIVE"&&(a?S.onLocalMediaSettings(r,t):S.onRemoteMediaSettings(s.externalId,t)),this._specListener&&!a&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){o.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&S.onRemoteParticipantState(i.externalId,i.participantState))}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(o.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),S.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case O.ACCEPTED_CALL:return this._onAcceptedCall(e);case O.HUNGUP:return this._onHungup(e);case O.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case O.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case O.CLOSED_CONVERSATION:return this._onClosedConversation(e);case O.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case O.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case O.RATE_CALL_DATA:return this._onNeedRate();case O.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case O.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case O.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case O.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case O.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case O.REGISTERED_PEER:return this._onPeerRegistered(e);case O.SWITCH_MICRO:return this._onMicSwitched(e);case O.CHAT_MESSAGE:return this._onChatMessage(e);case O.CUSTOM_DATA:return this._onCustomData(e);case O.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case O.RECORD_STOPPED:return this._onRecordInfo(null);case O.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case O.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case O.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case O.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case O.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case O.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case O.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants);case O.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e)}}_onSignalingReconnect(e){return c(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let a of e.conversation.participants){let s=I.composeId(a),p=a.roles||[];if(s===this._conversation.compositeUserId){t=Te(a.mediaSettings),Et(this._conversation.roles,p)||this._onRolesChanged(s,p);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:a.id,participant:a,mediaSettings:a.mediaSettings});else{let m=Te(a.mediaSettings);Ir(m,l.mediaSettings)||this._changeRemoteMediaSettings(s,m);let C=I.mapParticipantState(a),R=l.participantState;I.isEqualParticipantState(C,R)||this._changeRemoteParticipantState(s,C),Et(p,l.roles)||this._onRolesChanged(l.id,p)}}for(let a of i)r.indexOf(a)<0&&this._removeParticipant(this._participants[a],P.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){o.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return c(this,null,function*(){let t=I.composeMessageId(e),i=I.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new k(P.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:Te(e.mediaSettings)}),r=this._participants[t]),r.state=G.ACCEPTED,r.mediaSettings=Te(e.mediaSettings),this._logWithMediaSettings(_.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===je.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){o.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=I.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new k(e.reason,{remote:!0}));return}let i=this._participants[t];if(!i){o.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===P.REJECTED?G.REJECTED:G.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,P.HUNGUP)}_onAddedParticipant(e){return c(this,null,function*(){var r,a;o.debug(`Participant added [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state!==G.HUNGUP&&i.state!==G.REJECTED){o.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&Se.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:Te(e.participant.mediaSettings),state:e.participant.state,participantState:I.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}),i=this._participants[t]),i.state=G.CALLED,i.mediaSettings=Te((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=I.mapParticipantState(e.participant),i.roles=((a=e.participant)==null?void 0:a.roles)||[],this._setParticipantsStatus([i],$.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return c(this,null,function*(){var r,a;o.debug(`Participant joined [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state===G.ACCEPTED){o.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&Se.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:Te(e.participant.mediaSettings),state:e.participant.state,participantState:I.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===je.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=G.ACCEPTED,i.mediaSettings=Te(e.mediaSettings),i.participantState=I.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],$.CONNECTED):this._setParticipantsStatus([i],$.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((a=this._conversation)==null?void 0:a.observer))),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new k(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=I.composeMessageId(e);this._changeRemoteMediaSettings(t,Te(e.mediaSettings))}_onParticipantStateChanged(e){let t=I.composeMessageId(e);this._changeRemoteParticipantState(t,I.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),S.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return c(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=Te(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),d.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){o.debug("Got settings update notification",e);let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Ai(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){o.debug("Got video quality update notification",e);let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=Ai(this._serverSettings,r),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=I.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return c(this,null,function*(){S.onDeviceSwitched(ue.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return c(this,null,function*(){let t=I.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),S.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return c(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=I.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),S.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return c(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getParticipantId(e.initiator);S.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else S.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!Et(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,S.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!Et(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,S.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return c(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],a=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){o.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let p=this._participants[e.participantId];p&&(o.debug(`Mute states for participant [${e.participantId}] changed`,i),S.onMuteStates(i,r,a,e.muteAll,e.unmute,p.externalId,s==null?void 0:s.externalId));return}I.isObjectsEquals(this._conversation.muteStates,i)&&I.isArraysEquals(this._conversation.unmuteOptions,r)&&!a.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(a,e.muteAll,e.unmute,t,s)))})}_processMuteState(){return c(this,arguments,function*(e=[],t=!1,i=!1,r=null,a=null){if(!this._conversation||!this._mediaSource||this._participantState!==G.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),p=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),m=Object.entries(s);for(let[C,R]of m)if(!(R!==Ke.MUTE&&R!==Ke.MUTE_PERMANENT)&&(this._isCallAdmin()&&R===Ke.MUTE_PERMANENT&&(s[C]=Ke.MUTE),!(!e.includes(C)||i)))switch(C){case ue.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(S.onDeviceSwitched(ue.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case ue.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(S.onDeviceSwitched(ue.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case ue.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(S.onDeviceSwitched(ue.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}S.onMuteStates(s,p,e,t,i,null,a==null?void 0:a.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?S.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&S.onLocalPin(!0)),this._participants[e]?S.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&S.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!Xi(this._conversation.options,e)&&(this._conversation.options=e,S.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let a;if(i===this._conversation.compositeUserId||i==="")a=this._conversation.networkRating;else if(this._participants[i])a=this._participants[i].networkRating;else continue;if(a!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,S.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;o.log("Received network status update: ",e),S.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){S.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,d.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){o.error("Received remote stream notification for a participant that has no track associated with it",r);return}let a=this._streamIdByStreamDescription.get(r);if(!a||this._streamWaitTimerByStreamDescription.has(r)){o.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(a);if(!s){u.log(_.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${a}`);return}S.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&S.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===me.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(zi.ADD_PARTICIPANT);S.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&S.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let a=this._participants[i];a&&a.externalId&&t.push({uid:a.externalId,volume:r.real})}S.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(S.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return c(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===N.CONNECTED?i=$.CONNECTED:t===N.CONNECTING||t===N.OPENED?i=$.CONNECTING:t===N.RECONNECTING&&(i=$.RECONNECT),!i)return;let r=e.reduce((a,s)=>{if(s in this._participants){let p=this._participants[s];a.push(p),t===N.CONNECTED&&(p.remoteStream||(p.mediaSettings&&this._changeRemoteMediaSettings(s,p.mediaSettings),this._changeRemoteParticipantState(s,p.participantState)),this._updateDisplayLayoutFromCache(s))}else o.warn(`Participant [${s}] isn't in conversation`);return a},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return c(this,null,function*(){o.debug(`Local transport state has changed: ${e}`),e===N.CONNECTED&&S.onLocalStatus($.CONNECTED),e===N.CONNECTING&&S.onLocalStatus($.CONNECTING),e===N.RECONNECTING&&S.onLocalStatus($.RECONNECT),e===N.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(P.FAILED)),this._close(new k(P.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return c(this,null,function*(){if(e.endsWith(we.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i),S.onRemoteMixedAudioStream(t);else if(e.startsWith(we.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))o.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{o.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(o.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],$.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(S.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===de.audio&&(this._audioOutput.add(i),d.preserveAudioTracks||t.removeTrack(i)),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;S.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),d.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(o.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case de.audio:this._removeAudioTrack(e,t,i);break;case de.video:case de.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==we.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e===me.DIRECT&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let a=this._participants[r];e||this._lastStalled[r]?t.push(a):i.push(a)}t.length&&this._setParticipantsStatus(t,$.RECONNECT),i.length&&this._setParticipantsStatus(i,$.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(a=>{if(t[a]=!0,!this._lastStalled[a]){let s=this._participants[a];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[a]}),Object.keys(this._lastStalled).forEach(a=>{let s=this._participants[a];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,$.RECONNECT),r.length&&this._setParticipantsStatus(r,$.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!y.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),S.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return c(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==me.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((a,s)=>(s.status!==t&&(s.status=t,d.batchParticipantsOnStart?a.push(s.externalId):S.onParticipantStatus(s.externalId,t,i)),a),[]);!r.length||d.batchParticipantsOnStart&&S.onRemoteStatus(r,t,i)}},w=U;w._delayedHangup=!1;var Zt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Zt.prototype),this.participantErrors=t}};var ei;function Xa(){return c(this,null,function*(){var n;if(d.apiEnv!=="AUTO")return d.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(n=i==null?void 0:i.Answer[0])==null?void 0:n.data;if(!r)throw new Error("Wrong DNS response");return o.debug("Resolved API endpoint",r),r}catch(e){return o.warn("Failed to resolve API endpoint using DNS, default is used",e),d.apiEndpoint}})}function zr(){if(!d.apiKey)throw new k(re.API,{message:"Required argument apiAppKey not passed"})}function Ui(n,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Xr(n,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${ei}/fb.do`,r)}function Qr(i){return c(this,arguments,function*(n,e={},t=!1){ei||(ei=yield Xa());let r=Xr(n,e,t);return Za(r)})}function Za(n){return c(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${ei}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(a){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(n)})})}function Xr(n,e={},t=!1){e.method=n,e.format="JSON",e.application_key||(e.application_key=d.apiKey),t||(Z.sessionKey?e.session_key=Z.sessionKey:Z.accessToken&&(e.access_token=Z.accessToken));for(let[r,a]of Object.entries(e))typeof a=="object"&&(e[r]=JSON.stringify(a));let i="";for(let[r,a]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(a)}`;return i}var tn=10,rn=700,an=3e3,ti=class extends ft{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return c(this,arguments,function*(e,t={},i=!1){let a=s=>c(this,null,function*(){try{return yield Qr(e,t,i)}catch(p){if(!p.hasOwnProperty("error_msg")&&(s++,o.debug(`${e} network error, attempt ${s}...`),s<tn))return yield I.delay(Math.min(s*rn,an)),a(s);throw o.warn(e,"error",p),p}});return a(0)})}_call(r){return c(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(a){o.warn("Api call error",a);let s=re.API;switch(a.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=P.SERVICE_DISABLED;break;case 1102:s=P.CALLEE_IS_OFFLINE;break;case 1103:s=P.NOT_FRIENDS;break;case 1104:case 1106:s=P.EXTERNAL_API_ERROR;break}throw new k(s,{message:a.error_msg,code:a.error_code})}})}userId(e){return c(this,null,function*(){let t=I.decomposeId(e).id;return Z.isEmpty()?fe.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),fe.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return c(this,null,function*(){Z.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return c(this,null,function*(){if(!this._uuid){let t=$e.get("uuid");t||(t=I.uuid(),$e.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:d.appVersion,client_type:"SDK_JS"}};return d.authToken&&(e.session_data.auth_token=d.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),Z.sessionKey=t.session_key,Z.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&S.onTokenExpired(),new k(re.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${d.appName}:${d.sdkVersion}`,platform:d.platform,items:e})};Ui("log.externalLog",t)}init(){zr()}joinConversation(e,t=!1,i){return c(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:d.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return c(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1,protocolVersion:d.protocolVersion};return t&&(r.payload=t),d.domain&&(r.domainId=d.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,a="",s=!1,p=!1){return c(this,null,function*(){let l={conversationId:e,isVideo:r,protocolVersion:d.protocolVersion};if(t&&t.length)switch(i){case He.USER:l.uids=t.join(",");break;case He.GROUP:l.gid=t[0];break;case He.CHAT:l.chatId=t[0];break}return s&&(l.createJoinLink=!0),a&&(l.payload=a),d.domain&&(l.domainId=d.domain),p&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return c(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return c(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return c(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return c(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i){return c(this,null,function*(){let r={joinLink:e,isVideo:t,protocolVersion:d.protocolVersion};return(i==null?void 0:i.length)&&(r.observedIds=i.join(",")),d.anonymToken&&(r.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",r)})}getOkIdsByExternalIds(e){return c(this,null,function*(){let t=fe.fromIds(e),i=[],r={methods:[]},a=[],s=Object.keys(this._externalUidsCache),p=Object.values(this._externalUidsCache);for(let m of t){let C=fe.toString(m),R=p.indexOf(C);R>-1?i.push(Number(s[R])):(a.push(C),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:m.id,anonym:m.type===ht.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((m,C)=>{if(m.ok){let R=Number(m.ok.ok_id);this._externalUidsCache[R]=a[C],i.push(R)}}),i})}getExternalIdsByOkIds(e){return c(this,null,function*(){let t=[],i=[];for(let a of e)this._externalUidsCache.hasOwnProperty(a)?t.push(fe.fromString(this._externalUidsCache[a])):i.push(a);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let a of i)r.hasOwnProperty(a)&&t.push(fe.fromString(r[a]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=fe.toString(e),a=i.indexOf(r);return a>-1?I.composeUserId(t[a],X.USER):null}cacheExternalId(e,t){let i=I.decomposeId(e).id;this._externalUidsCache[i]=fe.toString(t)}getConversationParams(e){return c(this,null,function*(){let t={};return d.anonymToken&&(t.anonymToken=d.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:P.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),Ui("vchat.hangupConversation",t)}removeHistoryRecords(e){return c(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return c(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,a]of Object.entries(i.external_ids))t[r]=fe.fromIdToString(a,ht.USER);if(i.anonym_ids)for(let[r,a]of Object.entries(i.anonym_ids))t[r]=fe.fromIdToString(a,ht.ANONYM);return t}catch(i){return t}})}};var Zr=(f=>(f.RECOVER="recover",f.ACCEPT_CALL="accept-call",f.ADD_PARTICIPANT="add-participant",f.REMOVE_PARTICIPANT="remove-participant",f.HANGUP="hangup",f.TRANSMIT_DATA="transmit-data",f.ACCEPT_PRODUCER="accept-producer",f.ALLOCATE_CONSUMER="allocate-consumer",f.CHANGE_MEDIA_SETTINGS="change-media-settings",f.CHANGE_PARTICIPANT_STATE="change-participant-state",f.CHANGE_STREAM_PRIORITIES="change-streams-priorities",f.UPDATE_DISPLAY_LAYOUT="update-display-layout",f.REPORT_PERF_STAT="report-perf-stat",f.RECORD_START="record-start",f.RECORD_STOP="record-stop",f.RECORD_SET_ROLE="record-set-role",f.RECORD_GET_STATUS="record-get-status",f.SWITCH_MICRO="switch-micro",f.SWITCH_TOPOLOGY="switch-topology",f.REQUEST_REALLOC="request-realloc",f.CHAT_MESSAGE="chat-message",f.CHAT_HISTORY="chat-history",f.CUSTOM_DATA="custom-data",f.GRANT_ROLES="grant-roles",f.MUTE_PARTICIPANT="mute-participant",f.PIN_PARTICIPANT="pin-participant",f.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",f.CHANGE_OPTIONS="change-options",f.GET_WAITING_HALL="get-waiting-hall",f.PROMOTE_PARTICIPANT="promote-participant",f.REQUEST_TEST_MODE="request-test-mode",f.ADD_MOVIE="add-movie",f.UPDATE_MOVIE="update-movie",f.REMOVE_MOVIE="remove-movie",f))(Zr||{}),F=Zr;var ea="open",ta=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0,()=>d.movieShare],nn=10,Oe=class extends vt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+d.platform+"&appVersion="+d.appVersion+"&version="+d.protocolVersion+"&device="+d.device+"&capabilities="+Oe._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null}static _getCapabilityFlags(){let e=0;for(let t=0;t<ta.length;t++)ta[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return c(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){u.log(_.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return c(this,arguments,function*(e,t={},i=0){if(t.participantId){let a=I.decomposeParticipantId(t.participantId),s=I.decomposeId(a.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),a.deviceIdx&&(t.deviceIdx=a.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return c(this,arguments,function*(e,t={},i=0){let a=s=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===ea&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){u.log(_.SOCKET_ACTION,"not_opened"),o.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(u.log(_.SOCKET_ACTION,"invalid_state"),o.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,p)=>{let l=(C,R=!1)=>{!i||R?p(C):(o.debug("Resending a signaling message",e,m.sequence),i--,a(m))},m={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};a(m)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===F.UPDATE_DISPLAY_LAYOUT||e===F.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===F.UPDATE_DISPLAY_LAYOUT||e===F.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return c(this,null,function*(){return this._send(F.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return c(this,null,function*(){return this._send(F.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return c(this,null,function*(){return this._send(F.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return c(this,null,function*(){return this._send(F.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return c(this,null,function*(){return this._send(F.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return c(this,null,function*(){return this._send(F.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},nn)})}changeParticipantState(e){return c(this,null,function*(){return this._send(F.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return c(this,null,function*(){return this._send(F.ADD_PARTICIPANT,Ki({participantId:e},t))})}removeParticipant(e,t=!1){return c(this,null,function*(){return this._send(F.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return c(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(F.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return c(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(F.ACCEPT_PRODUCER,i)})}changePriorities(e){return c(this,null,function*(){return this._send(F.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return c(this,null,function*(){return this._send(F.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return c(this,null,function*(){return this._send(F.ADD_MOVIE,e)})}updateMovie(e){return c(this,null,function*(){return this._send(F.UPDATE_MOVIE,e)})}removeMovie(e){return c(this,null,function*(){return this._send(F.REMOVE_MOVIE,e)})}startStream(e){return c(this,null,function*(){return this._send(F.RECORD_START,e)})}stopStream(){return c(this,null,function*(){return this._send(F.RECORD_STOP)})}recordSetRole(e,t){return c(this,null,function*(){return this._send(F.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return c(this,null,function*(){return this._send(F.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return c(this,null,function*(){return this._send(F.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return c(this,null,function*(){return this._send(F.REQUEST_REALLOC)})}reportPerfStat(e){return c(this,null,function*(){return this._send(F.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return c(this,null,function*(){return this._send(F.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return c(this,null,function*(){return this._send(F.CHAT_HISTORY,{count:e})})}customData(e,t){return c(this,null,function*(){return this._send(F.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return c(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(F.GRANT_ROLES,r)})}muteParticipant(e,t,i){return c(this,null,function*(){return this._sendRaw(F.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return c(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(F.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return c(this,null,function*(){return this._send(F.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return c(this,null,function*(){return this._send(F.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return c(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(F.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return c(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(F.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ge.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),o.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){o.debug("Socket opened"),u.log(_.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){u.log(_.SOCKET_ACTION,"parse_error"),o.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(o.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(ve.RECONNECT,e),e.conversation.topology&&this._triggerEvent(ve.NOTIFICATION,{type:"notification",notification:O.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(ve.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(u.log(_.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(u.log(_.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new k(P.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(ve.NOTIFICATION,{notification:O.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new k(re.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(u.log(_.SOCKET_ACTION,"unknown_message"),o.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(ve.FAILED,e)}_onError(e){u.log(_.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){u.log(_.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Oe.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(Oe.RECONNECT_MAX_DELAY,Oe.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),u.log(_.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ge.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],u.log(_.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Oe.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),a=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==ea){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}Oe._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,a),Oe.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(a))}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,a),Oe.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(a))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new k(re.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Oe.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{o.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Ge.RETRY)},Oe.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Be=Oe;Be.RECONNECT_DELAY=d.signalingReconnectDelay,Be.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,Be.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,Be.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,Be.WAIT_RESPONSE_DELAY=d.waitResponseDelay,Be.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var ia=(t=>(t.KING="KING",t.PAWN="PAWN",t))(ia||{}),sn=ia;var _t,oe,wt=null,$u={getCameras:y.getCameras,getMicrophones:y.getMicrophones,getOutput:y.getOutput,hasCamera:y.hasCamera,hasMicrophone:y.hasMicrophone,getSavedCamera:y.getSavedCamera,getSavedMicrophone:y.getSavedMicrophone,getSavedOutput:y.getSavedOutput,hasCameraPermission:y.hasCameraPermission,hasMicrophonePermission:y.hasMicrophonePermission,hasPermissions:y.hasPermissions,getUserMedia:y.getUserMedia,getUserVideo:y.getUserVideo,getUserAudio:y.getUserAudio,saveDeviceId:y.saveDeviceId,isBrowserSupported:y.isBrowserSupported,isScreenCapturingSupported:y.isScreenCapturingSupported,os:y.os,isMobile:y.isMobile,browserName:y.browserName,browserVersion:y.browserVersion,baseChromeVersion:y.baseChromeVersion,getAudioContext:y.getAudioContext};function on(n){oe=n}function cn(n){_t=n}function qu(n){wt=n}function Ju(n){d.videoEffects=n}function Yu(n){return c(this,null,function*(){if(d.set(n),y.browserName()==="Sferum"&&(d.platform=`SFERUM:${y.browserVersion()}`),oe||on(new ti),_t||cn(()=>new Be),d.debug&&(ra.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${d.sdkVersion}`,n),yield y.init(),!y.isBrowserSupported())throw new k(re.UNSUPPORTED);oe.init()})}function zu(a){return c(this,arguments,function*(n,e=[ue.AUDIO],t="",i=!1,r=!1){let s=[],p=[];if(Array.isArray(n)?s=n.length?n:[]:n&&(s=[n]),s.length&&(p=yield oe.getOkIdsByExternalIds(s),!p.length))throw new k(P.CALLEE_IS_OFFLINE);return dn(p,He.USER,e,t,i,r)})}function dn(s){return c(this,arguments,function*(n,e=He.USER,t,i="",r=!1,a=!1){if(w.current())throw o.error("There is already active call"),new k(P.FAILED);return new w(oe,_t(),wt).onStart(n,e,t,i,r,a)})}function Qu(n){return c(this,null,function*(){return pn(n)})}function pn(i){return c(this,arguments,function*(n,e=X.USER,t){if(n===w.id())throw new Error("Push has already been processed");return new w(oe,_t(),wt).onPush(n,e,t)})}function Xu(n){return c(this,null,function*(){return n&&(d.authToken=n),oe.authorize()})}function Zu(){return c(this,arguments,function*(n=[ue.AUDIO]){let e=w.current();if(e)return e.accept(n);throw new Error("Conversation not found")})}function em(){return c(this,null,function*(){let n=w.current();if(n)return n.decline()})}function tm(t){return c(this,arguments,function*(n,e=[ue.AUDIO]){return ln(n,e)})}function ln(n,e,t){return c(this,null,function*(){if(w.current())throw o.error("There is already active call"),new k(P.FAILED);return new w(oe,_t(),wt).onJoin({conversationId:n,mediaOptions:e,chatId:t})})}function im(r){return c(this,arguments,function*(n,e=[ue.AUDIO],t,i){if(w.current())throw o.error("There is already active call"),new k(P.FAILED);return t&&(d.anonymToken=t),new w(oe,_t(),wt).onJoin({joinLink:n,mediaOptions:e,observedIds:i})})}function rm(){return c(this,null,function*(){let n=w.current();if(n)return n.hangup();w.hangupAfterInit()})}function am(n,e){return c(this,null,function*(){let t=yield oe.getOkIdsByExternalIds([n]);if(!t.length)throw new Error("User not found");return un(t[0],e)})}function un(n,e){return c(this,null,function*(){let t=w.current();t&&(yield t.addParticipant(I.composeUserId(n,X.USER),e))})}function nm(n,e=!1){return c(this,null,function*(){let t=yield oe.getOkIdsByExternalIds([n]);return mn(t[0],e)})}function mn(n,e=!1){return c(this,null,function*(){let t=w.current();t&&(yield t.removeParticipant(I.composeUserId(n,X.USER),e))})}function sm(n,e){return c(this,null,function*(){let t=yield y.saveDeviceId(n,e),i=w.current();return t&&i?i.changeDevice(n):Promise.reject()})}function om(n){return c(this,null,function*(){let e=w.current();return e?e.toggleScreenCapturing(n):Promise.reject()})}function cm(n,e=!1){return c(this,null,function*(){let t=w.current();t&&(yield t.setVideoStream(n,e))})}function dm(n){return c(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalVideo(n))})}function pm(n){return c(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalAudio(n))})}function lm(n,e,t){return c(this,null,function*(){let i=w.current();if(i)return i.setLocalResolution(n,e,t)})}function um(n){return c(this,null,function*(){let e=w.current();e&&(yield e.changePriorities(n))})}function mm(n){return c(this,null,function*(){let e=w.current();e&&(yield e.changeParticipantState(n))})}function hm(n){return c(this,null,function*(){let e=w.current();e&&(yield e.updateDisplayLayout(n))})}function _m(n,e,t=!1){return c(this,null,function*(){let i=yield oe.getOkIdsByExternalIds([n]);return hn(i[0],e,t)})}function hn(n,e,t=!1){return c(this,null,function*(){let i=w.current();i&&(yield i.grantRoles(I.composeUserId(n,X.USER),e,t))})}function gm(){return c(this,arguments,function*(n=null,e,t=[]){let i=null;return n&&(i=(yield oe.getOkIdsByExternalIds([n]))[0]),_n(i,e,t,Se.getDeviceIdx(n))})}function _n(){return c(this,arguments,function*(n=null,e,t=[],i=0){let r=w.current();if(r){let a=n?I.composeParticipantId(n,X.USER,i):null;yield r.muteParticipant(a,e,t)}})}function fm(n,e=!1){return c(this,null,function*(){let t=yield oe.getOkIdsByExternalIds([n]);return gn(t[0],e,Se.getDeviceIdx(n))})}function gn(n,e=!1,t=0){return c(this,null,function*(){let i=w.current();i&&(yield i.pinParticipant(I.composeParticipantId(n,X.USER,t),e))})}function Sm(n){return c(this,null,function*(){let e=w.current();e&&(yield e.updateMediaModifiers(n))})}function vm(n){return c(this,null,function*(){let e=w.current();e&&(yield e.changeOptions(n))})}function Em(n,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield oe.getOkIdsByExternalIds([e]))[0]),fn(n,t)})}function fn(n,e=null){return c(this,null,function*(){let t=w.current();if(t){let i=e?I.composeUserId(e,X.USER):null;yield t.chatMessage(n,i)}})}function Tm(n=10){return c(this,null,function*(){let e=w.current();if(e)return e.chatHistory(n)})}function Im(n,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield oe.getOkIdsByExternalIds([e]))[0]),Sn(n,t,Se.getDeviceIdx(e))})}function Sn(n,e=null,t=0){return c(this,null,function*(){let i=w.current();if(i){let r=e?I.composeParticipantId(e,X.USER,t):null;yield i.customData(n,r)}})}function Cm(n="",e=!1){return c(this,null,function*(){return(yield oe.createConversation(I.uuid(),n,e)).join_link})}function ym(){return c(this,null,function*(){let n=w.current();return n?n.createJoinLink():Promise.reject()})}function Rm(){return c(this,null,function*(){let n=w.current();return n?n.removeJoinLink():Promise.reject()})}function bm(n,e){return c(this,null,function*(){return oe.getAnonymTokenByLink(n,e)})}function Pm(n){let e=w.current();e&&e.setVolume(n)}function Mm(n){d.forceRelayPolicy=n}function Dm(n=!1,e=null,t=null,i="DIRECT_LINK",r=null){return c(this,null,function*(){let a=w.current();return a?a.startStream(n,e,t,i,r):Promise.reject()})}function Am(){return c(this,null,function*(){let n=w.current();return n?n.stopStream():Promise.reject()})}function Om(n,e){return c(this,null,function*(){let t=w.current();if(t){let i=yield oe.getOkIdsByExternalIds([n]),r=Se.getDeviceIdx(n);return t.recordSetRole(I.composeParticipantId(i[0],X.USER,r),e)}return Promise.reject()})}function km(){return c(this,null,function*(){let n=w.current();return n?n.getStreamInfo():Promise.reject()})}function wm(n){return c(this,null,function*(){let e=w.current();return e?e.addMovie(n):Promise.reject()})}function xm(n,e,t,i){return c(this,null,function*(){let r=w.current();return r?r.updateMovie(n,e,t,i):Promise.reject()})}function Nm(n){return c(this,null,function*(){let e=w.current();return e?e.removeMovie(n):Promise.reject()})}function Lm(n){d.statisticsInterval=n;let e=w.current();if(e)return e.updateStatisticsInterval()}function Um(n){ra.disableLog(!n),o.toggle(n)}function Bm(n,...e){!d.debugLog||o.send(n,"[external]",...e)}function Vm(n){return c(this,null,function*(){let e=w.current();if(e)return e.videoEffect(n)})}function Fm(n){return c(this,null,function*(){let e=w.current();e&&(yield e.setAudioStream(n))})}function Hm(n=null,e,t=!1){return c(this,null,function*(){let i=w.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(n,e,t)})}function Gm(n,e=!1){return c(this,null,function*(){let t=w.current();if(!t)throw new Error("Conversation not found");let i=yield oe.getOkIdsByExternalIds([n]);return t.promoteParticipant(I.composeUserId(i[0],X.USER),e)})}function Wm(n){return c(this,null,function*(){yield oe.removeHistoryRecords(n)})}export{ti as Api,ft as BaseApi,St as BaseLogger,vt as BaseSignaling,je as CallDirection,He as CallType,ai as ChatRoomEventType,ni as ConversationOption,Gr as DebugMessageType,ht as ExternalIdType,Dr as FacingMode,re as FatalError,k as HangupReason,P as HangupType,ue as MediaOption,de as MediaTrackKind,De as MediaType,Ke as MuteState,G as ParticipantState,$ as ParticipantStatus,sn as RecordRole,Be as Signaling,F as SignalingCommandType,Ge as SignalingConnectionType,O as SignalingNotification,rt as UserRole,X as UserType,I as Utils,Zu as acceptCall,wm as addMovie,am as addParticipant,un as addParticipantInternal,Xu as authorize,$u as browser,dn as callInternal,zu as callTo,om as captureScreen,vm as changeConversationOptions,sm as changeDevice,mm as changeParticipantState,um as changePriorities,Vm as changeVideoEffect,Tm as chatHistory,Em as chatMessage,fn as chatMessageInternal,ym as createJoinLink,Im as customData,Sn as customDataInternal,Um as debug,Bm as debugMessage,em as declineCall,Mm as forceRelayPolicy,bm as getAnonymTokenByLink,km as getStreamInfo,Hm as getWaitingHall,_m as grantRoles,hn as grantRolesInternal,rm as hangup,Yu as init,tm as joinCall,im as joinCallByLink,ln as joinCallInternal,gm as muteParticipant,_n as muteParticipantInternal,fm as pinParticipant,gn as pinParticipantInternal,Qu as processPush,pn as processPushInternal,Gm as promoteParticipant,Om as recordSetRole,Wm as removeHistoryRecords,Rm as removeJoinLink,Nm as removeMovie,nm as removeParticipant,mn as removeParticipantInternal,on as setApi,Fm as setAudioStream,lm as setLocalResolution,qu as setLogger,Sm as setMediaModifiers,cn as setSignalingFactory,Lm as setStatisticsInterval,Ju as setVideoEffects,cm as setVideoStream,Pm as setVolume,Cm as startConversation,Dm as startStream,Am as stopStream,pm as toggleLocalAudio,dm as toggleLocalVideo,hm as updateDisplayLayout,xm as updateMovie};