@vkontakte/calls-sdk 2.4.4-dev.00c279b.0 → 2.4.4-dev.c28b095.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.cjs.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
- * @vkontakte/calls-sdk v2.4.4-dev.00c279b.0
3
- * Mon, 29 Nov 2021 17:02:57 GMT
2
+ * @vkontakte/calls-sdk v2.4.4-dev.c28b095.0
3
+ * Tue, 07 Dec 2021 13:06:30 GMT
4
4
  * https://st.mycdn.me/static/callssdk/2-4-4/doc/
5
5
  */
6
6
 
7
- var pa=Object.create;var _t=Object.defineProperty;var ua=Object.getOwnPropertyDescriptor;var ma=Object.getOwnPropertyNames,ar=Object.getOwnPropertySymbols,ha=Object.getPrototypeOf,nr=Object.prototype.hasOwnProperty,_a=Object.prototype.propertyIsEnumerable;var sr=(a,e,t)=>e in a?_t(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,or=(a,e)=>{for(var t in e||(e={}))nr.call(e,t)&&sr(a,t,e[t]);if(ar)for(var t of ar(e))_a.call(e,t)&&sr(a,t,e[t]);return a};var cr=a=>_t(a,"__esModule",{value:!0});var ss=typeof require!="undefined"?require:a=>{throw new Error('Dynamic require of "'+a+'" is not supported')};var ga=(a,e)=>{cr(a);for(var t in e)_t(a,t,{get:e[t],enumerable:!0})},fa=(a,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ma(e))!nr.call(a,i)&&i!=="default"&&_t(a,i,{get:()=>e[i],enumerable:!(t=ua(e,i))||t.enumerable});return a},gt=a=>fa(cr(_t(a!=null?pa(ha(a)):{},"default",a&&a.__esModule&&"default"in a?{get:()=>a.default,enumerable:!0}:{value:a,enumerable:!0})),a);var s=(a,e,t)=>new Promise((i,r)=>{var n=p=>{try{l(t.next(p))}catch(f){r(f)}},c=p=>{try{l(t.throw(p))}catch(f){r(f)}},l=p=>p.done?i(p.value):Promise.resolve(p.value).then(n,c);l((t=t.apply(a,e)).next())});ga(exports,{Api:()=>Dt,BaseApi:()=>Ze,BaseLogger:()=>et,BaseSignaling:()=>tt,CallDirection:()=>Be,CallType:()=>we,ChatRoomEventType:()=>kt,ConversationOption:()=>wt,DebugMessageType:()=>pe,ExternalIdType:()=>Re,FacingMode:()=>Ft,FatalError:()=>re,HangupReason:()=>N,HangupType:()=>b,MediaOption:()=>le,MediaTrackKind:()=>K,MediaType:()=>Ie,MuteState:()=>Fe,ParticipantState:()=>H,ParticipantStatus:()=>q,RecordRole:()=>zr,Signaling:()=>De,SignalingCommandType:()=>G,SignalingConnectionType:()=>Ne,SignalingNotification:()=>w,UserRole:()=>je,UserType:()=>z,Utils:()=>I,acceptCall:()=>_n,addMovie:()=>Yn,addParticipant:()=>En,addParticipantInternal:()=>ra,apiCall:()=>mn,authorize:()=>hn,browser:()=>sn,callInternal:()=>ea,callTo:()=>ln,captureScreen:()=>Tn,changeConversationOptions:()=>xn,changeDevice:()=>Cn,changeParticipantState:()=>On,changePriorities:()=>An,changeVideoEffect:()=>ts,chatHistory:()=>Un,chatMessage:()=>Ln,chatMessageInternal:()=>ca,createJoinLink:()=>Fn,customData:()=>Vn,customDataInternal:()=>da,debug:()=>Zn,debugMessage:()=>es,declineCall:()=>gn,forceRelayPolicy:()=>jn,getAnonymTokenByLink:()=>Hn,getStreamInfo:()=>Jn,getTokenForAnonym:()=>un,getWaitingHall:()=>rs,grantRoles:()=>Mn,grantRolesInternal:()=>na,hangup:()=>vn,init:()=>dn,joinCall:()=>fn,joinCallByLink:()=>Sn,joinCallInternal:()=>ia,muteParticipant:()=>kn,muteParticipantInternal:()=>sa,pinParticipant:()=>wn,pinParticipantInternal:()=>oa,processPush:()=>pn,processPushInternal:()=>ta,promoteParticipant:()=>as,recordSetRole:()=>qn,removeHistoryRecords:()=>ns,removeJoinLink:()=>Gn,removeMovie:()=>zn,removeParticipant:()=>In,removeParticipantInternal:()=>aa,setApi:()=>Xr,setAudioStream:()=>is,setLocalResolution:()=>bn,setLogger:()=>on,setMediaModifiers:()=>Nn,setSignalingFactory:()=>Zr,setStatisticsInterval:()=>Xn,setVideoEffects:()=>cn,setVideoStream:()=>Rn,setVolume:()=>Wn,startConversation:()=>Bn,startStream:()=>Kn,stopStream:()=>$n,toggleLocalAudio:()=>Pn,toggleLocalVideo:()=>yn,updateDisplayLayout:()=>Dn,updateMovie:()=>Qn});var tr=gt(require("webrtc-adapter"));var Ze=class{createJoinLink(e){return s(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return s(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return s(this,null,function*(){return""})}log(e){}prepareUserIds(e){return s(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return s(this,null,function*(){})}cleanup(){}getTokenForAnonym(e,t){return s(this,null,function*(){return""})}call(i){return s(this,arguments,function*(e,t={}){return null})}};var et=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 tt=class extends Q{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var ti;(function(i){i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING"})(ti||(ti={}));var Be=ti;var ii;(function(i){i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT"})(ii||(ii={}));var we=ii;var ri;(function(t){t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP"})(ri||(ri={}));var kt=ri;var ai;(function(t){t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD"})(ai||(ai={}));var dr=ai;var ni;(function(i){i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL"})(ni||(ni={}));var wt=ni;function lr(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function pr(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 si;(function(R){R.CAMERA_PERMISSION="camera",R.MIC_PERMISSION="mic",R.CAMERA_ACCESS="cameralock",R.MIC_ACCESS="miclock",R.MIC_NOT_FOUND="nomic",R.SCREEN_PERMISSION="screenpermission",R.SCREEN_ACCESS="screenlock",R.CONNECTION="connection",R.NETWORK="network",R.UNKNOWN="unknown",R.UNSUPPORTED="unsupported",R.SIGNALING_FAILED="signalingfailed",R.API="api",R.AUTH="auth"})(si||(si={}));var re=si;var oi;(function(F){F.CANCELED="CANCELED",F.REJECTED="REJECTED",F.REMOVED="REMOVED",F.HUNGUP="HUNGUP",F.MISSED="MISSED",F.BUSY="BUSY",F.FAILED="FAILED",F.NETWORK_ERROR="NETWORK_ERROR",F.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",F.NOT_FRIENDS="NOT_FRIENDS",F.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",F.UNKNOWN_ERROR="UNKNOWN_ERROR",F.UNSUPPORTED="UNSUPPORTED",F.OLD_VERSION="OLD_VERSION",F.SERVICE_DISABLED="SERVICE_DISABLED",F.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",F.SOCKET_CLOSED="SOCKET_CLOSED",F.ENDED="ENDED"})(oi||(oi={}));var b=oi;var ci;(function(i){i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING"})(ci||(ci={}));var le=ci;var di;(function(i){i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT"})(di||(di={}));var Fe=di;var li;(function(r){r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP"})(li||(li={}));var H=li;var pi;(function(r){r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry"})(pi||(pi={}));var Ne=pi;var ui;(function(i){i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT"})(ui||(ui={}));var Se=ui;var mi;(function(m){m.TRANSMITTED_DATA="transmitted-data",m.ACCEPTED_CALL="accepted-call",m.HUNGUP="hungup",m.PARTICIPANT_ADDED="participant-added",m.PARTICIPANT_JOINED="participant-joined",m.CLOSED_CONVERSATION="closed-conversation",m.MEDIA_SETTINGS_CHANGED="media-settings-changed",m.PARTICIPANT_STATE_CHANGED="participant-state-changed",m.RATE_CALL_DATA="rate-call-data",m.FEATURE_SET_CHANGED="feature-set-changed",m.TOPOLOGY_CHANGED="topology-changed",m.PRODUCER_UPDATED="producer-updated",m.CONSUMER_ANSWERED="consumer-answered",m.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",m.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",m.SETTINGS_UPDATE="settings-update",m.VIDEO_QUALITY_UPDATE="video-quality-update",m.REGISTERED_PEER="registered-peer",m.SWITCH_MICRO="switch-micro",m.RECORD_STARTED="record-started",m.RECORD_STOPPED="record-stopped",m.REALLOC_CON="realloc-con",m.AUDIO_ACTIVITY="audio-activity",m.SPEAKER_CHANGED="speaker-changed",m.STALLED_ACTIVITY="stalled-activity",m.CHAT_MESSAGE="chat-message",m.CUSTOM_DATA="custom-data",m.ROLES_CHANGED="roles-changed",m.MUTE_PARTICIPANT="mute-participant",m.PIN_PARTICIPANT="pin-participant",m.OPTIONS_CHANGED="options-changed",m.NETWORK_STATUS="network-status",m.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",m.PROMOTE_PARTICIPANT="promote-participant",m.CHAT_ROOM_UPDATED="chat-room-updated",m.PROMOTION_APPROVED="promotion-approved",m.JOIN_LINK_CHANGED="join-link-changed"})(mi||(mi={}));var w=mi;var hi;(function(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"})(hi||(hi={}));var g=hi;var _i;(function(t){t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat"})(_i||(_i={}));var Oe=_i;var ft;(function(t){t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error"})(ft||(ft={}));var ur=ft;function mr(a){switch(a){case 1:return ft.NO_AVAILABLE_TRACKS;default:return ft.UNKNOWN_ERROR}}var gi;(function(t){t.CREATOR="CREATOR",t.ADMIN="ADMIN"})(gi||(gi={}));var je=gi;function St(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var fi;(function(t){t.USER="USER",t.GROUP="GROUP"})(fi||(fi={}));var z=fi;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 hr=2*1024*1024,Sa=512*1024,vt=100*1024,va=5,vi="_okcls_logs_session_",Ea=3e4,_r=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=hr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(vi)!==0)continue;let i=e.getItem(t);if(!i){Sr(t);continue}let r=fr(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(vt)}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(vi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Sr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>hr||this.length>va-1||this.size+e>this.available);)this.deleteOldestItem()}};function gr(){return`${vi}${Date.now()}`}function fr(a){return new Blob([a]).size}function Sr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function Ei(){let a=Ke.toString();if(!Ee.available||!a)return;let e=fr(a);Ee.cleanup(e);try{window.localStorage.setItem(Nt,a)}catch(t){if(console.warn("Failed to write log to storage",t),Ee.storageSize=Ee.size+e,Ee.cleanup(vt+e),Ee.available>=vt+e){Ei();return}if(e>vt){Ke.bisect(),Ei();return}Ee.storageSize=0;return}e>Sa&&(Ee.add(Nt,e),Nt=gr(),Ke.clear(),Ee.cleanup(vt))}function Ii(){!Ee.available||!Ke.length||Ei()}function Ia(a=!1){let e=[];try{let r=window.localStorage;for(let c of Ee.items){let l=r.getItem(c.key);e.push(l)}let n=Ke.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 Ca(t,i),i}function Ca(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 vr(a,e){!Ee.available||(Ke.push({t:Date.now(),l:a,d:e}),Ti||(Ti=window.setTimeout(()=>{Ti=null,Ii()},Ea)))}function Ci(){Ee||(Ee=new _r,Ke=new Si,Nt=gr(),window.addEventListener("beforeunload",Ii))}var Ee,Ke,Nt,Ti=null;window.__VKCallsSDKLogs__=(a=!1)=>(Ee||Ci(),Ii(),Ia(a));var Ri="_okcls_",it=(()=>{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 Ta(a){let e=it?it.getItem(Ri+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function Ra(a,e){try{it&&it.setItem(Ri+a,JSON.stringify(e))}catch(t){}}function ya(a){it&&it.removeItem(Ri+a)}var yi;(function(i){function a(r){return Ta(r)||null}i.get=a;function e(r,n){Ra(r,n)}i.set=e;function t(r){ya(r)}i.remove=t})(yi||(yi={}));var He=yi;var rt=gt(require("big-integer"));function Er(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 ve(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}var Ir=a=>a.stop(),Cr=a=>a.getTracks().forEach(Ir),Pi=a=>a.getVideoTracks().forEach(Ir),Tr=a=>a.getVideoTracks()[0].clone();var N=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(b).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,N)}};var u=class extends et{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={type:1,time:0,operation:e,timestamp:Date.now(),custom:{},uid:this._api.getUserId()};typeof t!="undefined"&&(r.custom.param=t),this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch(),this._externalLogger&&this._externalLogger.log(e,t,i)}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 destroy(){u._instance&&u._instance.destroy(),u._instance=null}};var ne;(function(i){i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS"})(ne||(ne={}));var K;(function(i){i.audio="audio",i.video="video",i.screen="screen"})(K||(K={}));var bi=class extends Q{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=ve();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return s(this,arguments,function*(e=[le.AUDIO]){if(this._stream)return;let t=e.includes(le.VIDEO),i=e.includes(le.AUDIO);if(!y.isBrowserSupported())throw new N(re.UNSUPPORTED);try{this._stream=yield y.getUserMedia(t,i),this._mediaSettings.isVideoEnabled=t&&this._stream.getVideoTracks().filter(r=>r.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=i&&this._stream.getAudioTracks().filter(r=>r.enabled).length>0||!1}catch(r){throw new N(r)}})}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=!1){let i=this.getStream(),r=this._getSendAudioTrack(),n=this.getSendVideoTrack(t);if(!i||!r&&!n)throw new Error("No local stream found");r&&e.addTrack(r,i),n&&e.addTrack(n,i)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return s(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return s(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);navigator.mediaDevices.addEventListener("devicechange",()=>s(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),c=n&&n.groupId,l=this._stream.getVideoTracks()[0],p=l&&l.enabled&&l.getSettings(),f=p&&p.groupId;if(!c&&!f)return;let A=yield navigator.mediaDevices.enumerateDevices();!e&&c&&(e=!A.find(M=>M.groupId===c)),!t&&f&&(t=!A.find(M=>M.groupId===f)),i()}))}_changeVideoInput(e=null){return s(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),n=yield this._videoEffect(this._effect,r);this._stopLocalTrack(K.video),u.log(g.DEVICE_CHANGED,t),o.log("Video stream changed"),yield this._replaceLocalTrack(n),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent(ne.SOURCE_CHANGED,{kind:K.video,mediaSettings:this._mediaSettings})}}catch(t){throw u.log(g.ERROR,"change_video"),o.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=Tr(e)),t=this._trackVideoStreamBackup.clone(),Pi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),Pi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return s(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return s(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(K.audio),u.log(g.DEVICE_CHANGED,"audio"),o.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent(ne.SOURCE_CHANGED,{kind:K.audio,mediaSettings:this._mediaSettings})}}catch(t){throw u.log(g.ERROR,"change_audio"),o.error("Microphone change failed",t),t}})}_changeScreen(e){return s(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(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(K.video),this._sendVideoTrack=d.consumerScreenDataChannel?y.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent(ne.SCREEN_STATUS,{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent(ne.SOURCE_CHANGED,{kind:K.screen,mediaSettings:this._mediaSettings})}}catch(t){throw u.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(ne.SCREEN_STATUS,{mediaSettings:this._mediaSettings}),this._triggerEvent(ne.SOURCE_CHANGED,{kind:K.screen,mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return s(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(ne.TRACK_REPLACED,e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return s(this,null,function*(){if(!d.videoEffects)return t;try{return u.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(){d.videoEffects&&(this._effect=null,d.videoEffects.destroy()),this._stream&&(Cr(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return s(this,null,function*(){return e?this._changeScreen():d.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return s(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(K.video),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent(ne.SOURCE_CHANGED,{kind:K.video,mediaSettings:this._mediaSettings})})}toggleAudio(e){return s(this,null,function*(){if(!this._stream)return;let t;e?t=(yield y.getUserAudio()).getAudioTracks()[0]:t=y.getSilentMediaTrack(),this._stopLocalTrack(K.audio),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent(ne.SOURCE_CHANGED,{kind:K.audio,mediaSettings:this._mediaSettings})})}setResolution(e,t){return s(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 s(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 s(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 Ai;(function(rr){function a(C,P,O,h,D=!1){let Te=/[\r\n]+/,X=`\r
8
- `;if(!P&&!O&&!h)return D?L(C.split(Te)).join(X):C;function L(Y){let ke=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],_e="a=rtcp-fb:111",oe=Y.findIndex(ee=>ee.startsWith(_e));return~oe&&(Y[oe]=Y[oe]+X+ke.join(X)),Y}function Z(Y,ke,_e){let oe=Y.split(" "),ee=oe.slice(0,3),me;for(me=3;me<oe.length;me++)_e.includes(oe[me])&&ee.push(oe[me]);for(me=3;me<oe.length;me++)!_e.includes(oe[me])&&!ke.includes(oe[me])&&ee.push(oe[me]);return ee.join(" ")}function _(Y,ke){let _e=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),oe,ee=[];for(oe=0;oe<Y.length;++oe){let me=Y[oe].match(_e);me&&me.length===3&&me[2]===ke&&ee.push(me[1])}return ee}function $(Y,ke,_e,oe){let ee,me="m="+ke;for(ee=0;ee<Y.length;++ee)if(Y[ee].startsWith(me)){Y[ee]=Z(Y[ee],_e,oe);break}}let de=[],m=C.split(Te);(O||P)&&(de=_(m,"H264"));let Ve=[];if(h&&(Ve=_(m,"VP9")),O){let Y=de.slice(0),ke=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),_e;for(_e=0;_e<m.length;++_e){let ee=m[_e].match(ke);ee&&ee.length===3&&Y.includes(ee[2])&&Y.push(ee[1])}let oe=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(_e=m.length;_e--;){let ee=m[_e].match(oe);ee&&ee.length===3&&Y.includes(ee[2])&&m.splice(_e,1)}$(m,"video",Y,[])}else P&&$(m,"video",[],de);return h&&$(m,"video",[],Ve),D&&L(m),m.join(X)}rr.patchSDP=a;function e(C){return C?`${C.type||"WEB_SOCKET"}_${C.id}`:"_"}rr.getPeerIdString=e;function t(C,P){return C&&C.id===P.id&&(C.type||"WEB_SOCKET")===(P.type||"WEB_SOCKET")}rr.comparePeerId=t;function i(C){return s(this,null,function*(){return!C||!C.getStats?Promise.resolve(null):C.getStats(null).then(P=>{let O=null,h=null;if(P.forEach(D=>{D.type==="transport"&&D.selectedCandidatePairId?h=P.get(D.selectedCandidatePairId):D.type==="candidate-pair"&&D.state==="succeeded"&&!h&&(!D.hasOwnProperty("selected")||D.selected)&&(h=D)}),h&&h.localCandidateId){let D=P.get(h.localCandidateId);D&&(O={type:D.candidateType,ip:D.ip||D.ipAddress,port:D.port||D.portNumber})}return O}).catch(()=>null)})}rr.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function c(C,P){let O=String(C);return n.test(O)?(o.warn(`Already composite id [${C}] type supplied [${P}]`),O):P===z.GROUP?"g"+O:P===z.USER?"u"+O:(o.warn(`Unknown type [${P}] for id [${C}]`),O.match(r)?"u"+O:O)}rr.composeId=c;function l(C){return c(C.id,C.idType||z.USER)}rr.composeParticipantId=l;function p(C){return C.participant?l(C.participant):c(C.participantId,C.participantType||z.USER)}rr.composeMessageId=p;function f(C){let P=String(C),O=P.match(n);return O?{id:Number(O[2]),type:O[1]==="g"?z.GROUP:z.USER}:(o.warn(`Unsupported compositeId [${C}]`),{id:Number(P),type:z.USER})}rr.decomposeId=f;function A(){let C="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),P=new Array(36),O=0,h,D;for(D=0;D<36;D++)D===8||D===13||D===18||D===23?P[D]="-":D===14?P[D]="4":(O<=2&&(O=33554432+Math.random()*16777216|0),h=O&15,O=O>>4,P[D]=C[D===19?h&3|8:h]);return P.join("")}rr.uuid=A;function M(C,P){let O;function h(){let D=this,Te=arguments;O&&window.clearTimeout(O),O=window.setTimeout(()=>{C.apply(D,Te)},P)}return h}rr.throttle=M;function j(C){let P="",O=C.split(`
9
- `);for(let X of O)if(X.startsWith("a=fingerprint")){let L=X.split(" ");if(L.length===2){P=L[1];break}}if(!P)return rt.default.minusOne;let h=P.split(":"),D=rt.default.zero;for(let X=Math.min(7,h.length-1);X>=0;X--){let L=(0,rt.default)(h[X],16);D=D.shiftLeft(8).or(L)}return((X,L)=>{let Z=L.value;if(typeof Z=="bigint")return(0,rt.default)(BigInt.asIntN(X,Z));let _=rt.default.one.shiftLeft(X),$=L.and(_.subtract(1));return $.greaterOrEquals(_.subtract($))?$.subtract(_):$})(64,D)}rr.sdpFingerprint=j;function ae(C){return s(this,null,function*(){return new Promise(P=>window.setTimeout(P,C))})}rr.delay=ae;function R(C,P,O){let h=[];return C.getSenders().forEach(D=>ge(P,D,D.track,O,h)),h}rr.applySettings=R;function ge(C,P,O,h,D){if(C&&O&&O.kind===K.video){let Te=O.getSettings();if(Te){let X=C.maxBitrateK?C.maxBitrateK*1024:null,L=Te.width,Z=Te.height,_=L&&Z&&C.maxDimension?Math.max(1,Math.max(L,Z)/C.maxDimension):null,$=C.maxFramerate?C.maxFramerate:null,de=C.degradationPreference?C.degradationPreference:"balanced",m=h[O.id];if(m&&m.bitrate===X&&m.scaleResolutionDownBy===_&&m.maxFramerate===$&&m.degradationPreference===de){D[O.id]=m;return}D[O.id]={bitrate:X,scaleResolutionDownBy:_,maxFramerate:$,degradationPreference:de};let Ve=P.getParameters();Ve.encodings||(Ve.encodings=[{}]),Ve.encodings.forEach(Y=>{X?Y.maxBitrate=X:delete Y.maxBitrate,_?Y.scaleResolutionDownBy=_:delete Y.scaleResolutionDownBy,$?Y.maxFramerate=$:delete Y.maxFramerate}),Ve.degradationPreference=de,P.setParameters(Ve)}}}rr.applyVideoTrackSettings=ge;function Me(C,P){Array.isArray(P)||(P=[P]);for(let O of P)if(C.includes(O))return!0;return!1}rr.includesOneOf=Me;function he(C){var P;return Object.entries(((P=C.participantState)==null?void 0:P.state)||{}).reduce((O,[h,D])=>(C.participantState&&(O[h]={ts:C.participantState.stateUpdateTs[h],state:D}),O),{})}rr.mapParticipantState=he;function F(C){return Object.entries(C).reduce((P,[O,{state:h}])=>(P[O]=h,P),{})}rr.mapLegacyParticipantState=F;function ue(C){return C.map(P=>{let O={uid:P.externalId,mediaSettings:P.mediaSettings,status:P.status,muteStates:P.muteStates,unmuteOptions:P.unmuteOptions};return d.participantStateMapped&&(O.participantState=P.participantState),O})}rr.mapSharedParticipants=ue;function be(C,P){let O=Object.keys(C),h=Object.keys(P);if(O.length!==h.length)return!1;for(let D of O)if(!h.hasOwnProperty(D)||C[D].state!==P[D].state||C[D].ts!==P[D].ts)return!1;return!0}rr.isEqualParticipantState=be;function Ae(C,P){let O=Object.keys(C),h=Object.keys(P);if(O.length!==h.length)return!1;for(let D of O)if(!P.hasOwnProperty(D)||C[D]!==P[D])return!1;return!0}rr.isObjectsEquals=Ae;function mt(C,P){if(C.length!==P.length)return!1;for(let O of C)if(P.indexOf(O)<0)return!1;return!0}rr.isArraysEquals=mt;function ir(C){return!Object.keys(C).length}rr.isEmptyObject=ir})(Ai||(Ai={}));var I=Ai;var $e=null,Oi=null,xt=[],Lt=[],Di=[],Et=null,It=null,Mi=null,ki=!1,wi=!1,Ut,at,Vt,Rr=!1,yr=!1,Ni=null,xi="",Bt=[],Li=null,Pr=navigator.appVersion,Pa=navigator.appName,Ce=navigator.userAgent,Ft;(function(r){r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right"})(Ft||(Ft={}));var Ct=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 l;It&&(l=It.deviceId),typeof e=="string"&&(l=e),l&&(n.deviceId={exact:l})}let c=!1;if(t){c={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 l;Et&&(l=Et.deviceId),typeof t=="string"&&(l=t),l&&(c.deviceId={exact:l}),d.videoFacingMode&&(c.facingMode={exact:d.videoFacingMode})}this.audio=n,this.video=c,this.needVideo=!!c}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}},br=class extends Ct{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 ba(){return s(this,null,function*(){$e=null,yield Gt()})}function Aa(){$e=null,Gt().then(()=>v.onDeviceChange())}function Gt(){return s(this,null,function*(){return $e||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Oi&&navigator.mediaDevices.addEventListener&&(Oi=I.throttle(Aa,1e3),navigator.mediaDevices.addEventListener("devicechange",Oi)),$e=navigator.mediaDevices.enumerateDevices().then(a=>{xt=a.filter(r=>r.kind==="videoinput"?(r.label&&(ki=!0),!0):!1),Lt=a.filter(r=>r.kind==="audioinput"?(r.label?wi=!0:qe.isMobile()&&qe.browserName()==="Firefox"&&(wi=ki),!0):!1),Di=a.filter(r=>r.kind==="audiooutput");let e=He.get("videoinput"),t=He.get("audioinput"),i=He.get("audiooutput");return Et=xt.find(r=>r.deviceId===e)||null,It=Lt.find(r=>r.deviceId===t)||null,Mi=Di.find(r=>r.deviceId===i)||null,$e=Promise.resolve(a),a}).catch(()=>($e=null,[]))))})}function Oa(){return s(this,null,function*(){return qe.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(Rr=!0),/^a=mid:0$/m.test(t.sdp)&&(yr=!0),a()}).catch(a)}):Promise.resolve()})}function Ht(a,e){return s(this,null,function*(){o.debug("Try to get media",a.getNative());let t=qe.hasPermissions(a.isVideo());!t&&!e&&v.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield ba()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?re.CAMERA_PERMISSION:re.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?re.CAMERA_ACCESS:re.MIC_ACCESS;break}if(a.canSimplify())return Ht(a.simplify(),e);let r=e||re.UNKNOWN;throw v.onPermissionsError(r),r}})}function Da(a){return s(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 re.SCREEN_PERMISSION;default:throw re.SCREEN_ACCESS}}})}function Ui(){return Bt.length||(Bt=(()=>{let a,e=!1,t=0,i=Ce.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return a=/\brv[ :]+(\d+)/g.exec(Ce),["IE",a&&a[1]||"Unknown",e,t];if(i[1]==="Safari"){if(a=Ce.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(a=Ce.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,a[1]];if(a=Ce.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t];if(a=Ce.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t];if(a=Ce.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),a=Ce.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t];if(a=Ce.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t];if(a=Ce.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t];if(a=Ce.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t]}return a=Ce.match(/version\/(\d+)/i),[i[2]?i[1]:Pa,a&&a[1]||i[2]||Pr,e,t]})()),Bt}var qe;(function(X){function a(){return s(this,null,function*(){return yield Oa(),Gt()})}X.init=a;function e(){return xt}X.getCameras=e;function t(){return Lt}X.getMicrophones=t;function i(){return Di}X.getOutput=i;function r(){return xt.length>0}X.hasCamera=r;function n(){return Lt.length>0}X.hasMicrophone=n;function c(){return Et}X.getSavedCamera=c;function l(){return It}X.getSavedMicrophone=l;function p(){return Mi}X.getSavedOutput=p;function f(){return ki}X.hasCameraPermission=f;function A(){return wi}X.hasMicrophonePermission=A;function M(L=!1){return A()?r()&&L?f():!0:!1}X.hasPermissions=M;function j(L=!1,Z=!0){return s(this,null,function*(){let _=n()&&Z,$=r()&&L,de;if(!_&&!$)de=new MediaStream;else try{de=yield Ht(new Ct(_,$))}catch(m){de=new MediaStream}return de.getVideoTracks().length||de.addTrack(F()),de.getAudioTracks().length||de.addTrack(he()),de})}X.getUserMedia=j;function ae(){return s(this,null,function*(){return Da(new br(window.screen.width,window.screen.height))})}X.getScreenMedia=ae;function R(L,Z=!1){return s(this,null,function*(){let _=Z?d.videoEffectMaxWidth:d.videoMaxWidth,$=Z?d.videoEffectMaxHeight:d.videoMaxHeight;return Ht(new Ct(!1,L||!0,_,$))})}X.getUserVideo=R;function ge(L){return s(this,null,function*(){return Ht(new Ct(L||!0,!1))})}X.getUserAudio=ge;function Me(L,Z){return s(this,null,function*(){let $=(yield Gt()).find(de=>de.kind===L&&de.deviceId===Z);return $?(L==="videoinput"?Et=$:L==="audioinput"?It=$:L==="audiooutput"&&(Mi=$),He.set(L,Z),$):null})}X.saveDeviceId=Me;function he(){if(!Vt||Vt.readyState==="ended"){let L=Te(),Z=L.createMediaStreamDestination(),_=L.createGain();_.gain.value=1e-5,_.connect(Z),_.connect(L.destination);let $=L.createOscillator();$.type="sine",$.frequency.value=0,$.connect(_),$.start(),Vt=Z.stream.getAudioTracks()[0]}return Object.assign(Vt.clone(),{enabled:!1})}X.getSilentMediaTrack=he;function F(L=d.videoMinWidth,Z=d.videoMinHeight){return at||(at=document.createElement("canvas"),at.getContext("2d")),at.width=L,at.height=Z,(!Ut||Ut.readyState==="ended")&&(Ut=at.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(Ut.clone(),{enabled:!1})}X.getBlackMediaTrack=F;function ue(){if(O()==="Edge"&&h()<70)return!1;try{let L=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&L.RTCPeerConnection&&L.RTCIceCandidate&&L.RTCSessionDescription&&L.HTMLCanvasElement&&L.HTMLCanvasElement.prototype.captureStream&&L.RTCRtpSender&&L.RTCRtpSender.prototype.replaceTrack&&L.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(L){return!1}}X.isBrowserSupported=ue;function be(){return!!navigator.mediaDevices.getDisplayMedia}X.isScreenCapturingSupported=be;function Ae(){return Rr}X.canVP8=Ae;function mt(){return yr}X.isUnifiedPlan=mt;function ir(){return X.browserName()==="Opera"&&X.os()==="Windows"}X.isBrokenH264=ir;function rr(){return!(X.baseChromeVersion()&&X.isMobile())}X.canPreferH264=rr;function C(){return xi||(xi=(()=>{let L={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 Z in L)if(L.hasOwnProperty(Z)&&L[Z].test(Ce))return Z;return"Unknown"})()),xi}X.os=C;function P(){return Ni===null&&(Ni=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Pr)),Ni}X.isMobile=P;function O(){return Ui()[0]}X.browserName=O;function h(){return Ui()[1]}X.browserVersion=h;function D(){return Ui()[3]}X.baseChromeVersion=D;function Te(){return Li||(Li=new(window.AudioContext||window.webkitAudioContext)),Li}X.getAudioContext=Te})(qe||(qe={}));var y=qe;var Vi=gt(require("@vkontakte/libvpx"));var Ar;(function(t){t.VP9="vp09.00.50.08",t.VP8="vp8"})(Ar||(Ar={}));var fe;(function(c){c.INIT="init",c.READY="ready",c.FRAME="frame",c.ERROR="error",c.DEBUG="debug",c.LOG_ERROR="log_error"})(fe||(fe={}));var xe=class{constructor(){this._worker=null}_createWorker(c,l){return s(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((p,f)=>{let A=i.join(","),M=new Blob([e,`exports.default(${A});`],{type:"application/javascript; charset=utf-8"}),j=window.URL.createObjectURL(M);this._worker=new Worker(j),this._worker.onmessage=ae=>{switch(ae.data.type){case fe.READY:p();break;case fe.ERROR:f(ae.data.error);break;case fe.FRAME:t(ae.data);break;case fe.DEBUG:o.debug(ae.data.message);break;case fe.LOG_ERROR:u.log(g.ERROR,ae.data.message);break}},this._sendToWorker(fe.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 nt=class extends xe{init(e){return s(this,null,function*(){o.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var R=Object.defineProperty;var V=o=>R(o,"__esModule",{value:!0});var M=typeof require!="undefined"?require:o=>{throw new Error(\'Dynamic require of "\'+o+\'" is not supported\')};var D=(o,i)=>{V(o);for(var e in i)R(o,e,{get:i[e],enumerable:!0})};var A={};D(A,{default:()=>h});var x;(function(e){e.VP9="vp09.00.50.08",e.VP8="vp8"})(x||(x={}));var t;(function(r){r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error"})(t||(t={}));var h=(o,i)=>{let e=null,n=null,m=!0;function E(){return o({locateFile:i}).then(a=>n=a)}function r(a,g,l,b,y){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(m!==l&&(m=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(y),!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(g.byteLength).set(new Uint8Array(g))}catch(s){self.postMessage({type:t.DEBUG,message:s}),e=null,self.postMessage({type:t.FRAME,error:String(s)});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 f=e.getImageWidth(),c=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let p=new Uint8ClampedArray(d.byteLength);if(p.set(d),b){let s=new ImageData(p,f,c);createImageBitmap(s,0,0,f,c).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:p.buffer,width:f,height:c},[p.buffer])}E().then(()=>{self.onmessage=a=>{switch(a.data.type){case t.FRAME:r(a.data.timestamp,a.data.data,a.data.isVP9,a.data.useImageBitmap,a.data.debug);break}},self.postMessage({type:t.READY})}).catch(a=>{self.postMessage({type:t.ERROR,error:String(a)})})};return A;})();\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)},[Vi.default,Vi.default.getUrl])})}decodeFrame(e,t,i,r){let n="ImageBitmap"in window;this._sendToWorker(fe.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 Je=class extends xe{init(e){return s(this,null,function*(){o.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var l=Object.defineProperty;var f=t=>l(t,"__esModule",{value:!0});var D=typeof require!="undefined"?require:t=>{throw new Error(\'Dynamic require of "\'+t+\'" is not supported\')};var E=(t,d)=>{f(t);for(var r in d)l(t,r,{get:d[r],enumerable:!0})};var R={};E(R,{default:()=>V});var n;(function(r){r.VP9="vp09.00.50.08",r.VP8="vp8"})(n||(n={}));var o;(function(e){e.INIT="init",e.READY="ready",e.FRAME="frame",e.ERROR="error",e.DEBUG="debug",e.LOG_ERROR="log_error"})(o||(o={}));var V=()=>{let t=null,d=!0;function r(){self.postMessage({type:o.READY})}function s(a,m,e,u=!1){(!t||d!==e)&&(d=e,t?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${e?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${e?"VP9":"VP8"}`}),t=new VideoDecoder({output:c=>{("createImageBitmap"in c?c.createImageBitmap():createImageBitmap(c)).then(i=>{self.postMessage({type:o.FRAME,data:i}),i.close()}).finally(()=>c.close())},error:c=>{t&&t.state!=="closed"&&t.close(),t=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),t.configure({codec:e?n.VP9:n.VP8}));let p=new EncodedVideoChunk({type:u?"key":"delta",timestamp:a,data:m});t.decode(p)}self.onmessage=a=>{switch(a.data.type){case o.INIT:r();break;case o.FRAME:s(a.data.timestamp,a.data.data,a.data.isVP9,a.data.keyFrame);break}}};return R;})();\n',t=>{t.error?o.warn("WebCodecsDecoder",t.error):e(t.data)})})}decodeFrame(e,t,i,r=!1){this._sendToWorker(fe.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 Ma=65536,Wt=class{constructor(e,t){this._decoderReady=!1;this._decoderQueue=[];this._chunks=[];this._onStream=()=>{};this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;o.debug(`StreamBuilder started for participant [${e}]`),this._participantId=e,this._onStream=t,this._useImageBitmap="ImageBitmap"in window,Je.isBrowserSupported()?this._decoder=new Je:this._decoder=new nt,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}_processFrameData(){let e=new Uint8Array;for(let t of this._chunks){let i=new Uint8Array(e.byteLength+t.data.byteLength);i.set(new Uint8Array(e),0),i.set(new Uint8Array(t.data),e.byteLength),e=i}return this._chunks=[],e}_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()}_decodeFrame(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)})}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)%Ma!==e.sequence){o.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData();this._decodeFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe})}}destroy(){this._decoder.destroy(),this._removeStream(),this._chunks=[],o.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}};var jt=1,ka=1,Or=0,Dr=11,Mr=1,kr=2,wr=4,Nr=8;function xr(a,e,t,i,r,n,c){let l=0;e&&(l|=Mr),t&&(l|=kr),i&&(l|=wr),c||(l|=Nr);let p=new ArrayBuffer(Dr),f=new DataView(p);if(f.setUint8(0,jt),f.setUint16(1,r),f.setUint32(3,a),f.setUint8(7,n?1:0),f.setUint16(8,Or),f.setUint8(10,l),!c)return p;let A=new Uint8Array(p.byteLength+c.byteLength);return A.set(new Uint8Array(p),0),A.set(new Uint8Array(c),p.byteLength),A.buffer}function Lr(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,c=e.getUint16(8),l=e.getUint8(10),p=!!(l&Mr),f=!!(l&kr),A=!!(l&wr),M=!!(l&Nr);if(t!==jt)throw new Error(`Unexpected protocol version. Got ${t}, expected ${jt}`);return{timestamp:r,start:p,end:f,keyframe:A,sequence:i,isVP9:n,ssrc:c,eos:M,data:a.slice(Dr)}}function Ur(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==jt||e.getUint8(1)!==ka||e.getUint16(2)!==Or)}var st=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,c;let t=Lr(e),i=(c=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:c.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];r||(r=new Wt(i,l=>this._onStream(i,l)),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(Je.isBrowserSupported()||nt.isBrowserSupported())&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(y.browserName()==="Safari"&&y.browserVersion()>=15)}};var Bi=gt(require("@vkontakte/libvpx"));var wa=1e3,Tt=class extends xe{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 s(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=l=>t(),r.onerror=()=>i(new Error("Video element error"));let n=r.play(),c=()=>i(new Error("Autoplay is disabled"));n?n.catch(c):c()}})})}_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 s(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 s(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 h=typeof require!="undefined"?require:o=>{throw new Error('Dynamic require of "'+o+'" is not supported')};var x=(o,s)=>{b(o);for(var t in s)u(o,t,{get:s[t],enumerable:!0})};var V={};x(V,{default:()=>g});var m;(function(t){t.VP9="vp09.00.50.08",t.VP8="vp8"})(m||(m={}));var r;(function(e){e.INIT="init",e.READY="ready",e.FRAME="frame",e.ERROR="error",e.DEBUG="debug",e.LOG_ERROR="log_error"})(r||(r={}));var g=(o,s)=>{let t;function E(a,e){return o({locateFile:s}).then(n=>{if(t=new n.VpxEncoder,t.debug(e),!t.init(a?n.VpxType.VP9:n.VpxType.VP8))throw self.postMessage({type:r.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");t.setMaxQuantizer(10),t.setTargetBitrate(1024)})}function R(a,e,n,i){let f=t.allocateImage(a,e);if(!f){self.postMessage({type:r.FRAME,error:"No buffer data"});return}f.set(new Uint8Array(n));let c=Math.round(performance.now()),l=150;if(!t.encode(c,l,i)){self.postMessage({type:r.FRAME,error:"Encode failed"});return}let d=t.readFrame();if(!d){self.postMessage({type:r.FRAME,error:"No encoded data"});return}t.readFrame()&&(self.postMessage({type:r.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:r.LOG_ERROR,message:"LibVPxEncoder-drop"}));let p=new Uint8Array(d.byteLength);p.set(d),self.postMessage({type:r.FRAME,frameType:i?"key":"delta",timestamp:c,duration:l,data:p.buffer},[p.buffer])}self.onmessage=a=>{switch(a.data.type){case r.INIT:E(a.data.isVP9,a.data.debug).then(()=>self.postMessage({type:r.READY})).catch(e=>self.postMessage({type:r.ERROR,error:String(e)}));break;case r.FRAME:R(a.data.width,a.data.height,a.data.imageData,a.data.keyFrame);break}}};return V;})();
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})},[Bi.default,Bi.default.getUrl],{isVP9:this.isVP9(),debug:o.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(fe.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)},wa),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 ot=class extends xe{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return s(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 p=Object.defineProperty;var h=a=>p(a,"__esModule",{value:!0});var g=typeof require!="undefined"?require:a=>{throw new Error('Dynamic require of "'+a+'" is not supported')};var A=(a,l)=>{h(a);for(var r in l)p(a,r,{get:l[r],enumerable:!0})};var y={};A(y,{default:()=>P});var n;(function(r){r.VP9="vp09.00.50.08",r.VP8="vp8"})(n||(n={}));var d;(function(t){t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error"})(d||(d={}));var P=()=>{let a=1e3,l,r,c,m,u,t,i=null,E=0,R=!1;function b(e){l=e.readable,r=l.getReader(),c=e.width,m=e.height,u=e.isVP9,t=e.framerate,f.configure({framerate:t,codec:u?n.VP9:n.VP8,width:c,height:m,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function F(e){E=self.setTimeout(()=>{i&&V(i,e)},a),!R&&(R=!0,r.read().finally(()=>{R=!1,self.clearTimeout(E)}).then(({done:o,value:s})=>{if(i==null||i.close(),i=null,!(o||!s)){if(!f){r.releaseLock(),l.cancel();return}i=s,V(s,e)}}))}function V(e,o){(e.codedWidth!==c||e.codedHeight!==m)&&(c=e.codedWidth,m=e.codedHeight,f.configure({framerate:t,codec:u?n.VP9:n.VP8,width:c,height:m,latencyMode:"realtime"})),f.encode(e,{keyFrame:o})}let f=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:b(e.data);break;case d.FRAME:F(e.data.keyFrame);break}}};return y;})();
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(fe.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 Na=16*1024,xa=11,Vr=Na-xa,La=65536,Fi=0,ct=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(c=>{o.warn("sendFrame failed",c),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};ot.isBrowserSupported()?this._encoder=new ot(e,i):this._encoder=new Tt(e,i),this._datachannel.onmessage=r=>{Ur(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 c=xr(e,t,i,r,Fi,this._encoder.isVP9(),n);return Fi=(Fi+1)%La,c}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return s(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+Vr),c=e.data.byteLength<=t+n.byteLength,l=this._wrapHeader(e.timestamp,!t,c,e.type==="key",n);this._datachannel.onbufferedamountlow=c?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(l)}catch(p){o.warn("Error send data to DataChannel",p),r();return}c||window.setTimeout(()=>this._sendChunk(e,t+Vr,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 ot.isBrowserSupported()||Tt.isBrowserSupported()}};var te=class{static get sessionKey(){return te._sessionKey}static set sessionKey(e){te._sessionKey=e}static get sessionSecretKey(){return te._sessionSecretKey}static set sessionSecretKey(e){te._sessionSecretKey=e}static get accessToken(){return te._accessToken}static set accessToken(e){te._accessToken=e}static isEmpty(){return!te._sessionKey||!te._sessionSecretKey}};var E=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(E._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(E._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(E._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(te.accessToken=e.apiAuth.accessToken,te.sessionKey=e.apiAuth.sessionKey,te.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(E._params,e)}static get(e){return E._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.4.4-dev.00c279b.0"}static get debug(){return!1}static get protocolVersion(){return 5}static get platform(){return E._params.platform}static set platform(e){E._params.platform=e}static get clientType(){return E._params.clientType}static set clientType(e){E._params.clientType=e}static get device(){return E._params.device}static get apiAppId(){return 42}static get apiKey(){return E._params.apiKey}static get apiEnv(){switch(E._params.apiEnv){case"TEST":return{api:"https://apitest.ok.ru/api/",connect:"https://test.ok.ru/"};case"VIDEOTEST":return{api:"https://videotestapi.ok.ru/api/",connect:"https://test.ok.ru/"};case"DEV":return{api:"https://1.api.an-eremeev.devdc.odkl.ru/api/",connect:"https://1.web.an-eremeev.devdc.odkl.ru/"};default:return{api:"https://api.ok.ru/",connect:"https://connect.ok.ru/"}}}static get authToken(){return E._params.authToken}static set authToken(e){E._params.authToken=e}static get anonymToken(){return E._params.anonymToken}static set anonymToken(e){E._params.anonymToken=e}static get domain(){return E._params.domain}static get iceServers(){return E._params.iceServers}static set iceServers(e){E._params.iceServers=e}static get wssBase(){return E._params.wssBase}static set wssBase(e){E._params.wssBase=e}static get wssToken(){return E._params.wssToken}static set wssToken(e){E._params.wssToken=e}static get signalingReconnectDelay(){return E._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return E._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return E._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return E._params.waitConnectionDelay}static get waitResponseDelay(){return E._params.waitResponseDelay}static get waitMessageDelay(){return E._params.waitMessageDelay}static get debugLog(){return E._params.debugLog}static get forceRelayPolicy(){return E._params.forceRelayPolicy}static set forceRelayPolicy(e){E._params.forceRelayPolicy=e}static get videoMinWidth(){return E._params.videoMinWidth}static get videoMaxWidth(){return E._params.videoMaxWidth}static set videoMaxWidth(e){E._params.videoMaxWidth=e}static get videoMinHeight(){return E._params.videoMinHeight}static get videoMaxHeight(){return E._params.videoMaxHeight}static set videoMaxHeight(e){E._params.videoMaxHeight=e}static get videoAspectRatio(){return E._params.videoAspectRatio}static get videoFrameRate(){return E._params.videoFrameRate}static get videoFacingMode(){return E._params.videoFacingMode}static get screenFrameRate(){return E._params.screenFrameRate}static get videoEffects(){return E._params.videoEffects}static set videoEffects(e){E._params.videoEffects=e}static get videoEffectMaxWidth(){return E._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){E._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return E._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){E._params.videoEffectMaxHeight=e}static get voiceParams(){return E._params.voiceParams}static get specListenerParams(){return E._params.specListenerParams}static get iceRestartWaitTime(){return E._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return E._params.transportConnectionWaitTime}static get statisticsInterval(){return E._params.statisticsInterval}static set statisticsInterval(e){E._params.statisticsInterval=e}static get networkStatisticsInterval(){return E._params.networkStatisticsInterval}static get perfStatReportEnabled(){return E._params.perfStatReportEnabled}static get producerNotificationDataChannel(){return E._params.producerNotificationDataChannel&&st.isBrowserSupported()}static get producerCommandDataChannel(){return E._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return E._params.consumerScreenDataChannel&&ct.isBrowserSupported()}static get producerScreenDataChannel(){return E._params.producerScreenDataChannel&&E.producerNotificationDataChannel}static get noiseSuppression(){return E._params.noiseSuppression}static set noiseSuppression(e){E._params.noiseSuppression=e}static get preferH264(){return E._params.preferH264}static get preferVP9(){return E._params.preferVP9}static get audioNack(){return E._params.audioNack}static get consumerScreenTrack(){return E._params.consumerScreenTrack&&E.consumerScreenDataChannel}static get producerScreenTrack(){return E._params.producerScreenTrack&&E.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=E._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get videoTracksCount(){return E.producerNotificationDataChannel?E._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return E._params.breakVideoPayloadTypes}static get filteredMessages(){return E._params.filteredMessages}static get batchParticipantsOnStart(){return E._params.batchParticipantsOnStart}static get participantStateMapped(){return E._params.participantStateMapped}},d=E;d._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"PROD",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,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,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,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!1,producerScreenTrack:!1,videoTracksCount:0,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!1};var q;(function(p){p.WAITING_HALL="WAITING_HALL",p.WAITING="WAITING",p.CONNECTING="CONNECTING",p.CONNECTED="CONNECTED",p.RECONNECT="RECONNECT",p.ERROR="ERROR",p.HANGUP="HANGUP",p.PERMISSIONS="PERMISSIONS"})(q||(q={}));function V(a,...e){let t=d.get(a);t&&setTimeout(t,0,...e)}function Le(a){return Object.assign({},a)}function dt(a){return a.slice()}var Gi;(function(me){function a(T,U){V("onLocalStream",T,Le(U))}me.onLocalStream=a;function e(T,U){V("onScreenStream",T,Le(U))}me.onScreenStream=e;function t(T,U){V("onLocalStreamUpdate",Le(T),U)}me.onLocalStreamUpdate=t;function i(T){V("onLocalStatus",T)}me.onLocalStatus=i;function r(T,U){V("onRemoteStream",T,U)}me.onRemoteStream=r;function n(T,U,ce){V("onRemoteLive",T,U,ce)}me.onRemoteLive=n;function c(T,U){V("onRemoteScreenStream",T,U)}me.onRemoteScreenStream=c;function l(T,U,ce,ht){V("onConversation",T,Le(U),Le(ce),ht)}me.onConversation=l;function p(T,U){V("onRemoteMediaSettings",T,Le(U))}me.onRemoteMediaSettings=p;function f(T,U){V("onRemoteParticipantState",T,Le(U))}me.onRemoteParticipantState=f;function A(T,U,ce=null){V("onRemoteStatus",T,U,ce)}me.onRemoteStatus=A;function M(T,U,ce=null){V("onParticipantStatus",T,U,ce)}me.onParticipantStatus=M;function j(){V("onPermissionsRequested")}me.onPermissionsRequested=j;function ae(T){V("onPermissionsError",T)}me.onPermissionsError=ae;function R(T){V("onRemoteRemoved",T)}me.onRemoteRemoved=R;function ge(T,U,ce){V("onCallState",T,U,Le(ce))}me.onCallState=ge;function Me(T,U){V("onDeviceSwitched",T,U)}me.onDeviceSwitched=Me;function he(T,U,ce,ht=!1,Zt=!1,ei=null,la=null){V("onMuteStates",Le(T),dt(U),dt(ce),ht,Zt,ei,la)}me.onMuteStates=he;function F(T,U){V("onRolesChanged",T,dt(U))}me.onRolesChanged=F;function ue(T){V("onLocalRolesChanged",dt(T))}me.onLocalRolesChanged=ue;function be(T,U){V("onPinnedParticipant",T,U)}me.onPinnedParticipant=be;function Ae(T){V("onLocalPin",T)}me.onLocalPin=Ae;function mt(T){V("onOptionsChanged",dt(T))}me.onOptionsChanged=mt;function ir(){V("onCallAccepted")}me.onCallAccepted=ir;function rr(){V("onRateNeeded")}me.onRateNeeded=rr;function C(T){V("onSpeakerChanged",T)}me.onSpeakerChanged=C;function P(T){V("onVolumesDetected",dt(T))}me.onVolumesDetected=P;function O(T,U){V("onLocalVolume",T,U)}me.onLocalVolume=O;function h(T,U){V("onJoinStatus",T,U)}me.onJoinStatus=h;function D(T,U){V("onHangup",T,U)}me.onHangup=D;function Te(T){V("onMultipartyChatCreated",Le(T))}me.onMultipartyChatCreated=Te;function X(){V("onDeviceChange")}me.onDeviceChange=X;function L(T){V("onFingerprintChange",T)}me.onFingerprintChange=L;function Z(){V("onTokenExpired")}me.onTokenExpired=Z;function _(T,U,ce=!1){V("onChatMessage",T,U,ce)}me.onChatMessage=_;function $(T,U,ce=!1){V("onCustomData",T,U,ce)}me.onCustomData=$;function de(T,U,ce,ht,Zt,ei){V("onRecordStarted",T,U,ce,ht,Zt,ei)}me.onRecordStarted=de;function m(){V("onRecordStopped")}me.onRecordStopped=m;function Ve(T){V("onLocalNetworkStatusChanged",T)}me.onLocalNetworkStatusChanged=Ve;function Y(T){V("onNetworkStatusChanged",T)}me.onNetworkStatusChanged=Y;function ke(T,...U){V("onDebugMessage",T,...U)}me.onDebugMessage=ke;function _e(T,U){let ce=Object.assign({},T,{memory:U});V("onStatistics",ce)}me.onStatistics=_e;function oe(){V("onAutoplayError")}me.onAutoplayError=oe;function ee(T,U,ce){V("onChatRoomUpdated",T,U,ce)}me.onChatRoomUpdated=ee})(Gi||(Gi={}));var v=Gi;var pe;(function(r){r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR"})(pe||(pe={}));var Hi;(function(ue){let a="📞",e=(be,...Ae)=>{v.onDebugMessage(be,...Ae)},t=!1,i=(be,Ae)=>(...mt)=>{be(...mt),vr(Ae,mt)},r=console.debug.bind(console,a),n=console.log.bind(console,a),c=console.warn.bind(console,a),l=console.error.bind(console,a),p=e.bind(null,pe.DEBUG),f=e.bind(null,pe.LOG),A=e.bind(null,pe.WARN),M=e.bind(null,pe.ERROR);ue.debug=p,ue.log=f,ue.warn=A,ue.error=M;function Me(){return t}ue.enabled=Me;function he(be){t=be,d.debugLog&&Ci(),be?(ue.debug=d.debugLog?i(r,pe.DEBUG):r,ue.log=d.debugLog?i(n,pe.LOG):n,ue.warn=d.debugLog?i(c,pe.WARN):c,ue.error=d.debugLog?i(l,pe.ERROR):l):(ue.debug=d.debugLog?i(p,pe.DEBUG):p,ue.log=d.debugLog?i(f,pe.LOG):f,ue.warn=d.debugLog?i(A,pe.WARN):A,ue.error=d.debugLog?i(M,pe.ERROR):M)}ue.toggle=he;function F(be,...Ae){switch(be){case pe.DEBUG:ue.debug(...Ae);break;case pe.LOG:ue.log(...Ae);break;case pe.WARN:ue.warn(...Ae);break;case pe.ERROR:ue.error(...Ae);break}}ue.send=F})(Hi||(Hi={}));var o=Hi;var Re;(function(i){i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP"})(Re||(Re={}));var ie;(function(l){function a(p){return p.length?typeof p[0]=="object"?p:p.map(f=>e(f)):[]}l.fromIds=a;function e(p,f=Re.USER){return{id:p,type:f}}l.fromId=e;function t(p){return{id:p.id,type:p.type==="ANONYM"?Re.ANONYM:Re.USER}}l.fromSignaling=t;function i(p){return`{"id":"${p.id}","type":"${p.type}"}`}l.toString=i;function r(p,f=Re.USER){return i(e(p,f))}l.fromIdToString=r;function n(p){try{return JSON.parse(p)}catch(f){throw new Error(`Failed to parse ExternalId from string '${p}'`)}}l.fromString=n;function c(p,f){return p.id===f.id&&p.type===f.type}l.compare=c})(ie||(ie={}));var Ie;(function(r){r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE"})(Ie||(Ie={}));var Wi=":",Br="s",Fr="m";function Ye(a){return a.participantId+(a.mediaType?Wi+Br+a.mediaType:"")+(a.streamName?Wi+Fr+a.streamName:"")}function Rt(a){let e=a.split(Wi),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i={participantId:t,mediaType:null};for(let r of e)switch(r.charAt(0)){case Br:i.mediaType=Ua(r.slice(1));break;case Fr:i.streamName=r.slice(1);break;default:throw new Error("Unexpected parameter type "+r.charAt(0)+" in stream description "+a)}return i}function Ua(a){for(let e of Object.keys(Ie))if(e===a)return Ie[e];return null}function ji(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 Kt(a,e){return!(!ji(a.camera,e.camera)||!ji(a.screenSharing,e.screenSharing))}function Ki(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function Gr(a){return{camera:Object.assign({},a.camera),screenSharing:Object.assign({},a.screenSharing)}}function Hr(a){try{return btoa(JSON.stringify(a))}catch(e){o.warn("WaitingParticipant: failed convert to string",a,e)}return null}function Wr(a){try{return JSON.parse(atob(a))}catch(e){o.warn("WaitingParticipant: failed convert from string",a,e)}return null}var yt=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(g.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,u.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"),u.log(g.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),u.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===K.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var $t=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 c;if(!((c=this._output)==null?void 0:c.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"),v.onAutoplayError()},r=l=>{t.srcObject=new MediaStream([l]),t.load();let p=t.play();p?p.catch(i):i()},n=()=>{var p;o.debug("Recover audio playback");let l=(p=this._output)==null?void 0:p.audioTrack;l?r(l):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 s(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(g.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var Va=90,Ba=3,qt=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}),v.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>Va?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 Fa=44100,Pt=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=Fa/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,c)=>n+c,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 Jt=class extends Q{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&v.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,ne.SOURCE_CHANGED,r=>{r.kind===K.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new Pt("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 Ga=1e3;function Ue(a,e,t=0){return e in a&&a[e]?a[e]:t}function jr(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function We(a,e){return t=>t[a]===e}function Ha(a){return(e,t)=>e[a]-t[a]}function Yt(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 ja(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function $i(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=ja(t[1])?$i(t[1]):t[1],e),{})}function Ka(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function $a(a){return s(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(Ka).then(Wa)})}function qa(a){let e=a.filter(We("type","candidate-pair")).sort(Ha("priority")).find(jr(We("nominated",!0),We("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(We("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(We("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}})),$i(t)}function Ja(a,e){let t=Yt("id",a),i=a.filter(jr(We("type","inbound-rtp"),We("type","outbound-rtp")));y.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,c)=>{if(!n[c.ssrc])n[c.ssrc]=c;else{let l=Object.assign({},n[c.ssrc],c),p=n[c.ssrc].isRemote?c:n[c.ssrc];l.id=p.id,l.type=p.type,delete l.isRemote,delete l.remoteId,n[l.ssrc]=l}return n},{})));let r={};if(y.browserName()==="Safari"){let n=a.filter(We("type","track"));r=Yt("trackIdentifier",n)}return i.map(n=>{let c=Number(n.ssrc),l=n.mediaType||n.kind,p=n.trackId,f=n.type,A=n.codecId;if(y.browserName()==="Safari"){let j=/^.+_([\d]+)$/.exec(n.id);if(j&&(c=parseInt(j[1],10)),l=n.id.indexOf("Audio")>0?"audio":"video",e[c]){let ae=l+"-"+e[c];r[ae]&&(p=r[ae].id)}}if(!f||!c||!l)return null;let M={ssrc:c,type:f,kind:l,bytesReceived:Ue(n,"bytesReceived"),bytesSent:Ue(n,"bytesSent"),jitter:Ue(n,"jitter"),packetsLost:Ue(n,"packetsLost"),packetsReceived:Ue(n,"packetsReceived"),packetsSent:Ue(n,"packetsSent"),fractionLost:Ue(n,"fractionLost"),pliCount:Ue(n,"pliCount"),firCount:Ue(n,"firCount"),nackCount:Ue(n,"nackCount"),userId:e[c]};if(A&&t[A]){let j=t[A];M.clockRate=j.clockRate,M.mimeType=j.mimeType}if(p&&t[p]){let j=t[p];M.frameHeight=j.frameHeight,M.frameWidth=j.frameWidth,M.framesDecoded=j.framesDecoded,M.framesReceived=j.framesReceived,M.framesDropped=j.framesDropped}return $i(M)}).filter(n=>!!n)}function Ya(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=Yt("ssrc",a.rtps),i=Yt("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let c=t[n],l=i[n];if(!(!c||!l)){if(c.bytesReceived&&c.bytesReceived>l.bytesReceived&&(c.bandwidth=Math.round((c.bytesReceived-l.bytesReceived)/r)),c.bytesSent&&c.bytesSent>l.bytesSent&&(c.bandwidth=Math.round((c.bytesSent-l.bytesSent)/r)),c.packetsReceived)if(c.packetsReceived>l.packetsReceived||c.packetsLost>l.packetsLost){let p=c.packetsLost-l.packetsLost,f=c.packetsReceived-l.packetsReceived;c.packetLoss=parseFloat((100*p/(p+f)).toFixed(2))}else c.packetLoss=0;c.framesDropped&&l.framesDropped&&c.framesDropped>l.framesDropped&&(c.framesDroppedDelta=parseFloat(((c.framesDropped-l.framesDropped)/r).toFixed(0)))}}),a}function bt(i,r){return s(this,arguments,function*(a,e,t={}){let n=yield $a(a),c={timestamp:Date.now(),transport:qa(n),rtps:Ja(n,t)};return e?Ya(c,e):(yield I.delay(Ga),bt(a,c,t))})}var Qt=.8,Qe=class extends Q{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=k.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.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ne.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ne.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,!0),this._applySettings()}catch(c){u.log(g.ERROR,"addTrack-direct"),o.error("Unable to add media source tracks",c,{participantId:this._participantId}),this._failedOnCreate=c;return}this._createOffer(!1).catch(c=>{this._state===k.IDLE?this._failedOnCreate=c:this.close(c)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==k.IDLE&&e!==k.CLOSED&&e!==k.FAILED&&this._startStatInterval()}open(e=null){return s(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,!0),this._applySettings()}catch(i){u.log(g.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(k.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(S.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Kt(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(S.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(k.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(k.CLOSED)),this._triggerEvent(S.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(S.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case w.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case w.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 w.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=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 s(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(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 s(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 s(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(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(S.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(S.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return s(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=>s(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===k.IDLE||e===k.OPENED?this._setState(k.CONNECTING):this._setState(k.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),u.log(g.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(k.CONNECTED),this._stopReconnection(),I.getPeerConnectionHostInfo(this._pc).then(e=>{e&&u.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(k.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(W.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(u.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}),u.log(g.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return s(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(g.ERROR,"createOffer-direct"),i}).then(i=>s(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=Qe._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(g.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return s(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(g.ERROR,"createAnswer-direct"),e}).then(e=>s(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=Qe._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(g.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),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(g.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}bt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:W.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:W.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(S.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=he=>he.rtt<=this._networkLimits.goodNet.rtt&&he.loss<=this._networkLimits.goodNet.loss,i=he=>he.rtt>=this._networkLimits.badNet.rtt||he.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((he,F)=>Math.max(he,F.packetLoss||0),0),c={rtt:this._lastNetworkStat.rtt*(1-Qt)+r*Qt,loss:this._lastNetworkStat.loss*(1-Qt)+n*Qt},l=i(c),p=t(c),f=i(this._remoteNetworkStat),A=t(this._remoteNetworkStat),M=i(this._lastNetworkStat),j=t(this._lastNetworkStat),ge=l||f?.2:p&&A?1:0,Me=Date.now();if((M!==l||j!==p||Me-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},c)},null).catch(he=>{o.warn("Unable to send [bad-net]",he)})),ge){let he={};he[this._participantId]=he[""]=ge,this._triggerEvent(S.NETWORK_STATUS,he)}this._lastNetworkStat.rtt=c.rtt,this._lastNetworkStat.loss=c.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);this._fingerprint===null?this._fingerprint=t:(v.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=I.applySettings(this._pc,e,this._prevConsumerSettings))}};var qi;(function(r){r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare"})(qi||(qi={}));var At=qi;var ze=gt(require("messagepack"));var Ji=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var n,c;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let l=(0,ze.decode)(r);return Object.entries(l).forEach(([R,ge])=>{let Me=Rt(R);this.streamDescriptionByCompactId.set(ge,Me)}),null;case 2:case 4:let p=(0,ze.decode)(r),f=[];for(let R of p){let ge=this.getStreamDescription(R);ge&&f.push(ge.participantId)}return i===2?{type:"notification",notification:w.AUDIO_ACTIVITY,activeParticipants:f}:{type:"notification",notification:w.STALLED_ACTIVITY,stalledParticipants:f};case 3:let A=(0,ze.decode)(r);return{type:"notification",notification:w.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(A))==null?void 0:n.participantId};case 5:let M=(0,ze.decode)(r);return{type:"notification",notification:w.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:M[0],maxDimension:M[1]}};case 6:let j=(0,ze.decode)(r),ae={};for(let[R,ge]of Object.entries(j)){let Me=(c=this.getStreamDescription(Number(R)))==null?void 0:c.participantId;Me&&(ae[Me]=ge/100)}return{type:"notification",notification:w.NETWORK_STATUS,statuses:ae};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return o.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,ze.decode)(e),i=[];for(let[r,n]of Object.entries(t)){let c=n[0],l=n[1],p=n[2],f;if(c!==null){if(f=this.getStreamDescription(c),!f){o.error(`could not uncompress participant ID ${c}`);continue}}else f=null;if(p===null){o.error("unexpected null sequenceNumber",r,n);continue}let A=Oe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,M=l?l>>>0:null;i.push({participantStreamDescription:f,streamId:A,rtpTimestamp:M,sequenceNumber:p})}return{type:"notification",notification:w.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Kr="videochat-epi",Ot=class extends Q{constructor(e,t){super();this._previousTimestamp=0;this._signaling=t,this.subscribe(e,S.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Kr)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return s(this,null,function*(){if(!d.perfStatReportEnabled||!e.inbound||!e.inbound.rtps)return;let t=e.inbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.framesDecoded+=n.framesDecoded||0,r.framesReceived+=n.framesReceived||0),r),{framesDecoded:0,framesReceived:0}),i=Date.now();if(!(this._previousTimestamp+5e3>i)){if(t.framesDecoded)try{let r=yield this._signaling.reportPerfStat(t);localStorage.setItem(Kr,r.estimatedPerformanceIndex)}catch(r){}this._previousTimestamp=i}})}};var Qa=90,za=4294967295,ye=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._reconnectionPrevented=!1;this._state=k.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,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ne.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ne.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,ne.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Ot(this,e),this._serverSettings=i,o.debug("ServerTransport: Created")}getState(){return this._state||k.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==k.IDLE&&e!==k.CLOSED&&e!==k.FAILED&&this._startStatInterval()}open(){if(this._isOpen){o.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(o.error("ServerTransport: Closed",e),this._setState(k.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(k.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Kt(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(S.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=()=>{o.debug(`[${t}] data channel opened`),r.onerror=n=>{o.error(`[${t}] data channel error`,n)},i(r)}}_openConnection(e=!1){o.debug("ServerTransport: Open single connection");let t={};y.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=I.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,At.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Ji,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,At.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,At.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){o.error("ServerTransport: Unable to add media source tracks",i),u.log(g.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,At.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(k.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==k.OPENED&&(this._setState(k.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(S.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(S.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(S.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(S.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
- `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Oe.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 ct(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 st(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(S.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(S.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!==K.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(y.getBlackMediaTrack()).catch(l=>{o.error("Could not disable video upload",l)});return}let c=this._mediaSource.getSendVideoTrack();if(!r&&n&&c){o.log("Enabling video upload"),this._disabledSenders.delete(i);let l=i.track;l.enabled=c.enabled,i.replaceTrack(c).then(()=>l.stop()).catch(p=>{o.error("Could not enable video upload",p)})}I.applyVideoTrackSettings(e,i,c!=null?c: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(S.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 s(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield bt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(S.REMOTE_DATA_STATS,{inbound:{topology:W.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:W.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(c=>c.type==="inbound-rtp"&&c.kind==="audio"&&this._ssrcMap[c.ssrc]==="mix");if(!t)return;let i=Oe.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let c=t.bytesReceived-r.bytesReceived;c>=0&&c<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(S.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Ot.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};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return s(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(g.ERROR,"setRemoteDescription-single"),i}).then(()=>s(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(g.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=I.patchSDP(i.sdp,!1,y.isBrokenH264(),!1),i)).then(i=>s(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(g.ERROR,"setLocalDescription-single"),i}).then(i=>s(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(g.ERROR,"acceptProducer")}).then(()=>s(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 s(this,null,function*(){if(!!this._isOpen)switch(e.notification){case w.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case w.REALLOC_CON:this._reconnect();break;case w.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case w.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case w.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case w.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return s(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(S.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(S.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(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===k.IDLE||i===k.OPENED?this._setState(k.CONNECTING):e.iceConnectionState==="checking"&&this._setState(k.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(k.RECONNECTING);break;case"connected":this._setState(k.CONNECTED),I.getPeerConnectionHostInfo(e).then(r=>{r&&u.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),u.log(g.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=y.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(y.browserName(),y.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return u.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 u.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 c=r[0].rtpTimestamp;if(!Number.isInteger(c))return u.log(g.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),o.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${c}`),0;let l=t-c&za,p=Math.ceil(l/Qa);return Math.min(100,Math.max(0,p))}};var S;(function(R){R.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",R.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",R.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",R.REMOTE_ALL_STALL="REMOTE_ALL_STALL",R.REMOTE_DATA_STATS="REMOTE_DATA_STATS",R.STATE_CHANGED="STATE_CHANGED",R.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",R.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",R.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",R.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",R.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",R.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",R.NETWORK_STATUS="NETWORK_STATUS",R.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED"})(S||(S={}));var k;(function(l){l.IDLE="IDLE",l.OPENED="OPENED",l.CONNECTING="CONNECTING",l.RECONNECTING="RECONNECTING",l.CONNECTED="CONNECTED",l.CLOSED="CLOSED",l.FAILED="FAILED"})(k||(k={}));var W;(function(t){t.DIRECT="DIRECT",t.SERVER="SERVER"})(W||(W={}));var Yi=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=k.IDLE;this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),e===W.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===W.DIRECT&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology===W.SERVER&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){o.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){o.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology===W.DIRECT&&this._directTransport&&this._directTransport.open(t),this._topology===W.SERVER&&this._serverTransport&&(this._serverTransport.open(),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===W.DIRECT&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology===W.SERVER&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,k.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(S.STATE_CHANGED,i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent(S.STATE_CHANGED,[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent(S.LOCAL_STATE_CHANGED,e))}_onSignalingNotification(e){if(e.notification===w.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===w.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(g.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology===W.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===W.DIRECT){let i=e.offerTo||[],r=e.offerToTypes||[],n=i.length&&r.length?I.composeId(i[0],r[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 c=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=n===c;this._directTransport=this._createDirectTransport(c,l)}this._opened.indexOf(c)>=0&&this._directTransport.open()}this._triggerEvent(S.TOPOLOGY_CHANGED,this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new Qe(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),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(S.REMOTE_TRACK_ADDED,this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener(S.REMOTE_TRACK_REMOVED,this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener(S.REMOTE_DATA_STATS,this._onDirectRemoteDataStats.bind(this)),i.addEventListener(S.STATE_CHANGED,this._onDirectTransportChanged.bind(this,e)),i.addEventListener(S.NETWORK_STATUS,this._onTransportNetworkStatus.bind(this)),i.addEventListener(S.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this,W.DIRECT))),i}_createServerTransport(){let e=new ye(this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!1),this._stListeners&&this._stListeners.length>0&&o.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener(S.REMOTE_TRACK_ADDED,this._onServerRemoteTrackAdded.bind(this)),e.addEventListener(S.REMOTE_TRACK_REMOVED,this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener(S.REMOTE_ALL_STALL,this._onServerRemoteAllStall.bind(this)),e.addEventListener(S.REMOTE_DATA_STATS,this._onServerRemoteDataStats.bind(this)),e.addEventListener(S.STATE_CHANGED,this._onServerTransportChanged.bind(this)),e.addEventListener(S.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener(S.SIGNALLED_ACTIVE_PARTICIPANTS,this._onTransportActiveParticipants.bind(this)),e.addEventListener(S.SIGNALLED_SPEAKER_CHANGED,this._onTransportSpeakerChanged.bind(this)),e.addEventListener(S.SIGNALLED_STALLED_PARTICIPANTS,this._onTransportStalledParticipants.bind(this)),e.addEventListener(S.NETWORK_STATUS,this._onTransportNetworkStatus.bind(this)),e.addEventListener(S.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),e.addEventListener(S.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this,W.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===k.CONNECTED&&this._topology===W.DIRECT&&this._releaseServerTransport(!0),(t===k.CLOSED||t===k.FAILED)&&(this._releaseDirectTransport(!1),this._topology===W.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===W.DIRECT&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e===k.CONNECTED&&this._topology===W.SERVER&&this._releaseDirectTransport(!0),(e===k.CLOSED||e===k.FAILED)&&(this._releaseServerTransport(!1),this._topology===W.SERVER&&(this._allocated=[],this._opened=[])),this._topology===W.SERVER&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent(S.ACTIVE_PARTICIPANTS_NO_SIGNAL)}_onTransportActiveParticipants(e){this._topology===W.SERVER&&this._triggerEvent(S.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_onTransportStalledParticipants(e){this._topology===W.SERVER&&this._triggerEvent(S.SIGNALLED_STALLED_PARTICIPANTS,e)}_onTransportSpeakerChanged(e){this._topology===W.SERVER&&this._triggerEvent(S.SIGNALLED_SPEAKER_CHANGED,e)}_onTransportNetworkStatus(e){this._triggerEvent(S.NETWORK_STATUS,e)}_onRemoteStreamSecond(e,t){this._triggerEvent(S.REMOTE_STREAM_SECOND,e,t)}_onPeerConnectionClosed(e){this._triggerEvent(S.PEER_CONNECTION_CLOSED,e)}_onServerRemoteAllStall(e){this._topology===W.SERVER&&this._triggerEvent(S.REMOTE_ALL_STALL,e)}_onServerRemoteDataStats(e){this._triggerEvent(S.REMOTE_DATA_STATS,e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent(S.REMOTE_TRACK_ADDED,e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent(S.REMOTE_TRACK_REMOVED,e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent(S.REMOTE_DATA_STATS,e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent(S.REMOTE_TRACK_ADDED,e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent(S.REMOTE_TRACK_REMOVED,e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!==W.SERVER?(u.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):(u.log(g.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Ge;(function(e){e.VOLUMES_DETECTED="VOLUMES_DETECTED"})(Ge||(Ge={}));var Qi=class extends Q{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,S.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,S.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,S.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,S.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===K.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Pt(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===K.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===Oe.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent(Ge.VOLUMES_DETECTED,e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var lt;(function(e){e.SPEAKER_CHANGED="SPEAKER_CHANGED"})(lt||(lt={}));var zi=class extends Q{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,Ge.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,S.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,S.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,S.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(lt.SPEAKER_CHANGED,i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent(lt.SPEAKER_CHANGED,e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var zt=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,S.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,Ge.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===k.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===k.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),u.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!==k.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),u.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),u.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 Xa=1e3,Za=1e4,J;(function(r){r.IDLE="IDLE",r.PROCESSING="PROCESSING",r.ACTIVE="ACTIVE",r.CLOSE="CLOSE"})(J||(J={}));var B=class extends Q{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state=J.IDLE;this._participantState=H.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._signalingServerSettings={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 $t,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Xa))}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,c=!1){return s(this,null,function*(){if(B._activationMutex)throw u.log(g.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new N(b.FAILED);B._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let l=this._mediaSource.getMediaSettings();t===we.CHAT||e.length>1?this._logWithMediaSettings(g.OUTGOING_MULTIPARTY_CALL,l):this._logWithMediaSettings(g.OUTGOING_CALL,l);let p=yield this._startConversation(e,t,Be.OUTGOING,i,r,n,c);if(!this._conversation)throw new N(b.UNKNOWN_ERROR);if(this._participantState=H.ACCEPTED,this._signaling.changeMediaSettings(l),yield this._registerParticipants(p.conversation.participants),this._processConnectionData(p),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new N(b.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let f=Object.values(this._participants),A;return d.batchParticipantsOnStart&&(A=I.mapSharedParticipants(f)),v.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),v.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,A),v.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),B._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(f,q.WAITING),this._conversation}catch(l){throw this._close(l,"Unable to start conversation"),l}finally{B._activationMutex=!1}})}onJoin(e){return s(this,null,function*(){if(B._activationMutex)throw u.log(g.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new N(b.FAILED);B._activationMutex=!0,this._state=J.PROCESSING;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new N(b.UNKNOWN_ERROR);return v.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(o.log("In waiting hall"),B._current=this,B._activationMutex=!1,this._signaling.readyToSend(),v.onLocalStatus(q.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw B._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return s(this,null,function*(){o.debug("Join conversation part 2"),B._activationMutex=!0;try{if(this._participantState=H.ACCEPTED,!this._conversation||!this._mediaSource)throw new N(b.UNKNOWN_ERROR);if(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 N(b.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=I.mapSharedParticipants(t)),v.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),v.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state=J.ACTIVE,this._changeFeatureSet(),B._current=this,d.batchParticipantsOnStart||this._setParticipantsStatus(t,q.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 s(this,arguments,function*(e,t=z.USER,i){if(B._activationMutex)throw o.warn("Conversation: there is already running activation"),new N(b.REJECTED);B._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new N(b.UNKNOWN_ERROR);if(!n.conversation.participants.find(l=>{var p;return l.state===H.CALLED&&l.id===((p=this._conversation)==null?void 0:p.userId)}))throw o.log("Push rejected (there is an active call)"),u.log(g.PUSH,"rejected"),new N(b.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),u.log(g.PUSH,"accepted"),B._current=this,B._delayedHangup)throw new N(b.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(wt.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 s(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new N(b.UNKNOWN_ERROR);this._state=J.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()),v.onCallAccepted(),this._state=J.ACTIVE,this._participantState=H.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return s(this,null,function*(){if(this._state!==J.IDLE)throw u.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 N(b.UNKNOWN_ERROR);this._state=J.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=H.ACCEPTED;let i=Object.values(this._participants),r;d.batchParticipantsOnStart&&(r=I.mapSharedParticipants(i)),v.onCallAccepted(),v.onLocalStream(this._mediaSource.getStream(),t),v.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),v.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(Fe.MUTE)||n.includes(Fe.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state=J.ACTIVE,this._changeFeatureSet(),d.batchParticipantsOnStart||this._setParticipantsStatus(i,q.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return s(this,null,function*(){var e;if(this._state!==J.IDLE)throw u.log(g.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state=J.PROCESSING,o.debug("Decline incoming call"),this._logWithMediaSettings(g.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=H.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(b.REJECTED)),this._close(new N(b.REJECTED))})}hangup(){return s(this,null,function*(){o.debug("Hangup");let e=this._state===J.ACTIVE?b.HUNGUP:b.CANCELED;u.log(g.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new N(e))):v.onHangup(new N(b.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return s(this,null,function*(){if(!this._signaling.ready){this._close(new N(b.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=b.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(e,n,r)})}removeParticipant(e,t=!1){return s(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){if(!this._transport)return;let i=[];for(let r of e)(r.state===H.CALLED||r.state===H.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===H.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&o.error(t,e),o.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(b.FAILED):u.log(g.ERROR,e.hangup),B._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([b.CANCELED,b.NOT_FRIENDS,b.CALLEE_IS_OFFLINE,b.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===b.REJECTED&&!e.remote){v.onHangup(e,i),this.destroy();return}if(e.hangup===b.HUNGUP&&(!e.remote||this._participantState===H.CALLED)){v.onHangup(e,i),this.destroy();return}if(e.hangup===b.MISSED&&!e.remote){v.onHangup(e,i),this.destroy();return}if(e.hangup===b.SOCKET_CLOSED&&B._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===b.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state=J.CLOSE,this._participantState=H.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,B._current=null,B._delayedHangup=!1,v.onHangup(e||new N(b.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,B._current=null,B._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return s(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 c=r.urls.filter((l,p,f)=>f.indexOf(l)===p);c.forEach(l=>c.push(`${l}?transport=tcp`)),i.push({urls:c,username:r.username,credential:r.credential})}d.iceServers=i,d.wssBase=t.endpoint,d.wssToken=t.token,t.client_type&&(d.clientType=t.client_type)})}_startConversation(e,t,i,r,n="",c=!1,l=!1){return s(this,null,function*(){let p=I.uuid();o.debug("Conversation: start",{conversationId:p,opponentIds:e,opponentType:t,direction:i});let f=r.includes(le.VIDEO),A=yield this._api.startConversation(p,e,t,f,n,c,l);o.debug("Api.startConversation",A),yield this._getConversationParams(A.id);let M=yield this._connectSignaling(Ne.START,A);return yield this._setConversation(A,M,i),M})}_joinConversation(e){return s(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n}=e;o.debug("Conversation: join",{conversationId:t,joinLink:n});let c=i.includes(le.VIDEO),l;if(t)l=yield this._api.joinConversation(t,c,r);else if(n)l=yield this._api.joinConversationByLink(n,c);else throw new N(b.UNKNOWN_ERROR);o.debug("Api.joinConversation",l),yield this._getConversationParams(l.id);let p=yield this._connectSignaling(Ne.JOIN,l);return yield this._setConversation(l,p,Be.JOINING),p})}_prepareConversation(r){return s(this,arguments,function*(e,t=z.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i}),yield this._getConversationParams(e);let n=this._api.getUserId();if(!n)throw new N(b.UNKNOWN_ERROR);let c={id:e,peerId:i,endpoint:`${d.wssBase}?userId=${n}&entityType=${t}&conversationId=${e}&token=${d.wssToken}`,is_concurrent:!1,p2p_forbidden:!1},l=yield this._connectSignaling(Ne.ACCEPT,c);return B._current&&(B._current._participantState===H.ACCEPTED||B._current._participantState===H.CALLED)?(o.log("Push rejected (busy)"),u.log(g.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(b.BUSY),Promise.reject({hangup:b.BUSY})):(B._current&&(B._current.destroy(),B._current=null),yield this._setConversation(c,l,Be.INCOMING,t),l)})}_createParticipant(e){return s(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:ve(),participantState:{},state:H.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);return e.externalId?this._api.cacheExternalId(t.id,e.externalId):t.externalId=yield this._getUserId(t.id),t})}_getUserId(e){return s(this,null,function*(){try{return yield this._api.userId(e)}catch(t){throw this._close(new N(b.NETWORK_ERROR),t),t}})}_setConversation(n,c,l){return s(this,arguments,function*(e,t,i,r=z.USER){let p=t.conversation.participants.map(j=>j.id);yield this._api.prepareUserIds(p);let f=this._api.getUserId();if(!f){let j=(t.conversation.participants||[]).find(ae=>I.comparePeerId(ae.peerId,t.peerId));if(!j)throw new N(b.UNKNOWN_ERROR);f=Number(j.id),j.idType&&(r=j.idType),this._api.setUserId(f)}let A=I.composeId(f,r),M=yield this._getUserId(A);this._conversation={userId:f,compositeUserId:A,externalId:M,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||W.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)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),u.log(g.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new N(b.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||W.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 bi;return this.subscribe(e,ne.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,ne.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new yt(e),e}_connectSignaling(e,t){return s(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,Se.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,Se.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return s(this,null,function*(){if(!!this._conversation)for(let t of e){let i=I.composeParticipantId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),v.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===H.HUNGUP||t.state===H.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],b.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&ie.fromSignaling(t.externalId),mediaSettings:ve(t.mediaSettings),participantState:I.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?q.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),v.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(kt.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Yi(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new qt,this.subscribe(this._transport,S.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,S.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,S.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,S.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,S.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,S.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,S.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,S.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,S.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,S.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,S.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,S.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Be.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===H.ACCEPTED||t.state===H.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new Qi(this._transport),this.subscribe(this._volumesDetector,Ge.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new zi(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,lt.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Jt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new zt(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(g.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===H.CALLED||e.state===H.ACCEPTED||this._state===J.CLOSE||!this._participants[e.id]||(t===b.HUNGUP?this._setParticipantsStatus([e],q.HANGUP):this._setParticipantsStatus([e],q.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:Ie.CAMERA,stopStream:!0}]),delete this._participants[e.id],v.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 s(this,null,function*(){o.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===H.ACCEPTED||r.state===H.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&&ie.fromSignaling(t.externalId),mediaSettings:ve(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],q.WAITING),i?(r.state=H.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=H.CALLED,this._transport.allocate(r.id,!0),u.log(g.ADD_PARTICIPANT))})}_onRemoveParticipant(e){o.debug(`Remove participant [${e}]`);let t=this._participants[e];if(!t){o.warn(`Participant [${e}] isn't in conversation`);return}this._transport&&this._transport.close(t.id),u.log(g.REMOVE_PARTICIPANT)}changeDevice(e){return s(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new yt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(re.UNKNOWN)})}toggleScreenCapturing(e){return s(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(re.UNKNOWN)})}setVideoStream(e,t=!1){return s(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return s(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return s(this,null,function*(){if(this._mediaSource)return u.log(g.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return s(this,null,function*(){if(this._mediaSource)return u.log(g.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return s(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:ie.fromId(r.uid),c=ie.toString(n);i[c]=r.priority}for(let r of Object.values(this._participants)){let n=ie.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return s(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)})}updateDisplayLayout(e){return s(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:ie.fromId(r.uid),c=ie.toString(n),l=this._api.getCachedOkIdByExternalId(n);if(!l){o.log(`Unknown participant external ID ${c}`);continue}let p=Ye({participantId:l,mediaType:r.mediaType,streamName:r.streamName}),f=this._participants[l];f&&(f.lastRequestedLayouts[p]=r),B._isStopStreaming(r)?this._streamIdByStreamDescription.has(p)&&!this._cooldownTimestampByStreamDescription.has(p)&&this._cooldownTimestampByStreamDescription.set(p,Date.now()):(this._cooldownTimestampByStreamDescription.delete(p),!this._streamIdByStreamDescription.has(p)&&d.videoTracksCount>0&&this._streamIdByStreamDescription.set(p,null),t[p]=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=Rt(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Ie.STREAM||i.mediaType===Ie.SCREEN)?v.onRemoteLive(r.externalId,i.streamName,null):v.onRemoteStream(r.externalId,null),u.log(g.PAT_DEALLOCATED)):o.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return s(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 c=Rt(r),l=this._participants[c.participantId];if(l){let p;typeof n!="number"?(o.warn(`Unexpected error code ${n} received for participant ${c.participantId}`),p=ur.UNKNOWN_ERROR):p=mr(n),i.push({externalId:l.externalId,errorReason:p})}}if(i&&i.length)throw new Xt("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 c=r[0];this._stopStreaming(c),e[c]=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),e.keyFrame&&(t!==""&&(t+=":"),t+="kf"),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 s(this,null,function*(){o.log("Promoted in waiting hall",!e.demote),e.demote?(o.log("Kicked from waiting hall"),this._close(new N(b.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return s(this,arguments,function*(e,t=0,i=[]){o.log(`Chat room updated: ${e}`);let n=[],c=[];i.length&&(i.forEach(l=>{if(l.externalId){let p=ie.fromSignaling(l.externalId);n.push(p),this._api.cacheExternalId(l.id.id,p)}else c.push(I.decomposeId(l.id.id).id)}),c.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(c))),v.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var l,p;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===Ie.SCREEN)return;let i=Ye(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(g.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,c=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(c<=0){this._streamWaitTimerByStreamDescription.delete(i);let f=t.participantId,A=this._participants[f];if(!A){u.log(g.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${f}`);return}let M=this._streamByStreamId.get(n);if(!M){u.log(g.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}u.log(g.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let j=(l=e.participantStreamDescription)==null?void 0:l.mediaType;if(j===Ie.STREAM||j===Ie.MOVIE)((p=e.participantStreamDescription)==null?void 0:p.streamName)&&v.onRemoteLive(A.externalId,e.participantStreamDescription.streamName,M);else{let ae=(d.producerScreenTrack?null:A.secondStream)||M;v.onRemoteStream(A.externalId,ae)}}else{o.debug(`Waiting for ${c} until stream ${n} for ${i} is switched`);let f=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),c);this._streamWaitTimerByStreamDescription.set(i,f)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Ye(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Ye(i)))return i}else{let i={participantId:t,mediaType:Ie.CAMERA};if(this._streamIdByStreamDescription.has(Ye(i)))return i;let r={participantId:t,mediaType:Ie.SCREEN};if(this._streamIdByStreamDescription.has(Ye(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,[je.ADMIN,je.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!I.includesOneOf(this._conversation.roles,[je.ADMIN,je.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return s(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return s(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return s(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return s(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return s(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=pr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return s(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Wr(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let c=n.participants||[],l=[],p=[],f=null;return c.length&&(c.forEach(A=>{if(A.externalId){let M=ie.fromSignaling(A.externalId);l.push(M),this._api.cacheExternalId(A.id.id,M)}else p.push(I.decomposeId(A.id.id).id)}),p.length&&!l.length&&(l=yield this._api.getExternalIdsByOkIds(p)),n.hasMore&&(f=Hr(c[c.length-1].id))),{participants:l,pageMarker:f,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return s(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return s(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return s(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 s(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return s(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 s(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 s(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 s(this,null,function*(){var l;let n={movieId:e,participantId:(l=this._conversation)==null?void 0:l.compositeUserId};(t||t===0)&&(n.gain=t),i&&(n.offset=i),typeof r!==void 0&&(n.pause=r);let c=yield this._signaling.updateMovie(n);if(c.error)throw new Error(c.error)})}removeMovie(e){return s(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 s(this,null,function*(){let c={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},l=yield this._signaling.startStream(c);return l.error?Promise.reject(l.message):l})}stopStream(){return s(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return s(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return s(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return s(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 s(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return s(this,null,function*(){var t;!this._conversation||(o.debug("Local media stream changed",e.mediaSettings),v.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return s(this,null,function*(){var t;if(o.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;v.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(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===J.ACTIVE&&v.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===J.ACTIVE&&(d.participantStateMapped?v.onRemoteParticipantState(i.externalId,i.participantState):v.onRemoteParticipantState(i.externalId,I.mapLegacyParticipantState(i.participantState))))}_onSignalingNotification(e){switch(e.notification){case w.ACCEPTED_CALL:return this._onAcceptedCall(e);case w.HUNGUP:return this._onHungup(e);case w.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case w.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case w.CLOSED_CONVERSATION:return this._onClosedConversation(e);case w.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case w.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case w.RATE_CALL_DATA:return this._onNeedRate();case w.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case w.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case w.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case w.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case w.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case w.REGISTERED_PEER:return this._onPeerRegistered(e);case w.SWITCH_MICRO:return this._onMicSwitched(e);case w.CHAT_MESSAGE:return this._onChatMessage(e);case w.CUSTOM_DATA:return this._onCustomData(e);case w.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case w.RECORD_STOPPED:return this._onRecordInfo(null);case w.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case w.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case w.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case w.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case w.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case w.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case w.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return s(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 c=I.composeParticipantId(n),l=n.roles||[];if(c===this._conversation.compositeUserId){t=ve(n.mediaSettings),St(this._conversation.roles,l)||this._onRolesChanged(c,l);continue}r.push(c);let p=this._participants[c];if(!p)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let f=ve(n.mediaSettings);Er(f,p.mediaSettings)||this._changeRemoteMediaSettings(c,f);let A=I.mapParticipantState(n),M=p.participantState;I.isEqualParticipantState(A,M)||this._changeRemoteParticipantState(c,A),St(l,p.roles)||this._onRolesChanged(p.id,l)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],b.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 s(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 N(b.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:ve(e.mediaSettings)}),r=this._participants[t]),r.state=H.ACCEPTED,r.mediaSettings=ve(e.mediaSettings),this._logWithMediaSettings(g.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Be.OUTGOING&&(this._state===J.IDLE||this._state===J.PROCESSING)&&(this._state=J.ACTIVE,this._changeFeatureSet()),this._state===J.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 N(e.reason));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===b.REJECTED?H.REJECTED:H.HUNGUP,this._state!==J.CLOSE&&this._removeParticipant(i,b.HUNGUP)}_onAddedParticipant(e){return s(this,null,function*(){var r,n;o.debug(`Participant added [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state!==H.HUNGUP&&i.state!==H.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&&ie.fromSignaling(e.participant.externalId),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:I.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=H.CALLED,i.mediaSettings=ve((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=I.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],q.WAITING),this._state===J.ACTIVE&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onJoinedParticipant(e){return s(this,null,function*(){var r;o.debug(`Participant joined [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state===H.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&&ie.fromSignaling(e.participant.externalId),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:I.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Be.OUTGOING&&(this._state===J.IDLE||this._state===J.PROCESSING)&&(this._state=J.ACTIVE,this._changeFeatureSet()),i.state=H.ACCEPTED,i.mediaSettings=ve(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],q.CONNECTED):this._setParticipantsStatus([i],q.WAITING),this._state===J.ACTIVE&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id])),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new N(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=I.composeMessageId(e);this._changeRemoteMediaSettings(t,ve(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(),v.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return s(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ve(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=Ki(this._serverSettings,t),this._signalingServerSettings=Gr(this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){let t=this._serverSettings.camera,i=this._signalingServerSettings.camera;if(!t||!i)return;let r=Math.min(Math.round(e.quality.maxBitrate/1024),i.maxBitrateK),n=Math.min(e.quality.maxDimension,i.maxDimension),c={camera:Object.assign({},t,{maxBitrateK:r,maxDimension:n}),screenSharing:null};this._serverSettings=Ki(this._serverSettings,c),o.log("Got video quality update notification",this._serverSettings),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 s(this,null,function*(){v.onDeviceSwitched(le.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return s(this,null,function*(){let t=I.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),v.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return s(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._getUserId(t),v.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return s(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._getUserId(e.initiator);v.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else v.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!St(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,v.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!St(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,v.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return s(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],c=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 l=this._participants[e.participantId];l&&(o.debug(`Mute states for participant [${e.participantId}] changed`,i),v.onMuteStates(i,r,n,e.muteAll,e.unmute,l.externalId,c==null?void 0:c.externalId));return}I.isObjectsEquals(this._conversation.muteStates,i)&&I.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,c)))})}_processMuteState(){return s(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==H.ACCEPTED)return;let c=Object.assign({},this._conversation.muteStates),l=this._conversation.unmuteOptions,p=this._mediaSource.getMediaSettings(),f=Object.entries(c);for(let[A,M]of f)if(!(M!==Fe.MUTE&&M!==Fe.MUTE_PERMANENT)&&(this._isCallAdmin()&&M===Fe.MUTE_PERMANENT&&(c[A]=Fe.MUTE),!(!e.includes(A)||i)))switch(A){case le.VIDEO:p.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(v.onDeviceSwitched(le.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case le.AUDIO:p.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(v.onDeviceSwitched(le.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case le.SCREEN_SHARING:p.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(v.onDeviceSwitched(le.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}v.onMuteStates(c,l,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]?v.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&v.onLocalPin(!0)),this._participants[e]?v.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&v.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!lr(this._conversation.options,e)&&(this._conversation.options=e,v.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,v.onLocalNetworkStatusChanged(r);else{let c=this._participants[i];c.networkRating=r,t.push({uid:c.externalId,rating:r})}}if(t.length===0)return;o.log("Received network status update: ",e),v.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){v.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 c=this._streamByStreamId.get(n);if(!c){u.log(g.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}v.onRemoteStream(i.externalId,i.secondStream||c)}else{let r=t||i.remoteStream;r&&v.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===W.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state===J.ACTIVE,t=this._conversation.features.includes(dr.ADD_PARTICIPANT);v.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&v.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})}v.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(v.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return s(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===k.CONNECTED?i=q.CONNECTED:t===k.CONNECTING||t===k.OPENED?i=q.CONNECTING:t===k.RECONNECTING&&(i=q.RECONNECT),!i)return;let r=e.reduce((n,c)=>{if(c in this._participants){let l=this._participants[c];n.push(l),t===k.CONNECTED&&(l.remoteStream||(l.mediaSettings&&this._changeRemoteMediaSettings(c,l.mediaSettings),this._changeRemoteParticipantState(c,l.participantState)),this._updateDisplayLayoutFromCache(c))}else o.warn(`Participant [${c}] isn't in conversation`);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return s(this,null,function*(){o.debug(`Local transport state has changed: ${e}`),e===k.CONNECTED&&v.onLocalStatus(q.CONNECTED),e===k.CONNECTING&&v.onLocalStatus(q.CONNECTING),e===k.RECONNECTING&&v.onLocalStatus(q.RECONNECT),e===k.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(b.FAILED)),this._close(new N(b.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return s(this,null,function*(){if(e.endsWith(Oe.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(Oe.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],q.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(v.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===K.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;v.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 K.audio:this._removeAudioTrack(e,t,i);break;case K.video:case K.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Oe.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,q.RECONNECT),i.length&&this._setParticipantsStatus(i,q.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let c=this._participants[n];c&&!this._remoteAllStalled&&i.push(c)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let c=this._participants[n];c&&!this._remoteAllStalled&&r.push(c)}),i.length&&this._setParticipantsStatus(i,q.RECONNECT),r.length&&this._setParticipantsStatus(r,q.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!==J.CLOSE||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),v.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return s(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==W.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,c)=>(c.status!==t&&(c.status=t,d.batchParticipantsOnStart?n.push(c.externalId):v.onParticipantStatus(c.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&v.onRemoteStatus(r,t,i)}},x=B;x._delayedHangup=!1;var Xt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Xt.prototype),this.participantErrors=t}};function $r(){if(!d.apiAppId||!d.apiKey)throw new N(re.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function Xi(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Jr(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${d.apiEnv.api}fb.do`,r)}function qr(i){return s(this,arguments,function*(a,e={},t=!1){let r=Jr(a,e,t);return en(r)})}function en(a){return s(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${d.apiEnv.api}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 Jr(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=d.apiKey),t||(te.sessionKey?e.session_key=te.sessionKey:te.accessToken&&(e.access_token=te.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 Xe;(function(n){n[n.VCHAT_SERVICE_DISABLED=1101]="VCHAT_SERVICE_DISABLED",n[n.TARGET_USER_UNAVAILABLE=1102]="TARGET_USER_UNAVAILABLE",n[n.FRIENDSHIP_REQUIRED=1103]="FRIENDSHIP_REQUIRED",n[n.VCHAT_YOULA_API_ERROR=1104]="VCHAT_YOULA_API_ERROR",n[n.VCHAT_VK_API_ERROR=1106]="VCHAT_VK_API_ERROR"})(Xe||(Xe={}));var pt;(function(r){r[r.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",r[r.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",r[r.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",r[r.AUTH_LOGIN=401]="AUTH_LOGIN"})(pt||(pt={}));var tn=10,rn=700,an=3e3,Dt=class extends Ze{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return s(this,arguments,function*(e,t={},i=!1){let n=c=>s(this,null,function*(){try{return yield qr(e,t,i)}catch(l){if(!l.hasOwnProperty("error_msg")&&(c++,o.debug(`${e} network error, attempt ${c}...`),c<tn))return yield I.delay(Math.min(c*rn,an)),n(c);throw o.warn(e,"error",l),l}});return n(0)})}_call(r){return s(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){o.warn("Api call error",n);let c=re.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:c=b.SERVICE_DISABLED;break;case 1102:c=b.CALLEE_IS_OFFLINE;break;case 1103:c=b.NOT_FRIENDS;break;case 1104:case 1106:c=b.EXTERNAL_API_ERROR;break}throw new N(c,{message:n.error_msg,code:n.error_code})}})}userId(e){return s(this,null,function*(){let t=I.decomposeId(e).id;return te.isEmpty()?ie.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),ie.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return s(this,null,function*(){te.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return s(this,null,function*(){if(!this._uuid){let t=He.get("uuid");t||(t=I.uuid(),He.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)),te.sessionKey=t.session_key,te.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&v.onTokenExpired(),new N(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})};Xi("log.externalLog",t)}init(){$r()}joinConversation(e,t=!1,i){return s(this,null,function*(){let r={conversationId:e,isVideo:t};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return s(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="",c=!1,l=!1){return s(this,null,function*(){let p={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case we.USER:p.uids=t.join(",");break;case we.GROUP:p.gid=t[0];break;case we.CHAT:p.chatId=t[0];break}return c&&(p.createJoinLink=!0),n&&(p.payload=n),d.domain&&(p.domainId=d.domain),l&&(p.requireAuthToJoin=!0),this._startConversation(p)})}_startConversation(e){return s(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return s(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return s(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return s(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){return s(this,null,function*(){let i={joinLink:e,isVideo:t};return d.anonymToken&&(i.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return s(this,null,function*(){let t=ie.fromIds(e),i=[],r={methods:[]},n=[],c=Object.keys(this._externalUidsCache),l=Object.values(this._externalUidsCache);for(let f of t){let A=ie.toString(f),M=l.indexOf(A);M>-1?i.push(Number(c[M])):(n.push(A),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:f.id,anonym:f.type===Re.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((f,A)=>{if(f.ok){let M=Number(f.ok.ok_id);this._externalUidsCache[M]=n[A],i.push(M)}}),i})}getExternalIdsByOkIds(e){return s(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(ie.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(ie.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=ie.toString(e),n=i.indexOf(r);return n>-1?I.composeId(t[n],z.USER):null}cacheExternalId(e,t){let i=I.decomposeId(e).id;this._externalUidsCache[i]=ie.toString(t)}getConversationParams(e){return s(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:b.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),Xi("vchat.hangupConversation",t)}removeHistoryRecords(e){return s(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return s(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]=ie.fromIdToString(n,Re.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=ie.fromIdToString(n,Re.ANONYM);return t}catch(i){return t}})}getTokenForAnonym(e,t){return s(this,null,function*(){let i={id:e};return t&&(i.application_key=t),(yield this._callUnsafe("auth.getTokenForAnonym",i,!0)).token})}call(i){return s(this,arguments,function*(e,t={}){return this._call(e,t)})}};var Zi;(function(_){_.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"})(Zi||(Zi={}));var G=Zi;var Yr="open",Qr=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0],nn=10,Pe=class extends tt{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="+Pe._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<Qr.length;t++)Qr[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 s(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){u.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 s(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=I.decomposeId(t.participantId);t=Object.assign({},t,{participantId:n.id,participantType:n.type})}return this._sendRaw(e,t,i)})}_sendRaw(r){return s(this,arguments,function*(e,t={},i=0){let n=c=>{var p;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(c),((p=this.producerCommandDataChannel)==null?void 0:p.readyState)===Yr&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){u.log(g.SOCKET_ACTION,"not_opened"),o.warn("Socket not opened"),c.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(u.log(g.SOCKET_ACTION,"invalid_state"),o.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(c),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((c,l)=>{let p=(A,M=!1)=>{!i||M?l(A):(o.debug("Resending a signaling message",e,f.sequence),i--,n(f))},f={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:c,reject:p};n(f)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return s(this,null,function*(){return this._send(G.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return s(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return s(this,null,function*(){return this._send(G.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return s(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return s(this,null,function*(){return this._send(G.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return s(this,null,function*(){return this._send(G.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},nn)})}changeParticipantState(e){return s(this,null,function*(){return this._send(G.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return s(this,null,function*(){return this._send(G.ADD_PARTICIPANT,or({participantId:e},t))})}removeParticipant(e,t=!1){return s(this,null,function*(){return this._send(G.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return s(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(G.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return s(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(G.ACCEPT_PRODUCER,i)})}changePriorities(e){return s(this,null,function*(){return this._send(G.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return s(this,null,function*(){return this._send(G.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return s(this,null,function*(){return this._send(G.ADD_MOVIE,e)})}updateMovie(e){return s(this,null,function*(){return this._send(G.UPDATE_MOVIE,e)})}removeMovie(e){return s(this,null,function*(){return this._send(G.REMOVE_MOVIE,e)})}startStream(e){return s(this,null,function*(){return this._send(G.RECORD_START,e)})}stopStream(){return s(this,null,function*(){return this._send(G.RECORD_STOP)})}recordSetRole(e,t){return s(this,null,function*(){return this._send(G.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return s(this,null,function*(){return this._send(G.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return s(this,null,function*(){return this._send(G.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return s(this,null,function*(){return this._send(G.REQUEST_REALLOC)})}reportPerfStat(e){return s(this,null,function*(){return this._send(G.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return s(this,null,function*(){return this._send(G.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return s(this,null,function*(){return this._send(G.CHAT_HISTORY,{count:e})})}customData(e,t){return s(this,null,function*(){return this._send(G.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return s(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(G.GRANT_ROLES,r)})}muteParticipant(e,t,i){return s(this,null,function*(){return this._sendRaw(G.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return s(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(G.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return s(this,null,function*(){return this._send(G.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return s(this,null,function*(){return this._send(G.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return s(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(G.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return s(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(G.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"),u.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){u.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(Se.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Se.NOTIFICATION,{type:"notification",notification:w.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(Se.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(u.log(g.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(u.log(g.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new N(b.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(Se.NOTIFICATION,{notification:w.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 N(re.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(u.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(Se.FAILED,e)}_onError(e){u.log(g.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){u.log(g.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Pe.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(Pe.RECONNECT_MAX_DELAY,Pe.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),u.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],u.log(g.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Pe.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)!==Yr){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}Pe._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Pe.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),Pe.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(n))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new N(re.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Pe.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)},Pe.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},De=Pe;De.RECONNECT_DELAY=d.signalingReconnectDelay,De.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,De.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,De.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,De.WAIT_RESPONSE_DELAY=d.waitResponseDelay,De.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var er;(function(t){t.KING="KING",t.PAWN="PAWN"})(er||(er={}));var zr=er;var ut,se,Mt=null,sn={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 Xr(a){se=a}function Zr(a){ut=a}function on(a){Mt=a}function cn(a){d.videoEffects=a}function dn(a){return s(this,null,function*(){if(d.set(a),y.browserName()==="Sferum"&&(d.platform=`SFERUM:${y.browserVersion()}`),se||Xr(new Dt),ut||Zr(()=>new De),d.debug&&(tr.default.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${d.sdkVersion}`,a),yield y.init(),!y.isBrowserSupported())throw new N(re.UNSUPPORTED);se.init()})}function ln(n){return s(this,arguments,function*(a,e=[le.AUDIO],t="",i=!1,r=!1){let c=[],l=[];if(Array.isArray(a)?c=a.length?a:[]:a&&(c=[a]),c.length&&(l=yield se.getOkIdsByExternalIds(c),!l.length))throw new N(b.CALLEE_IS_OFFLINE);return ea(l,we.USER,e,t,i,r)})}function ea(c){return s(this,arguments,function*(a,e=we.USER,t,i="",r=!1,n=!1){if(x.current())throw o.error("There is already active call"),new N(b.FAILED);return new x(se,ut(),Mt).onStart(a,e,t,i,r,n)})}function pn(a){return s(this,null,function*(){return ta(a)})}function ta(i){return s(this,arguments,function*(a,e=z.USER,t){if(a===x.id())throw new Error("Push has already been processed");return new x(se,ut(),Mt).onPush(a,e,t)})}function un(a,e){return s(this,null,function*(){return se.getTokenForAnonym(a,e)})}function mn(t){return s(this,arguments,function*(a,e={}){return se.call(a,e)})}function hn(a){return s(this,null,function*(){return a&&(d.authToken=a),se.authorize()})}function _n(){return s(this,arguments,function*(a=[le.AUDIO]){let e=x.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function gn(){return s(this,null,function*(){let a=x.current();if(a)return a.decline()})}function fn(t){return s(this,arguments,function*(a,e=[le.AUDIO]){return ia(a,e)})}function ia(a,e,t){return s(this,null,function*(){if(x.current())throw o.error("There is already active call"),new N(b.FAILED);return new x(se,ut(),Mt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function Sn(i){return s(this,arguments,function*(a,e=[le.AUDIO],t){if(x.current())throw o.error("There is already active call"),new N(b.FAILED);return t&&(d.anonymToken=t),new x(se,ut(),Mt).onJoin({joinLink:a,mediaOptions:e})})}function vn(){return s(this,null,function*(){let a=x.current();if(a)return a.hangup();x.hangupAfterInit()})}function En(a,e){return s(this,null,function*(){let t=yield se.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return ra(t[0],e)})}function ra(a,e){return s(this,null,function*(){let t=x.current();t&&(yield t.addParticipant(I.composeId(a,z.USER),e))})}function In(a,e=!1){return s(this,null,function*(){let t=yield se.getOkIdsByExternalIds([a]);return aa(t[0],e)})}function aa(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.removeParticipant(I.composeId(a,z.USER),e))})}function Cn(a,e){return s(this,null,function*(){let t=yield y.saveDeviceId(a,e),i=x.current();return t&&i?i.changeDevice(a):Promise.reject()})}function Tn(a){return s(this,null,function*(){let e=x.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function Rn(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.setVideoStream(a,e))})}function yn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalVideo(a))})}function Pn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalAudio(a))})}function bn(a,e,t){return s(this,null,function*(){let i=x.current();if(i)return i.setLocalResolution(a,e,t)})}function An(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changePriorities(a))})}function On(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changeParticipantState(a))})}function Dn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.updateDisplayLayout(a))})}function Mn(a,e,t=!1){return s(this,null,function*(){let i=yield se.getOkIdsByExternalIds([a]);return na(i[0],e,t)})}function na(a,e,t=!1){return s(this,null,function*(){let i=x.current();i&&(yield i.grantRoles(I.composeId(a,z.USER),e,t))})}function kn(){return s(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield se.getOkIdsByExternalIds([a]))[0]),sa(i,e,t)})}function sa(){return s(this,arguments,function*(a=null,e,t=[]){let i=x.current();if(i){let r=a?I.composeId(a,z.USER):null;yield i.muteParticipant(r,e,t)}})}function wn(a,e=!1){return s(this,null,function*(){let t=yield se.getOkIdsByExternalIds([a]);return oa(t[0],e)})}function oa(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.pinParticipant(I.composeId(a,z.USER),e))})}function Nn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.updateMediaModifiers(a))})}function xn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changeOptions(a))})}function Ln(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield se.getOkIdsByExternalIds([e]))[0]),ca(a,t)})}function ca(a,e=null){return s(this,null,function*(){let t=x.current();if(t){let i=e?I.composeId(e,z.USER):null;yield t.chatMessage(a,i)}})}function Un(a=10){return s(this,null,function*(){let e=x.current();if(e)return e.chatHistory(a)})}function Vn(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield se.getOkIdsByExternalIds([e]))[0]),da(a,t)})}function da(a,e=null){return s(this,null,function*(){let t=x.current();if(t){let i=e?I.composeId(e,z.USER):null;yield t.customData(a,i)}})}function Bn(a="",e=!1){return s(this,null,function*(){return(yield se.createConversation(I.uuid(),a,e)).join_link})}function Fn(){return s(this,null,function*(){let a=x.current();return a?a.createJoinLink():Promise.reject()})}function Gn(){return s(this,null,function*(){let a=x.current();return a?a.removeJoinLink():Promise.reject()})}function Hn(a,e){return s(this,null,function*(){return se.getAnonymTokenByLink(a,e)})}function Wn(a){let e=x.current();e&&e.setVolume(a)}function jn(a){d.forceRelayPolicy=a}function Kn(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return s(this,null,function*(){let n=x.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function $n(){return s(this,null,function*(){let a=x.current();return a?a.stopStream():Promise.reject()})}function qn(a,e){return s(this,null,function*(){let t=x.current();if(t){let i=yield se.getOkIdsByExternalIds([a]);return t.recordSetRole(I.composeId(i[0],z.USER),e)}return Promise.reject()})}function Jn(){return s(this,null,function*(){let a=x.current();return a?a.getStreamInfo():Promise.reject()})}function Yn(a){return s(this,null,function*(){let e=x.current();return e?e.addMovie(a):Promise.reject()})}function Qn(a,e,t,i){return s(this,null,function*(){let r=x.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function zn(a){return s(this,null,function*(){let e=x.current();return e?e.removeMovie(a):Promise.reject()})}function Xn(a){d.statisticsInterval=a;let e=x.current();if(e)return e.updateStatisticsInterval()}function Zn(a){tr.default.disableLog(!a),o.toggle(a)}function es(a,...e){!d.debugLog||o.send(a,"[external]",...e)}function ts(a){return s(this,null,function*(){let e=x.current();if(e)return e.videoEffect(a)})}function is(a){return s(this,null,function*(){let e=x.current();e&&(yield e.setAudioStream(a))})}function rs(a=null,e,t=!1){return s(this,null,function*(){let i=x.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(a,e,t)})}function as(a,e=!1){return s(this,null,function*(){let t=x.current();if(!t)throw new Error("Conversation not found");let i=yield se.getOkIdsByExternalIds([a]);return t.promoteParticipant(I.composeId(i[0],z.USER),e)})}function ns(a){return s(this,null,function*(){yield se.removeHistoryRecords(a)})}
7
+ var ha=Object.create;var ht=Object.defineProperty;var ga=Object.getOwnPropertyDescriptor;var _a=Object.getOwnPropertyNames,Vi=Object.getOwnPropertySymbols,fa=Object.getPrototypeOf,Fi=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable;var Hi=Math.pow,Gi=(a,e,t)=>e in a?ht(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,Wi=(a,e)=>{for(var t in e||(e={}))Fi.call(e,t)&&Gi(a,t,e[t]);if(Vi)for(var t of Vi(e))Sa.call(e,t)&&Gi(a,t,e[t]);return a};var ji=a=>ht(a,"__esModule",{value:!0});var va=(a,e)=>{ji(a);for(var t in e)ht(a,t,{get:e[t],enumerable:!0})},Ea=(a,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _a(e))!Fi.call(a,i)&&i!=="default"&&ht(a,i,{get:()=>e[i],enumerable:!(t=ga(e,i))||t.enumerable});return a},He=a=>Ea(ji(ht(a!=null?ha(fa(a)):{},"default",a&&a.__esModule&&"default"in a?{get:()=>a.default,enumerable:!0}:{value:a,enumerable:!0})),a);var s=(a,e,t)=>new Promise((i,r)=>{var n=l=>{try{p(t.next(l))}catch(m){r(m)}},c=l=>{try{p(t.throw(l))}catch(m){r(m)}},p=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,c);p((t=t.apply(a,e)).next())});va(exports,{Api:()=>Mt,BaseApi:()=>et,BaseLogger:()=>tt,BaseSignaling:()=>it,CallDirection:()=>Ue,CallType:()=>Oe,ChatRoomEventType:()=>Dt,ConversationOption:()=>Ot,DebugMessageType:()=>yi,ExternalIdType:()=>Je,FacingMode:()=>Si,FatalError:()=>te,HangupReason:()=>k,HangupType:()=>y,MediaOption:()=>oe,MediaTrackKind:()=>de,MediaType:()=>fe,MuteState:()=>Be,ParticipantState:()=>W,ParticipantStatus:()=>$,RecordRole:()=>ea,Signaling:()=>Me,SignalingCommandType:()=>H,SignalingConnectionType:()=>ke,SignalingNotification:()=>O,UserRole:()=>Ge,UserType:()=>Y,Utils:()=>S,acceptCall:()=>In,addMovie:()=>rs,addParticipant:()=>Mn,addParticipantInternal:()=>sa,apiCall:()=>Tn,authorize:()=>Cn,browser:()=>hn,callInternal:()=>ra,callTo:()=>Sn,captureScreen:()=>On,changeConversationOptions:()=>Wn,changeDevice:()=>Dn,changeParticipantState:()=>Un,changePriorities:()=>Ln,changeVideoEffect:()=>ds,chatHistory:()=>Kn,chatMessage:()=>jn,chatMessageInternal:()=>la,createJoinLink:()=>Jn,customData:()=>$n,customDataInternal:()=>ua,debug:()=>os,debugMessage:()=>cs,declineCall:()=>yn,forceRelayPolicy:()=>Xn,getAnonymTokenByLink:()=>zn,getStreamInfo:()=>is,getTokenForAnonym:()=>En,getWaitingHall:()=>ls,grantRoles:()=>Vn,grantRolesInternal:()=>ca,hangup:()=>Pn,init:()=>fn,joinCall:()=>Rn,joinCallByLink:()=>bn,joinCallInternal:()=>na,muteParticipant:()=>Fn,muteParticipantInternal:()=>da,pinParticipant:()=>Hn,pinParticipantInternal:()=>pa,processPush:()=>vn,processPushInternal:()=>aa,promoteParticipant:()=>us,recordSetRole:()=>ts,removeHistoryRecords:()=>ms,removeJoinLink:()=>Yn,removeMovie:()=>ns,removeParticipant:()=>An,removeParticipantInternal:()=>oa,setApi:()=>ta,setAudioStream:()=>ps,setLocalResolution:()=>xn,setLogger:()=>gn,setMediaModifiers:()=>Gn,setSignalingFactory:()=>ia,setStatisticsInterval:()=>ss,setVideoEffects:()=>_n,setVideoStream:()=>kn,setVolume:()=>Qn,startConversation:()=>qn,startStream:()=>Zn,stopStream:()=>es,toggleLocalAudio:()=>Nn,toggleLocalVideo:()=>wn,updateDisplayLayout:()=>Bn,updateMovie:()=>as});var Li=He(require("webrtc-adapter"));var et=class{createJoinLink(e){return s(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return s(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return s(this,null,function*(){return""})}log(e){}prepareUserIds(e){return s(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return s(this,null,function*(){})}cleanup(){}getTokenForAnonym(e,t){return s(this,null,function*(){return""})}call(i){return s(this,arguments,function*(e,t={}){return null})}};var tt=class{log(e,t,i=!1){}destroy(){}};var J=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 it=class extends J{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var Ki=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(Ki||{}),Ue=Ki;var $i=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))($i||{}),Oe=$i;var qi=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(qi||{}),Dt=qi;var Ji=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(Ji||{}),Yi=Ji;var zi=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(zi||{}),Ot=zi;function Qi(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function Xi(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 Zi=(F=>(F.CAMERA_PERMISSION="camera",F.MIC_PERMISSION="mic",F.CAMERA_ACCESS="cameralock",F.MIC_ACCESS="miclock",F.MIC_NOT_FOUND="nomic",F.SCREEN_PERMISSION="screenpermission",F.SCREEN_ACCESS="screenlock",F.CONNECTION="connection",F.NETWORK="network",F.UNKNOWN="unknown",F.UNSUPPORTED="unsupported",F.SIGNALING_FAILED="signalingfailed",F.API="api",F.AUTH="auth",F))(Zi||{}),te=Zi;var er=(G=>(G.CANCELED="CANCELED",G.REJECTED="REJECTED",G.REMOVED="REMOVED",G.HUNGUP="HUNGUP",G.MISSED="MISSED",G.BUSY="BUSY",G.FAILED="FAILED",G.NETWORK_ERROR="NETWORK_ERROR",G.KILLED="KILLED",G.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",G.NOT_FRIENDS="NOT_FRIENDS",G.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",G.UNKNOWN_ERROR="UNKNOWN_ERROR",G.UNSUPPORTED="UNSUPPORTED",G.OLD_VERSION="OLD_VERSION",G.SERVICE_DISABLED="SERVICE_DISABLED",G.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",G.SOCKET_CLOSED="SOCKET_CLOSED",G.ENDED="ENDED",G))(er||{}),y=er;var tr=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(tr||{}),oe=tr;var ir=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(ir||{}),Be=ir;var rr=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(rr||{}),W=rr;var ar=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(ar||{}),ke=ar;var nr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(nr||{}),me=nr;var sr=(M=>(M.TRANSMITTED_DATA="transmitted-data",M.ACCEPTED_CALL="accepted-call",M.HUNGUP="hungup",M.PARTICIPANT_ADDED="participant-added",M.PARTICIPANT_JOINED="participant-joined",M.CLOSED_CONVERSATION="closed-conversation",M.MEDIA_SETTINGS_CHANGED="media-settings-changed",M.PARTICIPANT_STATE_CHANGED="participant-state-changed",M.RATE_CALL_DATA="rate-call-data",M.FEATURE_SET_CHANGED="feature-set-changed",M.TOPOLOGY_CHANGED="topology-changed",M.PRODUCER_UPDATED="producer-updated",M.CONSUMER_ANSWERED="consumer-answered",M.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",M.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",M.SETTINGS_UPDATE="settings-update",M.VIDEO_QUALITY_UPDATE="video-quality-update",M.REGISTERED_PEER="registered-peer",M.SWITCH_MICRO="switch-micro",M.RECORD_STARTED="record-started",M.RECORD_STOPPED="record-stopped",M.REALLOC_CON="realloc-con",M.AUDIO_ACTIVITY="audio-activity",M.SPEAKER_CHANGED="speaker-changed",M.STALLED_ACTIVITY="stalled-activity",M.CHAT_MESSAGE="chat-message",M.CUSTOM_DATA="custom-data",M.ROLES_CHANGED="roles-changed",M.MUTE_PARTICIPANT="mute-participant",M.PIN_PARTICIPANT="pin-participant",M.OPTIONS_CHANGED="options-changed",M.NETWORK_STATUS="network-status",M.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",M.PROMOTE_PARTICIPANT="promote-participant",M.CHAT_ROOM_UPDATED="chat-room-updated",M.PROMOTION_APPROVED="promotion-approved",M.JOIN_LINK_CHANGED="join-link-changed",M))(sr||{}),O=sr;var or=(I=>(I.ERROR="callError",I.DEVICES="callDevices",I.CALL_SPEC_ERROR="callSpecError",I.ICE_CONNECTION_STATE="callIceConnectionState",I.ICE_CONNECTION_TYPE="callIceConnectionType",I.ICE_RESTART="callIceRestart",I.PUSH="callPush",I.OUTGOING_CALL="callStart",I.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",I.JOIN_CONVERSATION="callJoinConversation",I.ACCEPTED_OUTGOING="callAcceptedOutgoing",I.ACCEPT_INCOMING="callAcceptIncoming",I.DECLINE_INCOMING="callDeclineIncoming",I.ACCEPT_CONCURRENT="callAcceptConcurrent",I.HANGUP="callHangup",I.MEDIA_STATUS="callMediaStatus",I.DEVICE_CHANGED="callDeviceChanged",I.SOCKET_ACTION="callSocketAction",I.ADD_PARTICIPANT="callAddParticipant",I.REMOVE_PARTICIPANT="callRemoveParticipant",I.POOR_CONNECTION="callPoorConnection",I.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",I.RELAY_POLICY="callForceRelay",I.PAT_ALLOCATED="patAllocate",I.PAT_DEALLOCATED="patDeallocate",I.PAT_ERROR="patError",I.PAT_WAITING_TIME_ERROR="patWaitingTimeError",I.PAT_OUTDATED_RESPONSE="patOutdatedResponse",I))(or||{}),h=or;var cr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(cr||{}),be=cr;var dr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(dr||{}),pr=dr;function lr(a){switch(a){case 1:return"no-available-tracks";default:return"unknown-error"}}var ur=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(ur||{}),Ge=ur;function gt(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var mr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(mr||{}),Y=mr;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 hr=2*1024*1024,Ta=512*1024,_t=100*1024,Ca=5,Zt="_okcls_logs_session_",Ia=3e4,gr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=hr;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){Sr(t);continue}let r=fr(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(_t)}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&&(Sr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>hr||this.length>Ca-1||this.size+e>this.available);)this.deleteOldestItem()}};function _r(){return`${Zt}${Date.now()}`}function fr(a){return new Blob([a]).size}function Sr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function ei(){let a=We.toString();if(!_e.available||!a)return;let e=fr(a);_e.cleanup(e);try{window.localStorage.setItem(kt,a)}catch(t){if(console.warn("Failed to write log to storage",t),_e.storageSize=_e.size+e,_e.cleanup(_t+e),_e.available>=_t+e){ei();return}if(e>_t){We.bisect(),ei();return}_e.storageSize=0;return}e>Ta&&(_e.add(kt,e),kt=_r(),We.clear(),_e.cleanup(_t))}function ti(){!_e.available||!We.length||ei()}function ya(a=!1){let e=[];try{let r=window.localStorage;for(let c of _e.items){let p=r.getItem(c.key);e.push(p)}let n=We.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 Ra(t,i),i}function Ra(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 vr(a,e){!_e.available||(We.push({t:Date.now(),l:a,d:e}),ri||(ri=window.setTimeout(()=>{ri=null,ti()},Ia)))}function ii(){_e||(_e=new gr,We=new Xt,kt=_r(),window.addEventListener("beforeunload",ti))}var _e,We,kt,ri=null;window.__VKCallsSDKLogs__=(a=!1)=>(_e||ii(),ti(),ya(a));var ai=He(require("@vkontakte/libvpx"));var he=(c=>(c.INIT="init",c.READY="ready",c.FRAME="frame",c.ERROR="error",c.DEBUG="debug",c.LOG_ERROR="log_error",c))(he||{});var u=class extends tt{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={type:1,time:0,operation:e,timestamp:Date.now(),custom:{},uid:this._api.getUserId()};typeof t!="undefined"&&(r.custom.param=t),this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch(),this._externalLogger&&this._externalLogger.log(e,t,i)}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 destroy(){u._instance&&u._instance.destroy(),u._instance=null}};var we=class{constructor(){this._worker=null}_createWorker(c,p){return s(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((l,m)=>{let R=i.join(","),D=new Blob([e,`exports.default(${R});`],{type:"application/javascript; charset=utf-8"}),j=window.URL.createObjectURL(D);this._worker=new Worker(j),this._worker.onmessage=ie=>{switch(ie.data.type){case he.READY:l();break;case he.ERROR:m(ie.data.error);break;case he.FRAME:t(ie.data);break;case he.DEBUG:o.debug(ie.data.message);break;case he.LOG_ERROR:u.log(h.ERROR,ie.data.message);break}},this._sendToWorker(he.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 rt=class extends we{init(e){return s(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)},[ai.default,ai.default.getUrl])})}decodeFrame(e,t,i,r){let n="ImageBitmap"in window;this._sendToWorker(he.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 je=class extends we{init(e){return s(this,null,function*(){o.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var i=Object.defineProperty;var f=e=>i(e,"__esModule",{value:!0});var E=(e,d)=>{f(e);for(var a in d)i(e,a,{get:d[a],enumerable:!0})};var g={};E(g,{default:()=>V});var s=(a=>(a.VP9="vp09.00.50.08",a.VP8="vp8",a))(s||{}),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 V=()=>{let e=null,d=!0;function a(){self.postMessage({type:o.READY})}function l(r,p,t,m=!1){(!e||d!==t)&&(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:c=>{("createImageBitmap"in c?c.createImageBitmap():createImageBitmap(c)).then(n=>{self.postMessage({type:o.FRAME,data:n}),n.close()}).finally(()=>c.close())},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:t?s.VP9:s.VP8}));let u=new EncodedVideoChunk({type:m?"key":"delta",timestamp:r,data:p});e.decode(u)}self.onmessage=r=>{switch(r.data.type){case o.INIT:a();break;case o.FRAME:l(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(he.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 ni="_okcls_",at=(()=>{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 Pa(a){let e=at?at.getItem(ni+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function Ma(a,e){try{at&&at.setItem(ni+a,JSON.stringify(e))}catch(t){}}function Aa(a){at&&at.removeItem(ni+a)}var si;(i=>{function a(r){return Pa(r)||null}i.get=a;function e(r,n){Ma(r,n)}i.set=e;function t(r){Aa(r)}i.remove=t})(si||(si={}));var Ve=si;var nt=He(require("big-integer"));function Er(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 ge(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}var Tr=a=>a.stop(),Cr=a=>a.getTracks().forEach(Tr),oi=a=>a.getVideoTracks().forEach(Tr),Ir=a=>a.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(y).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 Se=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(Se||{}),de=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(de||{}),ci=class extends J{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=ge();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return s(this,arguments,function*(e=[oe.AUDIO]){if(this._stream)return;let t=e.includes(oe.VIDEO),i=e.includes(oe.AUDIO);if(!T.isBrowserSupported())throw new k(te.UNSUPPORTED);try{this._stream=yield T.getUserMedia(t,i),this._mediaSettings.isVideoEnabled=t&&this._stream.getVideoTracks().filter(r=>r.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=i&&this._stream.getAudioTracks().filter(r=>r.enabled).length>0||!1}catch(r){throw new k(r)}})}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=!1){let i=this.getStream(),r=this._getSendAudioTrack(),n=this.getSendVideoTrack(t);if(!i||!r&&!n)throw new Error("No local stream found");r&&e.addTrack(r,i),n&&e.addTrack(n,i)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return s(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return s(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=S.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);navigator.mediaDevices.addEventListener("devicechange",()=>s(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),c=n&&n.groupId,p=this._stream.getVideoTracks()[0],l=p&&p.enabled&&p.getSettings(),m=l&&l.groupId;if(!c&&!m)return;let R=yield navigator.mediaDevices.enumerateDevices();!e&&c&&(e=!R.find(D=>D.groupId===c)),!t&&m&&(t=!R.find(D=>D.groupId===m)),i()}))}_changeVideoInput(e=null){return s(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield T.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"),u.log(h.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 u.log(h.ERROR,"change_video"),o.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=Ir(e)),t=this._trackVideoStreamBackup.clone(),oi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),oi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return s(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return s(this,null,function*(){try{if(e=e||(yield T.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),u.log(h.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(h.ERROR,"change_audio"),o.error("Microphone change failed",t),t}})}_changeScreen(e){return s(this,null,function*(){try{if(e=e||(yield T.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(h.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?T.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(h.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 s(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 s(this,null,function*(){if(!d.videoEffects)return t;try{return u.log(h.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(){d.videoEffects&&(this._effect=null,d.videoEffects.destroy()),this._stream&&(Cr(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return s(this,null,function*(){return e?this._changeScreen():d.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return s(this,null,function*(){if(!this._stream)return;d.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield T.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=T.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 s(this,null,function*(){if(!this._stream)return;let t;e?t=(yield T.getUserAudio()).getAudioTracks()[0]:t=T.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 s(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 s(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 s(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 di;(Bi=>{function a(v,C,b,I,A=!1){let Te=/[\r\n]+/,z=`\r
8
+ `;if(!C&&!b&&!I)return A?N(v.split(Te)).join(z):v;function N(q){let De=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],le="a=rtcp-fb:111",ae=q.findIndex(X=>X.startsWith(le));return~ae&&(q[ae]=q[ae]+z+De.join(z)),q}function Q(q,De,le){let ae=q.split(" "),X=ae.slice(0,3),ce;for(ce=3;ce<ae.length;ce++)le.includes(ae[ce])&&X.push(ae[ce]);for(ce=3;ce<ae.length;ce++)!le.includes(ae[ce])&&!De.includes(ae[ce])&&X.push(ae[ce]);return X.join(" ")}function P(q,De){let le=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),ae,X=[];for(ae=0;ae<q.length;++ae){let ce=q[ae].match(le);ce&&ce.length===3&&ce[2]===De&&X.push(ce[1])}return X}function K(q,De,le,ae){let X,ce="m="+De;for(X=0;X<q.length;++X)if(q[X].startsWith(ce)){q[X]=Q(q[X],le,ae);break}}let se=[],M=v.split(Te);(b||C)&&(se=P(M,"H264"));let Le=[];if(I&&(Le=P(M,"VP9")),b){let q=se.slice(0),De=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),le;for(le=0;le<M.length;++le){let X=M[le].match(De);X&&X.length===3&&q.includes(X[2])&&q.push(X[1])}let ae=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(le=M.length;le--;){let X=M[le].match(ae);X&&X.length===3&&q.includes(X[2])&&M.splice(le,1)}K(M,"video",q,[])}else C&&K(M,"video",[],se);return I&&K(M,"video",[],Le),A&&N(M),M.join(z)}Bi.patchSDP=a;function e(v){return v?`${v.type||"WEB_SOCKET"}_${v.id}`:"_"}Bi.getPeerIdString=e;function t(v,C){return v&&v.id===C.id&&(v.type||"WEB_SOCKET")===(C.type||"WEB_SOCKET")}Bi.comparePeerId=t;function i(v){return s(this,null,function*(){return!v||!v.getStats?Promise.resolve(null):v.getStats(null).then(C=>{let b=null,I=null;if(C.forEach(A=>{A.type==="transport"&&A.selectedCandidatePairId?I=C.get(A.selectedCandidatePairId):A.type==="candidate-pair"&&A.state==="succeeded"&&!I&&(!A.hasOwnProperty("selected")||A.selected)&&(I=A)}),I&&I.localCandidateId){let A=C.get(I.localCandidateId);A&&(b={type:A.candidateType,ip:A.ip||A.ipAddress,port:A.port||A.portNumber})}return b}).catch(()=>null)})}Bi.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function c(v,C){let b=String(v);return n.test(b)?(o.warn(`Already composite id [${v}] type supplied [${C}]`),b):C===Y.GROUP?"g"+b:C===Y.USER?"u"+b:(o.warn(`Unknown type [${C}] for id [${v}]`),b.match(r)?"u"+b:b)}Bi.composeId=c;function p(v){return c(v.id,v.idType||Y.USER)}Bi.composeParticipantId=p;function l(v){return v.participant?p(v.participant):c(v.participantId,v.participantType||Y.USER)}Bi.composeMessageId=l;function m(v){let C=String(v),b=C.match(n);return b?{id:Number(b[2]),type:b[1]==="g"?Y.GROUP:Y.USER}:(o.warn(`Unsupported compositeId [${v}]`),{id:Number(C),type:Y.USER})}Bi.decomposeId=m;function R(){let v="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),C=new Array(36),b=0,I,A;for(A=0;A<36;A++)A===8||A===13||A===18||A===23?C[A]="-":A===14?C[A]="4":(b<=2&&(b=33554432+Math.random()*16777216|0),I=b&15,b=b>>4,C[A]=v[A===19?I&3|8:I]);return C.join("")}Bi.uuid=R;function D(v,C){let b;function I(){let A=this,Te=arguments;b&&window.clearTimeout(b),b=window.setTimeout(()=>{v.apply(A,Te)},C)}return I}Bi.throttle=D;function j(v){let C="",b=v.split(`
9
+ `);for(let z of b)if(z.startsWith("a=fingerprint")){let N=z.split(" ");if(N.length===2){C=N[1];break}}if(!C)return nt.default.minusOne;let I=C.split(":"),A=nt.default.zero;for(let z=Math.min(7,I.length-1);z>=0;z--){let N=(0,nt.default)(I[z],16);A=A.shiftLeft(8).or(N)}return((z,N)=>{let Q=N.value;if(typeof Q=="bigint")return(0,nt.default)(BigInt.asIntN(z,Q));let P=nt.default.one.shiftLeft(z),K=N.and(P.subtract(1));return K.greaterOrEquals(P.subtract(K))?K.subtract(P):K})(64,A)}Bi.sdpFingerprint=j;function ie(v){return s(this,null,function*(){return new Promise(C=>window.setTimeout(C,v))})}Bi.delay=ie;function F(v,C,b){let I=[];return v.getSenders().forEach(A=>ue(C,A,A.track,b,I)),I}Bi.applySettings=F;function ue(v,C,b,I,A){if(v&&b&&b.kind===de.video){let Te=b.getSettings();if(Te){let z=v.maxBitrateK?v.maxBitrateK*1024:null,N=Te.width,Q=Te.height,P=N&&Q&&v.maxDimension?Math.max(1,Math.max(N,Q)/v.maxDimension):null,K=v.maxFramerate?v.maxFramerate:null,se=v.degradationPreference?v.degradationPreference:"balanced",M=I[b.id];if(M&&M.bitrate===z&&M.scaleResolutionDownBy===P&&M.maxFramerate===K&&M.degradationPreference===se){A[b.id]=M;return}A[b.id]={bitrate:z,scaleResolutionDownBy:P,maxFramerate:K,degradationPreference:se};let Le=C.getParameters();Le.encodings||(Le.encodings=[{}]),Le.encodings.forEach(q=>{z?q.maxBitrate=z:delete q.maxBitrate,P?q.scaleResolutionDownBy=P:delete q.scaleResolutionDownBy,K?q.maxFramerate=K:delete q.maxFramerate}),Le.degradationPreference=se,C.setParameters(Le)}}}Bi.applyVideoTrackSettings=ue;function Ae(v,C){Array.isArray(C)||(C=[C]);for(let b of C)if(v.includes(b))return!0;return!1}Bi.includesOneOf=Ae;function pe(v){var C;return Object.entries(((C=v.participantState)==null?void 0:C.state)||{}).reduce((b,[I,A])=>(v.participantState&&(b[I]={ts:v.participantState.stateUpdateTs[I],state:A}),b),{})}Bi.mapParticipantState=pe;function Ze(v){return Object.entries(v).reduce((C,[b,{state:I}])=>(C[b]=I,C),{})}Bi.mapLegacyParticipantState=Ze;function G(v){return v.map(C=>{let b={uid:C.externalId,mediaSettings:C.mediaSettings,status:C.status,muteStates:C.muteStates,unmuteOptions:C.unmuteOptions};return d.participantStateMapped&&(b.participantState=C.participantState),b})}Bi.mapSharedParticipants=G;function ye(v,C){let b=Object.keys(v),I=Object.keys(C);if(b.length!==I.length)return!1;for(let A of b)if(!I.hasOwnProperty(A)||v[A].state!==C[A].state||v[A].ts!==C[A].ts)return!1;return!0}Bi.isEqualParticipantState=ye;function Re(v,C){let b=Object.keys(v),I=Object.keys(C);if(b.length!==I.length)return!1;for(let A of b)if(!C.hasOwnProperty(A)||v[A]!==C[A])return!1;return!0}Bi.isObjectsEquals=Re;function ut(v,C){if(v.length!==C.length)return!1;for(let b of v)if(C.indexOf(b)<0)return!1;return!0}Bi.isArraysEquals=ut;function Ui(v){return!Object.keys(v).length}Bi.isEmptyObject=Ui})(di||(di={}));var S=di;var Ke=null,pi=null,wt=[],Nt=[],li=[],ft=null,St=null,ui=null,mi=!1,hi=!1,xt,st,Lt,yr=!1,Rr=!1,gi=null,_i="",Ut=[],fi=null,br=navigator.appVersion,Da=navigator.appName,ve=navigator.userAgent,Si=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(Si||{}),vt=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;St&&(p=St.deviceId),typeof e=="string"&&(p=e),p&&(n.deviceId={exact:p})}let c=!1;if(t){c={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;ft&&(p=ft.deviceId),typeof t=="string"&&(p=t),p&&(c.deviceId={exact:p}),d.videoFacingMode&&(c.facingMode={exact:d.videoFacingMode})}this.audio=n,this.video=c,this.needVideo=!!c}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}},Pr=class extends vt{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 Oa(){return s(this,null,function*(){Ke=null,yield Bt()})}function ka(){Ke=null,Bt().then(()=>_.onDeviceChange())}function Bt(){return s(this,null,function*(){return Ke||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!pi&&navigator.mediaDevices.addEventListener&&(pi=S.throttle(ka,1e3),navigator.mediaDevices.addEventListener("devicechange",pi)),Ke=navigator.mediaDevices.enumerateDevices().then(a=>{wt=a.filter(r=>r.kind==="videoinput"?(r.label&&(mi=!0),!0):!1),Nt=a.filter(r=>r.kind==="audioinput"?(r.label?hi=!0:$e.isMobile()&&$e.browserName()==="Firefox"&&(hi=mi),!0):!1),li=a.filter(r=>r.kind==="audiooutput");let e=Ve.get("videoinput"),t=Ve.get("audioinput"),i=Ve.get("audiooutput");return ft=wt.find(r=>r.deviceId===e)||null,St=Nt.find(r=>r.deviceId===t)||null,ui=li.find(r=>r.deviceId===i)||null,Ke=Promise.resolve(a),a}).catch(()=>(Ke=null,[]))))})}function wa(){return s(this,null,function*(){return $e.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(yr=!0),/^a=mid:0$/m.test(t.sdp)&&(Rr=!0),a()}).catch(a)}):Promise.resolve()})}function Vt(a,e){return s(this,null,function*(){o.debug("Try to get media",a.getNative());let t=$e.hasPermissions(a.isVideo());!t&&!e&&_.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield Oa()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?te.CAMERA_PERMISSION:te.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?te.CAMERA_ACCESS:te.MIC_ACCESS;break}if(a.canSimplify())return Vt(a.simplify(),e);let r=e||te.UNKNOWN;throw _.onPermissionsError(r),r}})}function Na(a){return s(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 te.SCREEN_PERMISSION;default:throw te.SCREEN_ACCESS}}})}function vi(){return Ut.length||(Ut=(()=>{let a,e=!1,t=0,i=ve.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return a=/\brv[ :]+(\d+)/g.exec(ve),["IE",a&&a[1]||"Unknown",e,t];if(i[1]==="Safari"){if(a=ve.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(a=ve.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,a[1]];if(a=ve.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t];if(a=ve.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t];if(a=ve.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),a=ve.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t];if(a=ve.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t];if(a=ve.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t];if(a=ve.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t]}return a=ve.match(/version\/(\d+)/i),[i[2]?i[1]:Da,a&&a[1]||i[2]||br,e,t]})()),Ut}var $e;(z=>{function a(){return s(this,null,function*(){return yield wa(),Bt()})}z.init=a;function e(){return wt}z.getCameras=e;function t(){return Nt}z.getMicrophones=t;function i(){return li}z.getOutput=i;function r(){return wt.length>0}z.hasCamera=r;function n(){return Nt.length>0}z.hasMicrophone=n;function c(){return ft}z.getSavedCamera=c;function p(){return St}z.getSavedMicrophone=p;function l(){return ui}z.getSavedOutput=l;function m(){return mi}z.hasCameraPermission=m;function R(){return hi}z.hasMicrophonePermission=R;function D(N=!1){return R()?r()&&N?m():!0:!1}z.hasPermissions=D;function j(N=!1,Q=!0){return s(this,null,function*(){let P=n()&&Q,K=r()&&N,se;if(!P&&!K)se=new MediaStream;else try{se=yield Vt(new vt(P,K))}catch(M){se=new MediaStream}return se.getVideoTracks().length||se.addTrack(Ze()),se.getAudioTracks().length||se.addTrack(pe()),se})}z.getUserMedia=j;function ie(){return s(this,null,function*(){return Na(new Pr(window.screen.width,window.screen.height))})}z.getScreenMedia=ie;function F(N,Q=!1){return s(this,null,function*(){let P=Q?d.videoEffectMaxWidth:d.videoMaxWidth,K=Q?d.videoEffectMaxHeight:d.videoMaxHeight;return Vt(new vt(!1,N||!0,P,K))})}z.getUserVideo=F;function ue(N){return s(this,null,function*(){return Vt(new vt(N||!0,!1))})}z.getUserAudio=ue;function Ae(N,Q){return s(this,null,function*(){let K=(yield Bt()).find(se=>se.kind===N&&se.deviceId===Q);return K?(N==="videoinput"?ft=K:N==="audioinput"?St=K:N==="audiooutput"&&(ui=K),Ve.set(N,Q),K):null})}z.saveDeviceId=Ae;function pe(){if(!Lt||Lt.readyState==="ended"){let N=Te(),Q=N.createMediaStreamDestination(),P=N.createGain();P.gain.value=1e-5,P.connect(Q),P.connect(N.destination);let K=N.createOscillator();K.type="sine",K.frequency.value=0,K.connect(P),K.start(),Lt=Q.stream.getAudioTracks()[0]}return Object.assign(Lt.clone(),{enabled:!1})}z.getSilentMediaTrack=pe;function Ze(N=d.videoMinWidth,Q=d.videoMinHeight){return st||(st=document.createElement("canvas"),st.getContext("2d")),st.width=N,st.height=Q,(!xt||xt.readyState==="ended")&&(xt=st.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(xt.clone(),{enabled:!1})}z.getBlackMediaTrack=Ze;function G(){if(b()==="Edge"&&I()<70)return!1;try{let N=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&N.RTCPeerConnection&&N.RTCIceCandidate&&N.RTCSessionDescription&&N.HTMLCanvasElement&&N.HTMLCanvasElement.prototype.captureStream&&N.RTCRtpSender&&N.RTCRtpSender.prototype.replaceTrack&&N.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(N){return!1}}z.isBrowserSupported=G;function ye(){return!!navigator.mediaDevices.getDisplayMedia}z.isScreenCapturingSupported=ye;function Re(){return yr}z.canVP8=Re;function ut(){return Rr}z.isUnifiedPlan=ut;function Ui(){return z.browserName()==="Opera"&&z.os()==="Windows"}z.isBrokenH264=Ui;function Bi(){return!(z.baseChromeVersion()&&z.isMobile())}z.canPreferH264=Bi;function v(){return _i||(_i=(()=>{let N={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 Q in N)if(N.hasOwnProperty(Q)&&N[Q].test(ve))return Q;return"Unknown"})()),_i}z.os=v;function C(){return gi===null&&(gi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(br)),gi}z.isMobile=C;function b(){return vi()[0]}z.browserName=b;function I(){return vi()[1]}z.browserVersion=I;function A(){return vi()[3]}z.baseChromeVersion=A;function Te(){return fi||(fi=new(window.AudioContext||window.webkitAudioContext)),fi}z.getAudioContext=Te})($e||($e={}));var T=$e;var Mr=He(require("bit-buffer"));var xa=65536,qe=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)%xa!==e.sequence){o.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:n}=qe.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,c)=>n+c.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 Mr.BitStream(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),c=i.readBits(1)<<1|r;return c===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,c>=2&&i.index++,i.readBits(3)!==7?(i.index++,(c===1||c===3)&&(i.index+=3)):(c===1||c===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 Et=class extends qe{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,je.isBrowserSupported()?this._decoder=new je:this._decoder=new rt,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)&&!(T.browserName()==="Safari"&&T.browserVersion()>=15)}};var Ft=1,La=1,Ar=0,Dr=11,Or=1,kr=2,wr=4,Nr=8;function xr(a,e,t,i,r,n,c){let p=0;e&&(p|=Or),t&&(p|=kr),i&&(p|=wr),c||(p|=Nr);let l=new ArrayBuffer(Dr),m=new DataView(l);if(m.setUint8(0,Ft),m.setUint16(1,r),m.setUint32(3,a),m.setUint8(7,n?1:0),m.setUint16(8,Ar),m.setUint8(10,p),!c)return l;let R=new Uint8Array(l.byteLength+c.byteLength);return R.set(new Uint8Array(l),0),R.set(new Uint8Array(c),l.byteLength),R.buffer}function Lr(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,c=e.getUint16(8),p=e.getUint8(10),l=!!(p&Or),m=!!(p&kr),R=!!(p&wr),D=!!(p&Nr);if(t!==Ft)throw new Error(`Unexpected protocol version. Got ${t}, expected ${Ft}`);return{timestamp:r,start:l,end:m,keyframe:R,sequence:i,isVP9:n,ssrc:c,eos:D,data:a.slice(Dr)}}function Ur(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==Ft||e.getUint8(1)!==La||e.getUint16(2)!==Ar)}var g=He(require("simple-ebml-builder"));var Ua=Hi(2,15)-1,Ei=1,Ba=5,Va=5;var Ht=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=Ht._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return g.build(e[0])}else return new Uint8Array;let t=e.reduce((n,c)=>n+c.countSize(),0),i=new Uint8Array(t),r=0;for(let n of e){let c=g.build(n);i.set(c,r),r+=c.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;let e=(n=this._sourceBuffer)==null?void 0:n.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>Va&&(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}},Pe=class extends qe{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 g.element(g.ID.EBML,[g.element(g.ID.EBMLVersion,g.number(1)),g.element(g.ID.EBMLReadVersion,g.number(1)),g.element(g.ID.EBMLMaxIDLength,g.number(4)),g.element(g.ID.EBMLMaxSizeLength,g.number(8)),g.element(g.ID.DocType,g.string("webm")),g.element(g.ID.DocTypeVersion,g.number(2)),g.element(g.ID.DocTypeReadVersion,g.number(2))])}static _genSegmentHeader(e,t,i){let r=g.element(g.ID.Info,[g.element(g.ID.TimecodeScale,g.number(1e6)),g.element(g.ID.MuxingApp,g.string("vk-webm-builder")),g.element(g.ID.WritingApp,g.string("vk-webm-builder"))]),n=[g.element(g.ID.PixelWidth,g.number(e)),g.element(g.ID.PixelHeight,g.number(t))],c=g.element(g.ID.Tracks,g.element(g.ID.TrackEntry,[g.element(g.ID.TrackNumber,g.number(Ei)),g.element(g.ID.TrackUID,g.number(Ei)),g.element(g.ID.TrackType,g.number(1)),g.element(g.ID.FlagLacing,g.number(0)),g.element(g.ID.DefaultDuration,g.number(1e9)),g.element(g.ID.CodecID,g.string(`V_${i.toUpperCase()}`)),g.element(g.ID.Video,n)]));return g.unknownSizeElement(g.ID.Segment,[r,c])}static _genClusterHeader(e){return g.unknownSizeElement(g.ID.Cluster,[g.element(g.ID.Timecode,g.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new Ht(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,o.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let c=Pe._genWebmHeader();this._mediaBuffer.append(c);let p=Pe._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(p),this._mediaBuffer.cleanup()}let r=Math.round(i-this._clusterStartTime);if(r>Ua&&(this._clusterStartTime=i,r=0),r===0){o.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let c=Pe._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(c)}let n=g.element(g.ID.SimpleBlock,[g.vintEncodedNumber(Ei),g.bytes(Pe._intToU16BE(r)),g.number((e.keyframe?1:0)<<7),g.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 ot=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,c;let t=Lr(e),i=(c=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:c.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&&Pe.isBrowserSupported()?r=new Pe(i,p):r=new Et(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(je.isBrowserSupported()||rt.isBrowserSupported())&&(Et.isBrowserSupported()||Pe.isBrowserSupported())}};var Ti=He(require("@vkontakte/libvpx"));var Fa=1e3,Tt=class extends we{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 s(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(),c=()=>i(new Error("Autoplay is disabled"));n?n.catch(c):c()}})})}_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 s(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 s(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})},[Ti.default,Ti.default.getUrl],{isVP9:this.isVP9(),debug:o.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(he.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)},Fa),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 ct=class extends we{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return s(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(he.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 Ha=16*1024,Ga=11,Br=Ha-Ga,Wa=65536,Ci=0,dt=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(c=>{o.warn("sendFrame failed",c),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};ct.isBrowserSupported()?this._encoder=new ct(e,i):this._encoder=new Tt(e,i),this._datachannel.onmessage=r=>{Ur(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 c=xr(e,t,i,r,Ci,this._encoder.isVP9(),n);return Ci=(Ci+1)%Wa,c}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return s(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+Br),c=e.data.byteLength<=t+n.byteLength,p=this._wrapHeader(e.timestamp,!t,c,e.type==="key",n);this._datachannel.onbufferedamountlow=c?()=>{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}c||window.setTimeout(()=>this._sendChunk(e,t+Br,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 ct.isBrowserSupported()||Tt.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 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")&&(Z.accessToken=e.apiAuth.accessToken,Z.sessionKey=e.apiAuth.sessionKey,Z.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.4.4-dev.c28b095.0"}static get debug(){return!1}static get protocolVersion(){return 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 apiAppId(){return 42}static get apiKey(){return f._params.apiKey}static get apiEnv(){switch(f._params.apiEnv){case"TEST":return{api:"https://apitest.ok.ru/api/",connect:"https://test.ok.ru/"};case"VIDEOTEST":return{api:"https://videotestapi.ok.ru/api/",connect:"https://test.ok.ru/"};case"DEV":return{api:"https://1.api.an-eremeev.devdc.odkl.ru/api/",connect:"https://1.web.an-eremeev.devdc.odkl.ru/"};default:return{api:"https://api.ok.ru/",connect:"https://connect.ok.ru/"}}}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 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 producerNotificationDataChannel(){return f._params.producerNotificationDataChannel&&ot.isBrowserSupported()}static get producerCommandDataChannel(){return f._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return f._params.consumerScreenDataChannel&&dt.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 videoTracksCount(){return f.producerNotificationDataChannel?f._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return f._params.breakVideoPayloadTypes}static get filteredMessages(){return f._params.filteredMessages}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:"PROD",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,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,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:!1,producerScreenTrack:!1,videoTracksCount:0,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!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 B(a,...e){let t=d.get(a);t&&setTimeout(t,0,...e)}function Ne(a){return Object.assign({},a)}function pt(a){return a.slice()}var Ii;(ce=>{function a(E,x){B("onLocalStream",E,Ne(x))}ce.onLocalStream=a;function e(E,x){B("onScreenStream",E,Ne(x))}ce.onScreenStream=e;function t(E,x){B("onLocalStreamUpdate",Ne(E),x)}ce.onLocalStreamUpdate=t;function i(E){B("onLocalStatus",E)}ce.onLocalStatus=i;function r(E,x){B("onRemoteStream",E,x)}ce.onRemoteStream=r;function n(E,x,ne){B("onRemoteLive",E,x,ne)}ce.onRemoteLive=n;function c(E,x){B("onRemoteScreenStream",E,x)}ce.onRemoteScreenStream=c;function p(E,x,ne,mt){B("onConversation",E,Ne(x),Ne(ne),mt)}ce.onConversation=p;function l(E,x){B("onRemoteMediaSettings",E,Ne(x))}ce.onRemoteMediaSettings=l;function m(E,x){B("onRemoteParticipantState",E,Ne(x))}ce.onRemoteParticipantState=m;function R(E,x,ne=null){B("onRemoteStatus",E,x,ne)}ce.onRemoteStatus=R;function D(E,x,ne=null){B("onParticipantStatus",E,x,ne)}ce.onParticipantStatus=D;function j(){B("onPermissionsRequested")}ce.onPermissionsRequested=j;function ie(E){B("onPermissionsError",E)}ce.onPermissionsError=ie;function F(E){B("onRemoteRemoved",E)}ce.onRemoteRemoved=F;function ue(E,x,ne){B("onCallState",E,x,Ne(ne))}ce.onCallState=ue;function Ae(E,x){B("onDeviceSwitched",E,x)}ce.onDeviceSwitched=Ae;function pe(E,x,ne,mt=!1,zt=!1,Qt=null,ma=null){B("onMuteStates",Ne(E),pt(x),pt(ne),mt,zt,Qt,ma)}ce.onMuteStates=pe;function Ze(E,x){B("onRolesChanged",E,pt(x))}ce.onRolesChanged=Ze;function G(E){B("onLocalRolesChanged",pt(E))}ce.onLocalRolesChanged=G;function ye(E,x){B("onPinnedParticipant",E,x)}ce.onPinnedParticipant=ye;function Re(E){B("onLocalPin",E)}ce.onLocalPin=Re;function ut(E){B("onOptionsChanged",pt(E))}ce.onOptionsChanged=ut;function Ui(){B("onCallAccepted")}ce.onCallAccepted=Ui;function Bi(){B("onRateNeeded")}ce.onRateNeeded=Bi;function v(E){B("onSpeakerChanged",E)}ce.onSpeakerChanged=v;function C(E){B("onVolumesDetected",pt(E))}ce.onVolumesDetected=C;function b(E,x){B("onLocalVolume",E,x)}ce.onLocalVolume=b;function I(E,x){B("onJoinStatus",E,x)}ce.onJoinStatus=I;function A(E,x){B("onHangup",E,x)}ce.onHangup=A;function Te(E){B("onMultipartyChatCreated",Ne(E))}ce.onMultipartyChatCreated=Te;function z(){B("onDeviceChange")}ce.onDeviceChange=z;function N(E){B("onFingerprintChange",E)}ce.onFingerprintChange=N;function Q(){B("onTokenExpired")}ce.onTokenExpired=Q;function P(E,x,ne=!1){B("onChatMessage",E,x,ne)}ce.onChatMessage=P;function K(E,x,ne=!1){B("onCustomData",E,x,ne)}ce.onCustomData=K;function se(E,x,ne,mt,zt,Qt){B("onRecordStarted",E,x,ne,mt,zt,Qt)}ce.onRecordStarted=se;function M(){B("onRecordStopped")}ce.onRecordStopped=M;function Le(E){B("onLocalNetworkStatusChanged",E)}ce.onLocalNetworkStatusChanged=Le;function q(E){B("onNetworkStatusChanged",E)}ce.onNetworkStatusChanged=q;function De(E,...x){B("onDebugMessage",E,...x)}ce.onDebugMessage=De;function le(E,x){let ne=Object.assign({},E,{memory:x});B("onStatistics",ne)}ce.onStatistics=le;function ae(){B("onAutoplayError")}ce.onAutoplayError=ae;function X(E,x,ne){B("onChatRoomUpdated",E,x,ne)}ce.onChatRoomUpdated=X})(Ii||(Ii={}));var _=Ii;var yi=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(yi||{}),Ri;(G=>{let a="📞",e=(ye,...Re)=>{_.onDebugMessage(ye,...Re)},t=!1,i=(ye,Re)=>(...ut)=>{ye(...ut),vr(Re,ut)},r=console.debug.bind(console,a),n=console.log.bind(console,a),c=console.warn.bind(console,a),p=console.error.bind(console,a),l=e.bind(null,"DEBUG"),m=e.bind(null,"LOG"),R=e.bind(null,"WARN"),D=e.bind(null,"ERROR");G.debug=l,G.log=m,G.warn=R,G.error=D;function Ae(){return t}G.enabled=Ae;function pe(ye){t=ye,d.debugLog&&ii(),ye?(G.debug=d.debugLog?i(r,"DEBUG"):r,G.log=d.debugLog?i(n,"LOG"):n,G.warn=d.debugLog?i(c,"WARN"):c,G.error=d.debugLog?i(p,"ERROR"):p):(G.debug=d.debugLog?i(l,"DEBUG"):l,G.log=d.debugLog?i(m,"LOG"):m,G.warn=d.debugLog?i(R,"WARN"):R,G.error=d.debugLog?i(D,"ERROR"):D)}G.toggle=pe;function Ze(ye,...Re){switch(ye){case"DEBUG":G.debug(...Re);break;case"LOG":G.log(...Re);break;case"WARN":G.warn(...Re);break;case"ERROR":G.error(...Re);break}}G.send=Ze})(Ri||(Ri={}));var o=Ri;var Je=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(Je||{}),ee;(p=>{function a(l){return l.length?typeof l[0]=="object"?l:l.map(m=>e(m)):[]}p.fromIds=a;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 n(l){try{return JSON.parse(l)}catch(m){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}p.fromString=n;function c(l,m){return l.id===m.id&&l.type===m.type}p.compare=c})(ee||(ee={}));var fe=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(fe||{}),bi=":",Vr="s",Fr="m";function Ye(a){return a.participantId+(a.mediaType?bi+Vr+a.mediaType:"")+(a.streamName?bi+Fr+a.streamName:"")}function Ct(a){let e=a.split(bi),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i={participantId:t,mediaType:null};for(let r of e)switch(r.charAt(0)){case Vr:i.mediaType=ja(r.slice(1));break;case Fr:i.streamName=r.slice(1);break;default:throw new Error("Unexpected parameter type "+r.charAt(0)+" in stream description "+a)}return i}function ja(a){for(let e of Object.keys(fe))if(e===a)return fe[e];return null}function Pi(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 Gt(a,e){return!(!Pi(a.camera,e.camera)||!Pi(a.screenSharing,e.screenSharing))}function Mi(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function Hr(a){return{camera:Object.assign({},a.camera),screenSharing:Object.assign({},a.screenSharing)}}function Gr(a){try{return btoa(JSON.stringify(a))}catch(e){o.warn("WaitingParticipant: failed convert to string",a,e)}return null}function Wr(a){try{return JSON.parse(atob(a))}catch(e){o.warn("WaitingParticipant: failed convert from string",a,e)}return null}var It=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(h.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,u.log(h.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(h.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),u.log(h.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 Wt=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 c;if(!((c=this._output)==null?void 0:c.audioTrack))return;let e=T.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"),_.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 s(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=T.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw u.log(h.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var Ka=90,$a=3,jt=class extends J{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}),_.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>Ka?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=$a)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var qa=44100,yt=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=T.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=qa/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,c)=>n+c,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 Kt=class extends J{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&_.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,Se.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 yt("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 Ja=1e3;function xe(a,e,t=0){return e in a&&a[e]?a[e]:t}function jr(...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 Ya(a){return(e,t)=>e[a]-t[a]}function $t(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function za(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Qa(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Ai(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=Qa(t[1])?Ai(t[1]):t[1],e),{})}function Xa(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function Za(a){return s(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(Xa).then(za)})}function en(a){let e=a.filter(Fe("type","candidate-pair")).sort(Ya("priority")).find(jr(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}})),Ai(t)}function tn(a,e){let t=$t("id",a),i=a.filter(jr(Fe("type","inbound-rtp"),Fe("type","outbound-rtp")));T.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,c)=>{if(!n[c.ssrc])n[c.ssrc]=c;else{let p=Object.assign({},n[c.ssrc],c),l=n[c.ssrc].isRemote?c:n[c.ssrc];p.id=l.id,p.type=l.type,delete p.isRemote,delete p.remoteId,n[p.ssrc]=p}return n},{})));let r={};if(T.browserName()==="Safari"){let n=a.filter(Fe("type","track"));r=$t("trackIdentifier",n)}return i.map(n=>{let c=Number(n.ssrc),p=n.mediaType||n.kind,l=n.trackId,m=n.type,R=n.codecId;if(T.browserName()==="Safari"){let j=/^.+_([\d]+)$/.exec(n.id);if(j&&(c=parseInt(j[1],10)),p=n.id.indexOf("Audio")>0?"audio":"video",e[c]){let ie=p+"-"+e[c];r[ie]&&(l=r[ie].id)}}if(!m||!c||!p)return null;let D={ssrc:c,type:m,kind:p,bytesReceived:xe(n,"bytesReceived"),bytesSent:xe(n,"bytesSent"),jitter:xe(n,"jitter"),packetsLost:xe(n,"packetsLost"),packetsReceived:xe(n,"packetsReceived"),packetsSent:xe(n,"packetsSent"),fractionLost:xe(n,"fractionLost"),pliCount:xe(n,"pliCount"),firCount:xe(n,"firCount"),nackCount:xe(n,"nackCount"),userId:e[c]};if(R&&t[R]){let j=t[R];D.clockRate=j.clockRate,D.mimeType=j.mimeType}if(l&&t[l]){let j=t[l];D.frameHeight=j.frameHeight,D.frameWidth=j.frameWidth,D.framesDecoded=j.framesDecoded,D.framesReceived=j.framesReceived,D.framesDropped=j.framesDropped}return Ai(D)}).filter(n=>!!n)}function rn(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=$t("ssrc",a.rtps),i=$t("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let c=t[n],p=i[n];if(!(!c||!p)){if(c.bytesReceived&&c.bytesReceived>p.bytesReceived&&(c.bandwidth=Math.round((c.bytesReceived-p.bytesReceived)/r)),c.bytesSent&&c.bytesSent>p.bytesSent&&(c.bandwidth=Math.round((c.bytesSent-p.bytesSent)/r)),c.packetsReceived)if(c.packetsReceived>p.packetsReceived||c.packetsLost>p.packetsLost){let l=c.packetsLost-p.packetsLost,m=c.packetsReceived-p.packetsReceived;c.packetLoss=parseFloat((100*l/(l+m)).toFixed(2))}else c.packetLoss=0;c.framesDropped&&p.framesDropped&&c.framesDropped>p.framesDropped&&(c.framesDroppedDelta=parseFloat(((c.framesDropped-p.framesDropped)/r).toFixed(0)))}}),a}function Rt(i,r){return s(this,arguments,function*(a,e,t={}){let n=yield Za(a),c={timestamp:Date.now(),transport:en(n),rtps:tn(n,t)};return e?rn(c,e):(yield S.delay(Ja),Rt(a,c,t))})}var qt=.8,ze=class extends J{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=U.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.subscribe(this._signaling,me.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Se.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Se.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,!0),this._applySettings()}catch(c){u.log(h.ERROR,"addTrack-direct"),o.error("Unable to add media source tracks",c,{participantId:this._participantId}),this._failedOnCreate=c;return}this._createOffer(!1).catch(c=>{this._state===U.IDLE?this._failedOnCreate=c:this.close(c)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==U.IDLE&&e!==U.CLOSED&&e!==U.FAILED&&this._startStatInterval()}open(e=null){return s(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,!0),this._applySettings()}catch(i){u.log(h.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(U.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(L.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Gt(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(U.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(U.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,n;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=((n=e.data.sdk)==null?void 0:n.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=S.getPeerIdString(e.peerId);S.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 s(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(h.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 s(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 s(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(h.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 s(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=>s(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===U.IDLE||e===U.OPENED?this._setState(U.CONNECTING):this._setState(U.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),u.log(h.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(U.CONNECTED),this._stopReconnection(),S.getPeerConnectionHostInfo(this._pc).then(e=>{e&&u.log(h.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(U.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(Ee.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(u.log(h.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(h.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return s(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(h.ERROR,"createOffer-direct"),i}).then(i=>s(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=ze._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(h.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return s(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(h.ERROR,"createAnswer-direct"),e}).then(e=>s(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=ze._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(h.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!T.baseChromeVersion();return e.sdp=S.patchSDP(e.sdp,d.preferH264&&T.canPreferH264(),T.isBrokenH264(),d.preferVP9,t&&d.audioNack),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(h.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Rt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:Ee.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:Ee.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=pe=>pe.rtt<=this._networkLimits.goodNet.rtt&&pe.loss<=this._networkLimits.goodNet.loss,i=pe=>pe.rtt>=this._networkLimits.badNet.rtt||pe.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((pe,Ze)=>Math.max(pe,Ze.packetLoss||0),0),c={rtt:this._lastNetworkStat.rtt*(1-qt)+r*qt,loss:this._lastNetworkStat.loss*(1-qt)+n*qt},p=i(c),l=t(c),m=i(this._remoteNetworkStat),R=t(this._remoteNetworkStat),D=i(this._lastNetworkStat),j=t(this._lastNetworkStat),ue=p||m?.2:l&&R?1:0,Ae=Date.now();if((D!==p||j!==l||Ae-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},c)},null).catch(pe=>{o.warn("Unable to send [bad-net]",pe)})),ue){let pe={};pe[this._participantId]=pe[""]=ue,this._triggerEvent(L.NETWORK_STATUS,pe)}this._lastNetworkStat.rtt=c.rtt,this._lastNetworkStat.loss=c.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=S.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=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=S.applySettings(this._pc,e,this._prevConsumerSettings))}};var Kr=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Kr||{}),bt=Kr;var Qe=He(require("messagepack"));var Di=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var n,c;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let p=(0,Qe.decode)(r);return Object.entries(p).forEach(([F,ue])=>{let Ae=Ct(F);this.streamDescriptionByCompactId.set(ue,Ae)}),null;case 2:case 4:let l=(0,Qe.decode)(r),m=[];for(let F of l){let ue=this.getStreamDescription(F);ue&&m.push(ue.participantId)}return i===2?{type:"notification",notification:O.AUDIO_ACTIVITY,activeParticipants:m}:{type:"notification",notification:O.STALLED_ACTIVITY,stalledParticipants:m};case 3:let R=(0,Qe.decode)(r);return{type:"notification",notification:O.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(R))==null?void 0:n.participantId};case 5:let D=(0,Qe.decode)(r);return{type:"notification",notification:O.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:D[0],maxDimension:D[1]}};case 6:let j=(0,Qe.decode)(r),ie={};for(let[F,ue]of Object.entries(j)){let Ae=(c=this.getStreamDescription(Number(F)))==null?void 0:c.participantId;Ae&&(ie[Ae]=ue/100)}return{type:"notification",notification:O.NETWORK_STATUS,statuses:ie};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return o.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,Qe.decode)(e),i=[];for(let[r,n]of Object.entries(t)){let c=n[0],p=n[1],l=n[2],m;if(c!==null){if(m=this.getStreamDescription(c),!m){o.error(`could not uncompress participant ID ${c}`);continue}}else m=null;if(l===null){o.error("unexpected null sequenceNumber",r,n);continue}let R=be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,D=p?p>>>0:null;i.push({participantStreamDescription:m,streamId:R,rtpTimestamp:D,sequenceNumber:l})}return{type:"notification",notification:O.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var $r="videochat-epi",Pt=class extends J{constructor(e,t){super();this._previousTimestamp=0;this._signaling=t,this.subscribe(e,L.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem($r)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return s(this,null,function*(){if(!d.perfStatReportEnabled||!e.inbound||!e.inbound.rtps)return;let t=e.inbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.framesDecoded+=n.framesDecoded||0,r.framesReceived+=n.framesReceived||0),r),{framesDecoded:0,framesReceived:0}),i=Date.now();if(!(this._previousTimestamp+5e3>i)){if(t.framesDecoded)try{let r=yield this._signaling.reportPerfStat(t);localStorage.setItem($r,r.estimatedPerformanceIndex)}catch(r){}this._previousTimestamp=i}})}};var an=90,nn=4294967295,Ce=class extends J{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._reconnectionPrevented=!1;this._state=U.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,me.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Se.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Se.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,Se.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Pt(this,e),this._serverSettings=i,o.debug("ServerTransport: Created")}getState(){return this._state||U.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==U.IDLE&&e!==U.CLOSED&&e!==U.FAILED&&this._startStatInterval()}open(){if(this._isOpen){o.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(o.error("ServerTransport: Closed",e),this._setState(U.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(U.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Gt(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,Ce._closeDataChannel(this._producerNotification),Ce._closeDataChannel(this._producerCommand),Ce._closeDataChannel(this._producerScreen),Ce._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=()=>{o.debug(`[${t}] data channel opened`),r.onerror=n=>{o.error(`[${t}] data channel error`,n)},i(r)}}_openConnection(e=!1){o.debug("ServerTransport: Open single connection");let t={};T.baseChromeVersion()&&(t.sdpSemantics=Ce._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=S.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Ce._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,bt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Di,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,bt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,bt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){o.error("ServerTransport: Unable to add media source tracks",i),u.log(h.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,bt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(U.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==U.OPENED&&(this._setState(U.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)|(?:${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 dt(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 ot(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),n=e.maxDimension!==0;if(r&&!n){o.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(T.getBlackMediaTrack()).catch(p=>{o.error("Could not disable video upload",p)});return}let c=this._mediaSource.getSendVideoTrack();if(!r&&n&&c){o.log("Enabling video upload"),this._disabledSenders.delete(i);let p=i.track;p.enabled=c.enabled,i.replaceTrack(c).then(()=>p.stop()).catch(l=>{o.error("Could not enable video upload",l)})}S.applyVideoTrackSettings(e,i,c!=null?c: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 s(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Rt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(L.REMOTE_DATA_STATS,{inbound:{topology:Ee.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:Ee.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(c=>c.type==="inbound-rtp"&&c.kind==="audio"&&this._ssrcMap[c.ssrc]==="mix");if(!t)return;let i=be.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let c=t.bytesReceived-r.bytesReceived;c>=0&&c<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(L.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Pt.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:Ce._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return s(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(h.ERROR,"setRemoteDescription-single"),i}).then(()=>s(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(h.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=S.patchSDP(i.sdp,!1,T.isBrokenH264(),!1),i)).then(i=>s(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(h.ERROR,"setLocalDescription-single"),i}).then(i=>s(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(h.ERROR,"acceptProducer")}).then(()=>s(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 s(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 s(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(L.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(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(h.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===U.IDLE||i===U.OPENED?this._setState(U.CONNECTING):e.iceConnectionState==="checking"&&this._setState(U.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(U.RECONNECTING);break;case"connected":this._setState(U.CONNECTED),S.getPeerConnectionHostInfo(e).then(r=>{r&&u.log(h.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(h.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=T.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(T.browserName(),T.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return u.log(h.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(h.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 c=r[0].rtpTimestamp;if(!Number.isInteger(c))return u.log(h.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),o.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${c}`),0;let p=t-c&nn,l=Math.ceil(p/an);return Math.min(100,Math.max(0,l))}};var L=(F=>(F.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",F.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",F.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",F.REMOTE_ALL_STALL="REMOTE_ALL_STALL",F.REMOTE_DATA_STATS="REMOTE_DATA_STATS",F.STATE_CHANGED="STATE_CHANGED",F.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",F.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",F.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",F.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",F.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",F.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",F.NETWORK_STATUS="NETWORK_STATUS",F.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",F))(L||{}),U=(p=>(p.IDLE="IDLE",p.OPENED="OPENED",p.CONNECTING="CONNECTING",p.RECONNECTING="RECONNECTING",p.CONNECTED="CONNECTED",p.CLOSED="CLOSED",p.FAILED="FAILED",p))(U||{}),Ee=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(Ee||{}),Oi=class extends J{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,me.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){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){o.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){o.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(),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(h.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=i.length&&r.length?S.composeId(i[0],r[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 c=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let p=n===c;this._directTransport=this._createDirectTransport(c,p)}this._opened.indexOf(c)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new ze(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),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 Ce(this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!1),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"?(u.log(h.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(h.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Xe=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(Xe||{}),ki=class extends J{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.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===de.audio&&((r=this._detector)==null||r.destroy(),this._detector=new yt(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===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===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 wi=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(wi||{}),Ni=class extends J{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,Xe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,L.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,L.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,L.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 Jt=class extends J{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,Xe.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===U.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===U.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),u.log(h.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!==U.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),u.log(h.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(h.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var sn=1e3,on=1e4;var V=class extends J{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=W.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._signalingServerSettings={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 Wt,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),sn))}static current(){return V._current}static hangupAfterInit(){V._activationMutex&&!V._current&&(V._delayedHangup=!0)}static id(){var e,t;return((t=(e=V._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,c=!1){return s(this,null,function*(){if(V._activationMutex)throw u.log(h.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new k(y.FAILED);V._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let p=this._mediaSource.getMediaSettings();t===Oe.CHAT||e.length>1?this._logWithMediaSettings(h.OUTGOING_MULTIPARTY_CALL,p):this._logWithMediaSettings(h.OUTGOING_CALL,p);let l=yield this._startConversation(e,t,Ue.OUTGOING,i,r,n,c);if(!this._conversation)throw new k(y.UNKNOWN_ERROR);if(this._participantState=W.ACCEPTED,this._signaling.changeMediaSettings(p),yield this._registerParticipants(l.conversation.participants),this._processConnectionData(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),V._delayedHangup)throw new k(y.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let m=Object.values(this._participants),R;return d.batchParticipantsOnStart&&(R=S.mapSharedParticipants(m)),_.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),_.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,R),_.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),V._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{V._activationMutex=!1}})}onJoin(e){return s(this,null,function*(){if(V._activationMutex)throw u.log(h.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new k(y.FAILED);V._activationMutex=!0,this._state="PROCESSING";try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(h.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new k(y.UNKNOWN_ERROR);return _.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(o.log("In waiting hall"),V._current=this,V._activationMutex=!1,this._signaling.readyToSend(),_.onLocalStatus($.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw V._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return s(this,null,function*(){o.debug("Join conversation part 2"),V._activationMutex=!0;try{if(this._participantState=W.ACCEPTED,!this._conversation||!this._mediaSource)throw new k(y.UNKNOWN_ERROR);if(this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),V._delayedHangup)throw new k(y.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=S.mapSharedParticipants(t)),_.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),_.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),V._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{V._activationMutex=!1}})}onPush(r){return s(this,arguments,function*(e,t=Y.USER,i){if(V._activationMutex)throw o.warn("Conversation: there is already running activation"),new k(y.REJECTED);V._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new k(y.UNKNOWN_ERROR);if(!n.conversation.participants.find(p=>{var l;return p.state===W.CALLED&&p.id===((l=this._conversation)==null?void 0:l.userId)}))throw o.log("Push rejected (there is an active call)"),u.log(h.PUSH,"rejected"),new k(y.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),u.log(h.PUSH,"accepted"),V._current=this,V._delayedHangup)throw new k(y.CANCELED);V._activationMutex=!1}catch(n){throw V._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Ot.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>S.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return s(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new k(y.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(h.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),_.onCallAccepted(),this._state="ACTIVE",this._participantState=W.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return s(this,null,function*(){if(this._state!=="IDLE")throw u.log(h.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(y.UNKNOWN_ERROR);this._state="PROCESSING",o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(h.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=W.ACCEPTED;let i=Object.values(this._participants),r;d.batchParticipantsOnStart&&(r=S.mapSharedParticipants(i)),_.onCallAccepted(),_.onLocalStream(this._mediaSource.getStream(),t),_.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),_.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(Be.MUTE)||n.includes(Be.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 s(this,null,function*(){var e;if(this._state!=="IDLE")throw u.log(h.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(h.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=W.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(y.REJECTED)),this._close(new k(y.REJECTED))})}hangup(){return s(this,null,function*(){o.debug("Hangup");let e=this._state==="ACTIVE"?y.HUNGUP:y.CANCELED;u.log(h.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new k(e))):_.onHangup(new k(y.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return s(this,null,function*(){if(!this._signaling.ready){this._close(new k(y.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=y.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(e,n,r)})}removeParticipant(e,t=!1){return s(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){if(!this._transport)return;let i=[];for(let r of e)(r.state===W.CALLED||r.state===W.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===W.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&o.error(t,e),o.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(y.FAILED):u.log(h.ERROR,e.hangup),V._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([y.CANCELED,y.NOT_FRIENDS,y.CALLEE_IS_OFFLINE,y.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===y.REJECTED&&!e.remote){_.onHangup(e,i),this.destroy();return}if(e.hangup===y.HUNGUP&&(!e.remote||this._participantState===W.CALLED)){_.onHangup(e,i),this.destroy();return}if(e.hangup===y.MISSED&&!e.remote){_.onHangup(e,i),this.destroy();return}if(e.hangup===y.SOCKET_CLOSED&&V._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===y.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=W.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,V._current=null,V._delayedHangup=!1,_.onHangup(e||new k(y.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,V._current=null,V._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return s(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 c=r.urls.filter((p,l,m)=>m.indexOf(p)===l);c.forEach(p=>c.push(`${p}?transport=tcp`)),i.push({urls:c,username:r.username,credential:r.credential})}d.iceServers=i,d.wssBase=t.endpoint,d.wssToken=t.token,t.client_type&&(d.clientType=t.client_type)})}_startConversation(e,t,i,r,n="",c=!1,p=!1){return s(this,null,function*(){let l=S.uuid();o.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let m=r.includes(oe.VIDEO),R=yield this._api.startConversation(l,e,t,m,n,c,p);o.debug("Api.startConversation",R),yield this._getConversationParams(R.id);let D=yield this._connectSignaling(ke.START,R);return yield this._setConversation(R,D,i),D})}_joinConversation(e){return s(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n}=e;o.debug("Conversation: join",{conversationId:t,joinLink:n});let c=i.includes(oe.VIDEO),p;if(t)p=yield this._api.joinConversation(t,c,r);else if(n)p=yield this._api.joinConversationByLink(n,c);else throw new k(y.UNKNOWN_ERROR);o.debug("Api.joinConversation",p),yield this._getConversationParams(p.id);let l=yield this._connectSignaling(ke.JOIN,p);return yield this._setConversation(p,l,Ue.JOINING),l})}_prepareConversation(r){return s(this,arguments,function*(e,t=Y.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i}),yield this._getConversationParams(e);let n=this._api.getUserId();if(!n)throw new k(y.UNKNOWN_ERROR);let c={id:e,peerId:i,endpoint:`${d.wssBase}?userId=${n}&entityType=${t}&conversationId=${e}&token=${d.wssToken}`,is_concurrent:!1,p2p_forbidden:!1},p=yield this._connectSignaling(ke.ACCEPT,c);return V._current&&(V._current._participantState===W.ACCEPTED||V._current._participantState===W.CALLED)?(o.log("Push rejected (busy)"),u.log(h.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(y.BUSY),Promise.reject({hangup:y.BUSY})):(V._current&&(V._current.destroy(),V._current=null),yield this._setConversation(c,p,Ue.INCOMING,t),p)})}_createParticipant(e){return s(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:ge(),participantState:{},state:W.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);return e.externalId?this._api.cacheExternalId(t.id,e.externalId):t.externalId=yield this._getUserId(t.id),t})}_getUserId(e){return s(this,null,function*(){try{return yield this._api.userId(e)}catch(t){throw this._close(new k(y.NETWORK_ERROR),t),t}})}_setConversation(n,c,p){return s(this,arguments,function*(e,t,i,r=Y.USER){let l=t.conversation.participants.map(j=>j.id);yield this._api.prepareUserIds(l);let m=this._api.getUserId();if(!m){let j=(t.conversation.participants||[]).find(ie=>S.comparePeerId(ie.peerId,t.peerId));if(!j)throw new k(y.UNKNOWN_ERROR);m=Number(j.id),j.idType&&(r=j.idType),this._api.setUserId(m)}let R=S.composeId(m,r),D=yield this._getUserId(R);this._conversation={userId:m,compositeUserId:R,externalId:D,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||Ee.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)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),u.log(h.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new k(y.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||Ee.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 ci;return this.subscribe(e,Se.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Se.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new It(e),e}_connectSignaling(e,t){return s(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,me.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,me.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,me.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return s(this,null,function*(){if(!!this._conversation)for(let t of e){let i=S.composeParticipantId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),_.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===W.HUNGUP||t.state===W.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],y.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&ee.fromSignaling(t.externalId),mediaSettings:ge(t.mediaSettings),participantState:S.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?$.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),_.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){S.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(Dt.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Oi(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.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.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===Ue.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===W.ACCEPTED||t.state===W.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new ki(this._transport),this.subscribe(this._volumesDetector,Xe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Ni(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,wi.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Kt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Jt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=T.getCameras().length,t=T.getMicrophones().length;o.debug("Cameras: "+e+(T.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(T.hasMicrophonePermission()?"✔":"✖")),u.log(h.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===W.CALLED||e.state===W.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===y.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:fe.CAMERA,stopStream:!0}]),delete this._participants[e.id],_.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 s(this,null,function*(){o.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===W.ACCEPTED||r.state===W.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&&ee.fromSignaling(t.externalId),mediaSettings:ge(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],$.WAITING),i?(r.state=W.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=W.CALLED,this._transport.allocate(r.id,!0),u.log(h.ADD_PARTICIPANT))})}_onRemoveParticipant(e){o.debug(`Remove participant [${e}]`);let t=this._participants[e];if(!t){o.warn(`Participant [${e}] isn't in conversation`);return}this._transport&&this._transport.close(t.id),u.log(h.REMOVE_PARTICIPANT)}changeDevice(e){return s(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new It(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(te.UNKNOWN)})}toggleScreenCapturing(e){return s(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(te.UNKNOWN)})}setVideoStream(e,t=!1){return s(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return s(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return s(this,null,function*(){if(this._mediaSource)return u.log(h.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return s(this,null,function*(){if(this._mediaSource)return u.log(h.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return s(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:ee.fromId(r.uid),c=ee.toString(n);i[c]=r.priority}for(let r of Object.values(this._participants)){let n=ee.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return s(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)})}updateDisplayLayout(e){return s(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:ee.fromId(r.uid),c=ee.toString(n),p=this._api.getCachedOkIdByExternalId(n);if(!p){o.log(`Unknown participant external ID ${c}`);continue}let l=Ye({participantId:p,mediaType:r.mediaType,streamName:r.streamName}),m=this._participants[p];m&&(m.lastRequestedLayouts[l]=r),V._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]=V._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]=V._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=Ct(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===fe.STREAM||i.mediaType===fe.SCREEN)?_.onRemoteLive(r.externalId,i.streamName,null):_.onRemoteStream(r.externalId,null),u.log(h.PAT_DEALLOCATED)):o.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return s(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 c=Ct(r),p=this._participants[c.participantId];if(p){let l;typeof n!="number"?(o.warn(`Unexpected error code ${n} received for participant ${c.participantId}`),l=pr.UNKNOWN_ERROR):l=lr(n),i.push({externalId:p.externalId,errorReason:l})}}if(i&&i.length)throw new Yt("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]+on>Date.now())break;let c=r[0];this._stopStreaming(c),e[c]=V._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(V._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),e.keyFrame&&(t!==""&&(t+=":"),t+="kf"),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 s(this,null,function*(){o.log("Promoted in waiting hall",!e.demote),e.demote?(o.log("Kicked from waiting hall"),this._close(new k(y.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return s(this,arguments,function*(e,t=0,i=[]){o.log(`Chat room updated: ${e}`);let n=[],c=[];i.length&&(i.forEach(p=>{if(p.externalId){let l=ee.fromSignaling(p.externalId);n.push(l),this._api.cacheExternalId(p.id.id,l)}else c.push(S.decomposeId(p.id.id).id)}),c.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(c))),_.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var p,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===fe.SCREEN)return;let i=Ye(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(h.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,c=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(c<=0){this._streamWaitTimerByStreamDescription.delete(i);let m=t.participantId,R=this._participants[m];if(!R){u.log(h.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${m}`);return}let D=this._streamByStreamId.get(n);if(!D){u.log(h.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}u.log(h.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let j=(p=e.participantStreamDescription)==null?void 0:p.mediaType;if(j===fe.STREAM||j===fe.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&_.onRemoteLive(R.externalId,e.participantStreamDescription.streamName,D);else{let ie=(d.producerScreenTrack?null:R.secondStream)||D;_.onRemoteStream(R.externalId,ie)}}else{o.debug(`Waiting for ${c} until stream ${n} for ${i} is switched`);let m=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),c);this._streamWaitTimerByStreamDescription.set(i,m)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Ye(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Ye(i)))return i}else{let i={participantId:t,mediaType:fe.CAMERA};if(this._streamIdByStreamDescription.has(Ye(i)))return i;let r={participantId:t,mediaType:fe.SCREEN};if(this._streamIdByStreamDescription.has(Ye(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?S.includesOneOf(this._conversation.roles,[Ge.ADMIN,Ge.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!S.includesOneOf(this._conversation.roles,[Ge.ADMIN,Ge.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return s(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return s(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return s(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return s(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return s(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Xi(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return s(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Wr(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let c=n.participants||[],p=[],l=[],m=null;return c.length&&(c.forEach(R=>{if(R.externalId){let D=ee.fromSignaling(R.externalId);p.push(D),this._api.cacheExternalId(R.id.id,D)}else l.push(S.decomposeId(R.id.id).id)}),l.length&&!p.length&&(p=yield this._api.getExternalIdsByOkIds(l)),n.hasMore&&(m=Gr(c[c.length-1].id))),{participants:p,pageMarker:m,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return s(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return s(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return s(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 s(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return s(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 s(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 s(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 s(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 c=yield this._signaling.updateMovie(n);if(c.error)throw new Error(c.error)})}removeMovie(e){return s(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 s(this,null,function*(){let c={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},p=yield this._signaling.startStream(c);return p.error?Promise.reject(p.message):p})}stopStream(){return s(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return s(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return s(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return s(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 s(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return s(this,null,function*(){var t;!this._conversation||(o.debug("Local media stream changed",e.mediaSettings),_.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return s(this,null,function*(){var t;if(o.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;_.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(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"&&_.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?_.onRemoteParticipantState(i.externalId,i.participantState):_.onRemoteParticipantState(i.externalId,S.mapLegacyParticipantState(i.participantState))))}_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)}}_onSignalingReconnect(e){return s(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 c=S.composeParticipantId(n),p=n.roles||[];if(c===this._conversation.compositeUserId){t=ge(n.mediaSettings),gt(this._conversation.roles,p)||this._onRolesChanged(c,p);continue}r.push(c);let l=this._participants[c];if(!l)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let m=ge(n.mediaSettings);Er(m,l.mediaSettings)||this._changeRemoteMediaSettings(c,m);let R=S.mapParticipantState(n),D=l.participantState;S.isEqualParticipantState(R,D)||this._changeRemoteParticipantState(c,R),gt(p,l.roles)||this._onRolesChanged(l.id,p)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],y.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 s(this,null,function*(){let t=S.composeMessageId(e),i=S.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new k(y.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:ge(e.mediaSettings)}),r=this._participants[t]),r.state=W.ACCEPTED,r.mediaSettings=ge(e.mediaSettings),this._logWithMediaSettings(h.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Ue.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=S.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new k(e.reason));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===y.REJECTED?W.REJECTED:W.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,y.HUNGUP)}_onAddedParticipant(e){return s(this,null,function*(){var r,n;o.debug(`Participant added [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state!==W.HUNGUP&&i.state!==W.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&&ee.fromSignaling(e.participant.externalId),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=W.CALLED,i.mediaSettings=ge((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=S.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.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)})}_onJoinedParticipant(e){return s(this,null,function*(){var r;o.debug(`Participant joined [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state===W.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&&ee.fromSignaling(e.participant.externalId),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Ue.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=W.ACCEPTED,i.mediaSettings=ge(e.mediaSettings),i.participantState=S.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])),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new k(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=S.composeMessageId(e);this._changeRemoteMediaSettings(t,ge(e.mediaSettings))}_onParticipantStateChanged(e){let t=S.composeMessageId(e);this._changeRemoteParticipantState(t,S.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(),_.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return s(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ge(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=Mi(this._serverSettings,t),this._signalingServerSettings=Hr(this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){let t=this._serverSettings.camera,i=this._signalingServerSettings.camera;if(!t||!i)return;let r=Math.min(Math.round(e.quality.maxBitrate/1024),i.maxBitrateK),n=Math.min(e.quality.maxDimension,i.maxDimension),c={camera:Object.assign({},t,{maxBitrateK:r,maxDimension:n}),screenSharing:null};this._serverSettings=Mi(this._serverSettings,c),o.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=S.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return s(this,null,function*(){_.onDeviceSwitched(oe.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return s(this,null,function*(){let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),_.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return s(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),_.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return s(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._getUserId(e.initiator);_.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else _.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!gt(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,_.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!gt(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,_.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return s(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],c=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),_.onMuteStates(i,r,n,e.muteAll,e.unmute,p.externalId,c==null?void 0:c.externalId));return}S.isObjectsEquals(this._conversation.muteStates,i)&&S.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,c)))})}_processMuteState(){return s(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==W.ACCEPTED)return;let c=Object.assign({},this._conversation.muteStates),p=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),m=Object.entries(c);for(let[R,D]of m)if(!(D!==Be.MUTE&&D!==Be.MUTE_PERMANENT)&&(this._isCallAdmin()&&D===Be.MUTE_PERMANENT&&(c[R]=Be.MUTE),!(!e.includes(R)||i)))switch(R){case oe.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(_.onDeviceSwitched(oe.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case oe.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(_.onDeviceSwitched(oe.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case oe.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(_.onDeviceSwitched(oe.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}_.onMuteStates(c,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]?_.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&_.onLocalPin(!0)),this._participants[e]?_.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&_.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!Qi(this._conversation.options,e)&&(this._conversation.options=e,_.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,_.onLocalNetworkStatusChanged(r);else{let c=this._participants[i];c.networkRating=r,t.push({uid:c.externalId,rating:r})}}if(t.length===0)return;o.log("Received network status update: ",e),_.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){_.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 c=this._streamByStreamId.get(n);if(!c){u.log(h.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}_.onRemoteStream(i.externalId,i.secondStream||c)}else{let r=t||i.remoteStream;r&&_.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===Ee.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Yi.ADD_PARTICIPANT);_.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&_.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})}_.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(_.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return s(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===U.CONNECTED?i=$.CONNECTED:t===U.CONNECTING||t===U.OPENED?i=$.CONNECTING:t===U.RECONNECTING&&(i=$.RECONNECT),!i)return;let r=e.reduce((n,c)=>{if(c in this._participants){let p=this._participants[c];n.push(p),t===U.CONNECTED&&(p.remoteStream||(p.mediaSettings&&this._changeRemoteMediaSettings(c,p.mediaSettings),this._changeRemoteParticipantState(c,p.participantState)),this._updateDisplayLayoutFromCache(c))}else o.warn(`Participant [${c}] isn't in conversation`);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return s(this,null,function*(){o.debug(`Local transport state has changed: ${e}`),e===U.CONNECTED&&_.onLocalStatus($.CONNECTED),e===U.CONNECTING&&_.onLocalStatus($.CONNECTING),e===U.RECONNECTING&&_.onLocalStatus($.RECONNECT),e===U.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(y.FAILED)),this._close(new k(y.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return s(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],$.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(_.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),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;_.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!==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,$.RECONNECT),i.length&&this._setParticipantsStatus(i,$.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let c=this._participants[n];c&&!this._remoteAllStalled&&i.push(c)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let c=this._participants[n];c&&!this._remoteAllStalled&&r.push(c)}),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;!T.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}),_.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return s(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==Ee.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,c)=>(c.status!==t&&(c.status=t,d.batchParticipantsOnStart?n.push(c.externalId):_.onParticipantStatus(c.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&_.onRemoteStatus(r,t,i)}},w=V;w._delayedHangup=!1;var Yt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Yt.prototype),this.participantErrors=t}};function qr(){if(!d.apiAppId||!d.apiKey)throw new k(te.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function xi(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Yr(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${d.apiEnv.api}fb.do`,r)}function Jr(i){return s(this,arguments,function*(a,e={},t=!1){let r=Yr(a,e,t);return cn(r)})}function cn(a){return s(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${d.apiEnv.api}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 Yr(a,e={},t=!1){e.method=a,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,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 pn=10,ln=700,un=3e3,Mt=class extends et{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return s(this,arguments,function*(e,t={},i=!1){let n=c=>s(this,null,function*(){try{return yield Jr(e,t,i)}catch(p){if(!p.hasOwnProperty("error_msg")&&(c++,o.debug(`${e} network error, attempt ${c}...`),c<pn))return yield S.delay(Math.min(c*ln,un)),n(c);throw o.warn(e,"error",p),p}});return n(0)})}_call(r){return s(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){o.warn("Api call error",n);let c=te.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:c=y.SERVICE_DISABLED;break;case 1102:c=y.CALLEE_IS_OFFLINE;break;case 1103:c=y.NOT_FRIENDS;break;case 1104:case 1106:c=y.EXTERNAL_API_ERROR;break}throw new k(c,{message:n.error_msg,code:n.error_code})}})}userId(e){return s(this,null,function*(){let t=S.decomposeId(e).id;return Z.isEmpty()?ee.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),ee.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return s(this,null,function*(){Z.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return s(this,null,function*(){if(!this._uuid){let t=Ve.get("uuid");t||(t=S.uuid(),Ve.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&&_.onTokenExpired(),new k(te.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})};xi("log.externalLog",t)}init(){qr()}joinConversation(e,t=!1,i){return s(this,null,function*(){let r={conversationId:e,isVideo:t};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return s(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="",c=!1,p=!1){return s(this,null,function*(){let l={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case Oe.USER:l.uids=t.join(",");break;case Oe.GROUP:l.gid=t[0];break;case Oe.CHAT:l.chatId=t[0];break}return c&&(l.createJoinLink=!0),n&&(l.payload=n),d.domain&&(l.domainId=d.domain),p&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return s(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return s(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return s(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return s(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){return s(this,null,function*(){let i={joinLink:e,isVideo:t};return d.anonymToken&&(i.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return s(this,null,function*(){let t=ee.fromIds(e),i=[],r={methods:[]},n=[],c=Object.keys(this._externalUidsCache),p=Object.values(this._externalUidsCache);for(let m of t){let R=ee.toString(m),D=p.indexOf(R);D>-1?i.push(Number(c[D])):(n.push(R),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:m.id,anonym:m.type===Je.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((m,R)=>{if(m.ok){let D=Number(m.ok.ok_id);this._externalUidsCache[D]=n[R],i.push(D)}}),i})}getExternalIdsByOkIds(e){return s(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(ee.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(ee.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=ee.toString(e),n=i.indexOf(r);return n>-1?S.composeId(t[n],Y.USER):null}cacheExternalId(e,t){let i=S.decomposeId(e).id;this._externalUidsCache[i]=ee.toString(t)}getConversationParams(e){return s(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:y.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),xi("vchat.hangupConversation",t)}removeHistoryRecords(e){return s(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return s(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]=ee.fromIdToString(n,Je.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=ee.fromIdToString(n,Je.ANONYM);return t}catch(i){return t}})}getTokenForAnonym(e,t){return s(this,null,function*(){let i={id:e};return t&&(i.application_key=t),(yield this._callUnsafe("auth.getTokenForAnonym",i,!0)).token})}call(i){return s(this,arguments,function*(e,t={}){return this._call(e,t)})}};var zr=(P=>(P.RECOVER="recover",P.ACCEPT_CALL="accept-call",P.ADD_PARTICIPANT="add-participant",P.REMOVE_PARTICIPANT="remove-participant",P.HANGUP="hangup",P.TRANSMIT_DATA="transmit-data",P.ACCEPT_PRODUCER="accept-producer",P.ALLOCATE_CONSUMER="allocate-consumer",P.CHANGE_MEDIA_SETTINGS="change-media-settings",P.CHANGE_PARTICIPANT_STATE="change-participant-state",P.CHANGE_STREAM_PRIORITIES="change-streams-priorities",P.UPDATE_DISPLAY_LAYOUT="update-display-layout",P.REPORT_PERF_STAT="report-perf-stat",P.RECORD_START="record-start",P.RECORD_STOP="record-stop",P.RECORD_SET_ROLE="record-set-role",P.RECORD_GET_STATUS="record-get-status",P.SWITCH_MICRO="switch-micro",P.SWITCH_TOPOLOGY="switch-topology",P.REQUEST_REALLOC="request-realloc",P.CHAT_MESSAGE="chat-message",P.CHAT_HISTORY="chat-history",P.CUSTOM_DATA="custom-data",P.GRANT_ROLES="grant-roles",P.MUTE_PARTICIPANT="mute-participant",P.PIN_PARTICIPANT="pin-participant",P.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",P.CHANGE_OPTIONS="change-options",P.GET_WAITING_HALL="get-waiting-hall",P.PROMOTE_PARTICIPANT="promote-participant",P.REQUEST_TEST_MODE="request-test-mode",P.ADD_MOVIE="add-movie",P.UPDATE_MOVIE="update-movie",P.REMOVE_MOVIE="remove-movie",P))(zr||{}),H=zr;var Qr="open",Xr=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0],mn=10,Ie=class extends it{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="+Ie._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<Xr.length;t++)Xr[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 s(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){u.log(h.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 s(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=S.decomposeId(t.participantId);t=Object.assign({},t,{participantId:n.id,participantType:n.type})}return this._sendRaw(e,t,i)})}_sendRaw(r){return s(this,arguments,function*(e,t={},i=0){let n=c=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(c),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===Qr&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){u.log(h.SOCKET_ACTION,"not_opened"),o.warn("Socket not opened"),c.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(u.log(h.SOCKET_ACTION,"invalid_state"),o.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(c),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((c,p)=>{let l=(R,D=!1)=>{!i||D?p(R):(o.debug("Resending a signaling message",e,m.sequence),i--,n(m))},m={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:c,reject:l};n(m)})})}_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 s(this,null,function*(){return this._send(H.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return s(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return s(this,null,function*(){return this._send(H.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return s(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return s(this,null,function*(){return this._send(H.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return s(this,null,function*(){return this._send(H.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},mn)})}changeParticipantState(e){return s(this,null,function*(){return this._send(H.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return s(this,null,function*(){return this._send(H.ADD_PARTICIPANT,Wi({participantId:e},t))})}removeParticipant(e,t=!1){return s(this,null,function*(){return this._send(H.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return s(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(H.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return s(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(H.ACCEPT_PRODUCER,i)})}changePriorities(e){return s(this,null,function*(){return this._send(H.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return s(this,null,function*(){return this._send(H.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return s(this,null,function*(){return this._send(H.ADD_MOVIE,e)})}updateMovie(e){return s(this,null,function*(){return this._send(H.UPDATE_MOVIE,e)})}removeMovie(e){return s(this,null,function*(){return this._send(H.REMOVE_MOVIE,e)})}startStream(e){return s(this,null,function*(){return this._send(H.RECORD_START,e)})}stopStream(){return s(this,null,function*(){return this._send(H.RECORD_STOP)})}recordSetRole(e,t){return s(this,null,function*(){return this._send(H.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return s(this,null,function*(){return this._send(H.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return s(this,null,function*(){return this._send(H.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return s(this,null,function*(){return this._send(H.REQUEST_REALLOC)})}reportPerfStat(e){return s(this,null,function*(){return this._send(H.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return s(this,null,function*(){return this._send(H.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return s(this,null,function*(){return this._send(H.CHAT_HISTORY,{count:e})})}customData(e,t){return s(this,null,function*(){return this._send(H.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return s(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 s(this,null,function*(){return this._sendRaw(H.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return s(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(H.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return s(this,null,function*(){return this._send(H.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return s(this,null,function*(){return this._send(H.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return s(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 s(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===ke.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(h.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(h.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(me.RECONNECT,e),e.conversation.topology&&this._triggerEvent(me.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(me.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(u.log(h.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(u.log(h.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new k(y.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(me.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(te.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(u.log(h.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(me.FAILED,e)}_onError(e){u.log(h.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){u.log(h.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Ie.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(Ie.RECONNECT_MAX_DELAY,Ie.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),u.log(h.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,ke.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(h.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Ie.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}Ie._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Ie.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),Ie.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(n))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new k(te.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Ie.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(ke.RETRY)},Ie.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Me=Ie;Me.RECONNECT_DELAY=d.signalingReconnectDelay,Me.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,Me.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,Me.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,Me.WAIT_RESPONSE_DELAY=d.waitResponseDelay,Me.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var Zr=(t=>(t.KING="KING",t.PAWN="PAWN",t))(Zr||{}),ea=Zr;var lt,re,At=null,hn={getCameras:T.getCameras,getMicrophones:T.getMicrophones,getOutput:T.getOutput,hasCamera:T.hasCamera,hasMicrophone:T.hasMicrophone,getSavedCamera:T.getSavedCamera,getSavedMicrophone:T.getSavedMicrophone,getSavedOutput:T.getSavedOutput,hasCameraPermission:T.hasCameraPermission,hasMicrophonePermission:T.hasMicrophonePermission,hasPermissions:T.hasPermissions,getUserMedia:T.getUserMedia,getUserVideo:T.getUserVideo,getUserAudio:T.getUserAudio,saveDeviceId:T.saveDeviceId,isBrowserSupported:T.isBrowserSupported,isScreenCapturingSupported:T.isScreenCapturingSupported,os:T.os,isMobile:T.isMobile,browserName:T.browserName,browserVersion:T.browserVersion,baseChromeVersion:T.baseChromeVersion,getAudioContext:T.getAudioContext};function ta(a){re=a}function ia(a){lt=a}function gn(a){At=a}function _n(a){d.videoEffects=a}function fn(a){return s(this,null,function*(){if(d.set(a),T.browserName()==="Sferum"&&(d.platform=`SFERUM:${T.browserVersion()}`),re||ta(new Mt),lt||ia(()=>new Me),d.debug&&(Li.default.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${d.sdkVersion}`,a),yield T.init(),!T.isBrowserSupported())throw new k(te.UNSUPPORTED);re.init()})}function Sn(n){return s(this,arguments,function*(a,e=[oe.AUDIO],t="",i=!1,r=!1){let c=[],p=[];if(Array.isArray(a)?c=a.length?a:[]:a&&(c=[a]),c.length&&(p=yield re.getOkIdsByExternalIds(c),!p.length))throw new k(y.CALLEE_IS_OFFLINE);return ra(p,Oe.USER,e,t,i,r)})}function ra(c){return s(this,arguments,function*(a,e=Oe.USER,t,i="",r=!1,n=!1){if(w.current())throw o.error("There is already active call"),new k(y.FAILED);return new w(re,lt(),At).onStart(a,e,t,i,r,n)})}function vn(a){return s(this,null,function*(){return aa(a)})}function aa(i){return s(this,arguments,function*(a,e=Y.USER,t){if(a===w.id())throw new Error("Push has already been processed");return new w(re,lt(),At).onPush(a,e,t)})}function En(a,e){return s(this,null,function*(){return re.getTokenForAnonym(a,e)})}function Tn(t){return s(this,arguments,function*(a,e={}){return re.call(a,e)})}function Cn(a){return s(this,null,function*(){return a&&(d.authToken=a),re.authorize()})}function In(){return s(this,arguments,function*(a=[oe.AUDIO]){let e=w.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function yn(){return s(this,null,function*(){let a=w.current();if(a)return a.decline()})}function Rn(t){return s(this,arguments,function*(a,e=[oe.AUDIO]){return na(a,e)})}function na(a,e,t){return s(this,null,function*(){if(w.current())throw o.error("There is already active call"),new k(y.FAILED);return new w(re,lt(),At).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function bn(i){return s(this,arguments,function*(a,e=[oe.AUDIO],t){if(w.current())throw o.error("There is already active call"),new k(y.FAILED);return t&&(d.anonymToken=t),new w(re,lt(),At).onJoin({joinLink:a,mediaOptions:e})})}function Pn(){return s(this,null,function*(){let a=w.current();if(a)return a.hangup();w.hangupAfterInit()})}function Mn(a,e){return s(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return sa(t[0],e)})}function sa(a,e){return s(this,null,function*(){let t=w.current();t&&(yield t.addParticipant(S.composeId(a,Y.USER),e))})}function An(a,e=!1){return s(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);return oa(t[0],e)})}function oa(a,e=!1){return s(this,null,function*(){let t=w.current();t&&(yield t.removeParticipant(S.composeId(a,Y.USER),e))})}function Dn(a,e){return s(this,null,function*(){let t=yield T.saveDeviceId(a,e),i=w.current();return t&&i?i.changeDevice(a):Promise.reject()})}function On(a){return s(this,null,function*(){let e=w.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function kn(a,e=!1){return s(this,null,function*(){let t=w.current();t&&(yield t.setVideoStream(a,e))})}function wn(a){return s(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalVideo(a))})}function Nn(a){return s(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalAudio(a))})}function xn(a,e,t){return s(this,null,function*(){let i=w.current();if(i)return i.setLocalResolution(a,e,t)})}function Ln(a){return s(this,null,function*(){let e=w.current();e&&(yield e.changePriorities(a))})}function Un(a){return s(this,null,function*(){let e=w.current();e&&(yield e.changeParticipantState(a))})}function Bn(a){return s(this,null,function*(){let e=w.current();e&&(yield e.updateDisplayLayout(a))})}function Vn(a,e,t=!1){return s(this,null,function*(){let i=yield re.getOkIdsByExternalIds([a]);return ca(i[0],e,t)})}function ca(a,e,t=!1){return s(this,null,function*(){let i=w.current();i&&(yield i.grantRoles(S.composeId(a,Y.USER),e,t))})}function Fn(){return s(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield re.getOkIdsByExternalIds([a]))[0]),da(i,e,t)})}function da(){return s(this,arguments,function*(a=null,e,t=[]){let i=w.current();if(i){let r=a?S.composeId(a,Y.USER):null;yield i.muteParticipant(r,e,t)}})}function Hn(a,e=!1){return s(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);return pa(t[0],e)})}function pa(a,e=!1){return s(this,null,function*(){let t=w.current();t&&(yield t.pinParticipant(S.composeId(a,Y.USER),e))})}function Gn(a){return s(this,null,function*(){let e=w.current();e&&(yield e.updateMediaModifiers(a))})}function Wn(a){return s(this,null,function*(){let e=w.current();e&&(yield e.changeOptions(a))})}function jn(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield re.getOkIdsByExternalIds([e]))[0]),la(a,t)})}function la(a,e=null){return s(this,null,function*(){let t=w.current();if(t){let i=e?S.composeId(e,Y.USER):null;yield t.chatMessage(a,i)}})}function Kn(a=10){return s(this,null,function*(){let e=w.current();if(e)return e.chatHistory(a)})}function $n(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield re.getOkIdsByExternalIds([e]))[0]),ua(a,t)})}function ua(a,e=null){return s(this,null,function*(){let t=w.current();if(t){let i=e?S.composeId(e,Y.USER):null;yield t.customData(a,i)}})}function qn(a="",e=!1){return s(this,null,function*(){return(yield re.createConversation(S.uuid(),a,e)).join_link})}function Jn(){return s(this,null,function*(){let a=w.current();return a?a.createJoinLink():Promise.reject()})}function Yn(){return s(this,null,function*(){let a=w.current();return a?a.removeJoinLink():Promise.reject()})}function zn(a,e){return s(this,null,function*(){return re.getAnonymTokenByLink(a,e)})}function Qn(a){let e=w.current();e&&e.setVolume(a)}function Xn(a){d.forceRelayPolicy=a}function Zn(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return s(this,null,function*(){let n=w.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function es(){return s(this,null,function*(){let a=w.current();return a?a.stopStream():Promise.reject()})}function ts(a,e){return s(this,null,function*(){let t=w.current();if(t){let i=yield re.getOkIdsByExternalIds([a]);return t.recordSetRole(S.composeId(i[0],Y.USER),e)}return Promise.reject()})}function is(){return s(this,null,function*(){let a=w.current();return a?a.getStreamInfo():Promise.reject()})}function rs(a){return s(this,null,function*(){let e=w.current();return e?e.addMovie(a):Promise.reject()})}function as(a,e,t,i){return s(this,null,function*(){let r=w.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function ns(a){return s(this,null,function*(){let e=w.current();return e?e.removeMovie(a):Promise.reject()})}function ss(a){d.statisticsInterval=a;let e=w.current();if(e)return e.updateStatisticsInterval()}function os(a){Li.default.disableLog(!a),o.toggle(a)}function cs(a,...e){!d.debugLog||o.send(a,"[external]",...e)}function ds(a){return s(this,null,function*(){let e=w.current();if(e)return e.videoEffect(a)})}function ps(a){return s(this,null,function*(){let e=w.current();e&&(yield e.setAudioStream(a))})}function ls(a=null,e,t=!1){return s(this,null,function*(){let i=w.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(a,e,t)})}function us(a,e=!1){return s(this,null,function*(){let t=w.current();if(!t)throw new Error("Conversation not found");let i=yield re.getOkIdsByExternalIds([a]);return t.promoteParticipant(S.composeId(i[0],Y.USER),e)})}function ms(a){return s(this,null,function*(){yield re.removeHistoryRecords(a)})}