@vkontakte/calls-sdk 2.4.3-beta.5 → 2.4.3-beta.9

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,11 +1,11 @@
1
1
  /**
2
- * @vkontakte/calls-sdk v2.4.3-beta.5-dev
3
- * Fri, 17 Sep 2021 11:49:51 GMT
2
+ * @vkontakte/calls-sdk v2.4.3-beta.9-dev
3
+ * Wed, 06 Oct 2021 14:58:46 GMT
4
4
  */
5
5
 
6
- var ia=Object.create;var lt=Object.defineProperty;var ra=Object.getOwnPropertyDescriptor;var aa=Object.getOwnPropertyNames,Yi=Object.getOwnPropertySymbols,na=Object.getPrototypeOf,zi=Object.prototype.hasOwnProperty,sa=Object.prototype.propertyIsEnumerable;var Qi=(a,e,t)=>e in a?lt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,Xi=(a,e)=>{for(var t in e||(e={}))zi.call(e,t)&&Qi(a,t,e[t]);if(Yi)for(var t of Yi(e))sa.call(e,t)&&Qi(a,t,e[t]);return a};var Zi=a=>lt(a,"__esModule",{value:!0});var is=typeof require!="undefined"?require:a=>{throw new Error('Dynamic require of "'+a+'" is not supported')};var oa=(a,e)=>{Zi(a);for(var t in e)lt(a,t,{get:e[t],enumerable:!0})},ca=(a,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of aa(e))!zi.call(a,i)&&i!=="default"&&lt(a,i,{get:()=>e[i],enumerable:!(t=ra(e,i))||t.enumerable});return a},pt=a=>ca(Zi(lt(a!=null?ia(na(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(_){r(_)}},c=p=>{try{l(t.throw(p))}catch(_){r(_)}},l=p=>p.done?i(p.value):Promise.resolve(p.value).then(n,c);l((t=t.apply(a,e)).next())});oa(exports,{Api:()=>bt,BaseApi:()=>Ze,BaseLogger:()=>et,BaseSignaling:()=>tt,CallDirection:()=>Be,CallType:()=>xe,ChatRoomEventType:()=>Dt,ConversationOption:()=>Ot,DebugMessageType:()=>de,ExternalIdType:()=>Pe,HangupReason:()=>N,HangupType:()=>P,MediaOption:()=>ie,MediaType:()=>Ce,ParticipantState:()=>W,ParticipantStatus:()=>q,Signaling:()=>we,SignalingCommandType:()=>G,SignalingConnectionType:()=>Le,SignalingNotification:()=>w,UserRole:()=>je,UserType:()=>z,Utils:()=>C,acceptCall:()=>sn,addMovie:()=>Gn,addParticipant:()=>pn,addParticipantInternal:()=>Kr,apiCall:()=>an,authorize:()=>nn,browser:()=>za,callInternal:()=>Hr,callTo:()=>en,captureScreen:()=>mn,changeConversationOptions:()=>bn,changeDevice:()=>hn,changeParticipantState:()=>En,changePriorities:()=>vn,changeVideoEffect:()=>qn,chatHistory:()=>Dn,chatMessage:()=>An,chatMessageInternal:()=>Qr,createJoinLink:()=>wn,customData:()=>On,customDataInternal:()=>Xr,debug:()=>Kn,debugMessage:()=>$n,declineCall:()=>on,forceRelayPolicy:()=>Ln,getAnonymTokenByLink:()=>Nn,getStreamInfo:()=>Fn,getTokenForAnonym:()=>rn,getWaitingHall:()=>Yn,grantRoles:()=>Cn,grantRolesInternal:()=>qr,hangup:()=>ln,init:()=>Za,joinCall:()=>cn,joinCallByLink:()=>dn,joinCallInternal:()=>jr,muteParticipant:()=>Tn,muteParticipantInternal:()=>Jr,pinParticipant:()=>yn,pinParticipantInternal:()=>zr,processPush:()=>tn,processPushInternal:()=>Wr,promoteParticipant:()=>zn,recordSetRole:()=>Bn,removeHistoryRecords:()=>Qn,removeJoinLink:()=>kn,removeMovie:()=>Wn,removeParticipant:()=>un,removeParticipantInternal:()=>$r,setApi:()=>Fr,setAudioStream:()=>Jn,setLocalResolution:()=>Sn,setLogger:()=>Qa,setMediaModifiers:()=>Pn,setSignalingFactory:()=>Gr,setStatisticsInterval:()=>jn,setVideoEffects:()=>Xa,setVideoStream:()=>_n,setVolume:()=>xn,startConversation:()=>Mn,startStream:()=>Un,stopStream:()=>Vn,toggleLocalAudio:()=>fn,toggleLocalVideo:()=>gn,unmuteRequest:()=>Rn,unmuteRequestInternal:()=>Yr,updateDisplayLayout:()=>In,updateMovie:()=>Hn});var Ji=pt(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])setTimeout(i,0,...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 zt;(function(i){i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING"})(zt||(zt={}));var Be=zt;var Qt;(function(i){i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT"})(Qt||(Qt={}));var xe=Qt;var Xt;(function(t){t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP"})(Xt||(Xt={}));var Dt=Xt;var Zt;(function(t){t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD"})(Zt||(Zt={}));var er=Zt;var ei;(function(i){i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL"})(ei||(ei={}));var Ot=ei;function tr(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function ir(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 ti;(function(T){T.CAMERA_PERMISSION="camera",T.MIC_PERMISSION="mic",T.CAMERA_ACCESS="cameralock",T.MIC_ACCESS="miclock",T.MIC_NOT_FOUND="nomic",T.SCREEN_PERMISSION="screenpermission",T.SCREEN_ACCESS="screenlock",T.CONNECTION="connection",T.NETWORK="network",T.UNKNOWN="unknown",T.UNSUPPORTED="unsupported",T.SIGNALING_FAILED="signalingfailed",T.API="api",T.AUTH="auth"})(ti||(ti={}));var se=ti;var ii;(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"})(ii||(ii={}));var P=ii;var ri;(function(i){i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING"})(ri||(ri={}));var ie=ri;var ai;(function(i){i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT"})(ai||(ai={}));var ye=ai;var ni;(function(r){r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP"})(ni||(ni={}));var W=ni;var si;(function(r){r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry"})(si||(si={}));var Le=si;var oi;(function(i){i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT"})(oi||(oi={}));var Se=oi;var ci;(function(g){g.TRANSMITTED_DATA="transmitted-data",g.ACCEPTED_CALL="accepted-call",g.HUNGUP="hungup",g.PARTICIPANT_ADDED="participant-added",g.PARTICIPANT_JOINED="participant-joined",g.CLOSED_CONVERSATION="closed-conversation",g.MEDIA_SETTINGS_CHANGED="media-settings-changed",g.PARTICIPANT_STATE_CHANGED="participant-state-changed",g.RATE_CALL_DATA="rate-call-data",g.FEATURE_SET_CHANGED="feature-set-changed",g.TOPOLOGY_CHANGED="topology-changed",g.PRODUCER_UPDATED="producer-updated",g.CONSUMER_ANSWERED="consumer-answered",g.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",g.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",g.SETTINGS_UPDATE="settings-update",g.VIDEO_QUALITY_UPDATE="video-quality-update",g.REGISTERED_PEER="registered-peer",g.SWITCH_MICRO="switch-micro",g.RECORD_STARTED="record-started",g.RECORD_STOPPED="record-stopped",g.REALLOC_CON="realloc-con",g.AUDIO_ACTIVITY="audio-activity",g.SPEAKER_CHANGED="speaker-changed",g.STALLED_ACTIVITY="stalled-activity",g.CHAT_MESSAGE="chat-message",g.CUSTOM_DATA="custom-data",g.ROLES_CHANGED="roles-changed",g.MUTE_PARTICIPANT="mute-participant",g.PIN_PARTICIPANT="pin-participant",g.OPTIONS_CHANGED="options-changed",g.NETWORK_STATUS="network-status",g.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",g.PROMOTE_PARTICIPANT="promote-participant",g.CHAT_ROOM_UPDATED="chat-room-updated",g.PROMOTION_APPROVED="promotion-approved",g.JOIN_LINK_CHANGED="join-link-changed"})(ci||(ci={}));var w=ci;var di;(function(E){E.ERROR="callError",E.DEVICES="callDevices",E.CALL_SPEC_ERROR="callSpecError",E.ICE_CONNECTION_STATE="callIceConnectionState",E.ICE_CONNECTION_TYPE="callIceConnectionType",E.ICE_RESTART="callIceRestart",E.PUSH="callPush",E.OUTGOING_CALL="callStart",E.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",E.JOIN_CONVERSATION="callJoinConversation",E.ACCEPTED_OUTGOING="callAcceptedOutgoing",E.ACCEPT_INCOMING="callAcceptIncoming",E.DECLINE_INCOMING="callDeclineIncoming",E.ACCEPT_CONCURRENT="callAcceptConcurrent",E.HANGUP="callHangup",E.MEDIA_STATUS="callMediaStatus",E.DEVICE_CHANGED="callDeviceChanged",E.SOCKET_ACTION="callSocketAction",E.ADD_PARTICIPANT="callAddParticipant",E.REMOVE_PARTICIPANT="callRemoveParticipant",E.POOR_CONNECTION="callPoorConnection",E.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",E.RELAY_POLICY="callForceRelay",E.PAT_ALLOCATED="patAllocate",E.PAT_DEALLOCATED="patDeallocate",E.PAT_ERROR="patError",E.PAT_WAITING_TIME_ERROR="patWaitingTimeError",E.PAT_OUTDATED_RESPONSE="patOutdatedResponse"})(di||(di={}));var m=di;var li;(function(t){t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat"})(li||(li={}));var Me=li;var ut;(function(t){t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error"})(ut||(ut={}));var rr=ut;function ar(a){switch(a){case 1:return ut.NO_AVAILABLE_TRACKS;default:return ut.UNKNOWN_ERROR}}var pi;(function(t){t.CREATOR="CREATOR",t.ADMIN="ADMIN"})(pi||(pi={}));var je=pi;function ht(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var ui;(function(t){t.USER="USER",t.GROUP="GROUP"})(ui||(ui={}));var z=ui;var hi=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 nr=2*1024*1024,da=512*1024,mt=100*1024,la=5,mi="_okcls_logs_session_",pa=3e4,sr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=nr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(mi)!==0)continue;let i=e.getItem(t);if(!i){dr(t);continue}let r=cr(i);this.add(t,r)}}catch(e){console.error("Storage is blocked",e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(mt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(mi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(dr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>nr||this.length>la-1||this.size+e>this.available);)this.deleteOldestItem()}};function or(){return`${mi}${Date.now()}`}function cr(a){return new Blob([a]).size}function dr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function _i(){let a=Ke.toString();if(!Ee.available||!a)return;let e=cr(a);Ee.cleanup(e);try{window.localStorage.setItem(Mt,a)}catch(t){if(console.warn("Failed to write log to storage",t),Ee.storageSize=Ee.size+e,Ee.cleanup(mt+e),Ee.available>=mt+e){_i();return}if(e>mt){Ke.bisect(),_i();return}Ee.storageSize=0;return}e>da&&(Ee.add(Mt,e),Mt=or(),Ke.clear(),Ee.cleanup(mt))}function gi(){!Ee.available||!Ke.length||_i()}function ua(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 ha(t,i),i}function ha(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 lr(a,e){!Ee.available||(Ke.push({t:Date.now(),l:a,d:e}),Si||(Si=window.setTimeout(()=>{Si=null,gi()},pa)))}function fi(){Ee||(Ee=new sr,Ke=new hi,Mt=or(),window.addEventListener("beforeunload",gi))}var Ee,Ke,Mt,Si=null;window.__VKCallsSDKLogs__=(a=!1)=>(Ee||fi(),gi(),ua(a));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 v=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(v._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(v._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(v._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(v._params,e)}static get(e){return v._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.4.3-beta.5"}static get debug(){return!1}static get protocolVersion(){return 5}static get platform(){return v._params.platform}static set platform(e){v._params.platform=e}static get clientType(){return v._params.clientType}static set clientType(e){v._params.clientType=e}static get device(){return v._params.device}static get apiAppId(){return 42}static get apiKey(){return v._params.apiKey}static get apiEnv(){switch(v._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 v._params.authToken}static set authToken(e){v._params.authToken=e}static get anonymToken(){return v._params.anonymToken}static set anonymToken(e){v._params.anonymToken=e}static get domain(){return v._params.domain}static get iceServers(){return v._params.iceServers}static set iceServers(e){v._params.iceServers=e}static get wssBase(){return v._params.wssBase}static set wssBase(e){v._params.wssBase=e}static get wssToken(){return v._params.wssToken}static set wssToken(e){v._params.wssToken=e}static get signalingReconnectDelay(){return v._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return v._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return v._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return v._params.waitConnectionDelay}static get waitResponseDelay(){return v._params.waitResponseDelay}static get waitMessageDelay(){return v._params.waitMessageDelay}static get debugLog(){return v._params.debugLog}static get forceRelayPolicy(){return v._params.forceRelayPolicy}static set forceRelayPolicy(e){v._params.forceRelayPolicy=e}static get videoMinWidth(){return v._params.videoMinWidth}static get videoMaxWidth(){return v._params.videoMaxWidth}static set videoMaxWidth(e){v._params.videoMaxWidth=e}static get videoMinHeight(){return v._params.videoMinHeight}static get videoMaxHeight(){return v._params.videoMaxHeight}static set videoMaxHeight(e){v._params.videoMaxHeight=e}static get videoAspectRatio(){return v._params.videoAspectRatio}static get videoFrameRate(){return v._params.videoFrameRate}static get videoFacingMode(){return v._params.videoFacingMode}static get screenFrameRate(){return v._params.screenFrameRate}static get videoEffects(){return v._params.videoEffects}static set videoEffects(e){v._params.videoEffects=e}static get videoEffectMaxWidth(){return v._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){v._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return v._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){v._params.videoEffectMaxHeight=e}static get voiceParams(){return v._params.voiceParams}static get specListenerParams(){return v._params.specListenerParams}static get iceRestartWaitTime(){return v._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return v._params.transportConnectionWaitTime}static get statisticsInterval(){return v._params.statisticsInterval}static set statisticsInterval(e){v._params.statisticsInterval=e}static get networkStatisticsInterval(){return v._params.networkStatisticsInterval}static get perfStatReportEnabled(){return v._params.perfStatReportEnabled}static get producerNotificationDataChannel(){return v._params.producerNotificationDataChannel}static get producerCommandDataChannel(){return v._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return v._params.consumerScreenDataChannel}static set consumerScreenDataChannel(e){v._params.consumerScreenDataChannel=e}static get producerScreenDataChannel(){return v._params.producerScreenDataChannel&&v._params.producerNotificationDataChannel}static set producerScreenDataChannel(e){v._params.producerScreenDataChannel=e}static get noiseSuppression(){return v._params.noiseSuppression}static set noiseSuppression(e){v._params.noiseSuppression=e}static get preferH264(){return v._params.preferH264}static get preferVP9(){return v._params.preferVP9}static get audioNack(){return v._params.audioNack}static get consumerScreenTrack(){return v._params.consumerScreenTrack&&v._params.consumerScreenDataChannel}static get producerScreenTrack(){return v._params.producerScreenTrack&&v._params.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=v._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get videoTracksCount(){return v._params.videoTracksCount}static get breakVideoPayloadTypes(){return v._params.breakVideoPayloadTypes}static get filteredMessages(){return v._params.filteredMessages}static get batchParticipantsOnStart(){return v._params.batchParticipantsOnStart}static get participantStateMapped(){return v._params.participantStateMapped}},d=v;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 Ge(a){return Object.assign({},a)}function wt(a){return a.slice()}var vi;(function(ts){function a(I,U){V("onLocalStream",I,Ge(U))}ts.onLocalStream=a;function e(I,U){V("onScreenStream",I,Ge(U))}ts.onScreenStream=e;function t(I,U){V("onLocalStreamUpdate",Ge(I),U)}ts.onLocalStreamUpdate=t;function i(I){V("onLocalStatus",I)}ts.onLocalStatus=i;function r(I,U){V("onRemoteStream",I,U)}ts.onRemoteStream=r;function n(I,U,ue){V("onRemoteLive",I,U,ue)}ts.onRemoteLive=n;function c(I,U){V("onRemoteScreenStream",I,U)}ts.onRemoteScreenStream=c;function l(I,U,ue){V("onConversation",I,Ge(U),ue)}ts.onConversation=l;function p(I,U){V("onRemoteMediaSettings",I,Ge(U))}ts.onRemoteMediaSettings=p;function _(I,U){V("onRemoteParticipantState",I,Ge(U))}ts.onRemoteParticipantState=_;function b(I,U,ue=null){V("onRemoteStatus",I,U,ue)}ts.onRemoteStatus=b;function k(I,U,ue=null){V("onParticipantStatus",I,U,ue)}ts.onParticipantStatus=k;function K(){V("onPermissionsRequested")}ts.onPermissionsRequested=K;function ne(I){V("onPermissionsError",I)}ts.onPermissionsError=ne;function T(I){V("onRemoteRemoved",I)}ts.onRemoteRemoved=T;function _e(I,U,ue){V("onCallState",I,U,Ge(ue))}ts.onCallState=_e;function ke(I,U){V("onDeviceSwitched",I,U)}ts.onDeviceSwitched=ke;function he(I){V("onUnmuteRequest",I)}ts.onUnmuteRequest=he;function F(I){V("onUnmutePermission",I)}ts.onUnmutePermission=F;function le(I,U){V("onRolesChanged",I,wt(U))}ts.onRolesChanged=le;function De(I){V("onLocalRolesChanged",wt(I))}ts.onLocalRolesChanged=De;function Oe(I,U){V("onPinnedParticipant",I,U)}ts.onPinnedParticipant=Oe;function R(I){V("onLocalPin",I)}ts.onLocalPin=R;function A(I){V("onOptionsChanged",wt(I))}ts.onOptionsChanged=A;function O(){V("onCallAccepted")}ts.onCallAccepted=O;function $(){V("onRateNeeded")}ts.onRateNeeded=$;function M(I){V("onSpeakerChanged",I)}ts.onSpeakerChanged=M;function Re(I){V("onVolumesDetected",wt(I))}ts.onVolumesDetected=Re;function E(I,U){V("onLocalVolume",I,U)}ts.onLocalVolume=E;function ve(I,U){V("onJoinStatus",I,U)}ts.onJoinStatus=ve;function Ne(I,U){V("onHangup",I,U)}ts.onHangup=Ne;function ge(I){V("onMultipartyChatCreated",Ge(I))}ts.onMultipartyChatCreated=ge;function L(){V("onDeviceChange")}ts.onDeviceChange=L;function X(I){V("onFingerprintChange",I)}ts.onFingerprintChange=X;function h(){V("onTokenExpired")}ts.onTokenExpired=h;function Z(I,U,ue=!1){V("onChatMessage",I,U,ue)}ts.onChatMessage=Z;function H(I,U,ue=!1){V("onCustomData",I,U,ue)}ts.onCustomData=H;function g(I,U,ue,Zr,ea,ta){V("onRecordStarted",I,U,ue,Zr,ea,ta)}ts.onRecordStarted=g;function me(){V("onRecordStopped")}ts.onRecordStopped=me;function ce(I){V("onLocalNetworkStatusChanged",I)}ts.onLocalNetworkStatusChanged=ce;function ee(I){V("onNetworkStatusChanged",I)}ts.onNetworkStatusChanged=ee;function pe(I,...U){V("onDebugMessage",I,...U)}ts.onDebugMessage=pe;function Xn(I,U){let ue=Object.assign({},I,{memory:U});V("onStatistics",ue)}ts.onStatistics=Xn;function Zn(){V("onAutoplayError")}ts.onAutoplayError=Zn;function es(I,U,ue){V("onChatRoomUpdated",I,U,ue)}ts.onChatRoomUpdated=es})(vi||(vi={}));var S=vi;var de;(function(r){r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR"})(de||(de={}));var Ei;(function(le){let a="📞",e=(De,...Oe)=>{S.onDebugMessage(De,...Oe)},t=!1,i=(De,Oe)=>(...R)=>{De(...R),lr(Oe,R)},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,de.DEBUG),_=e.bind(null,de.LOG),b=e.bind(null,de.WARN),k=e.bind(null,de.ERROR);le.debug=p,le.log=_,le.warn=b,le.error=k;function ke(){return t}le.enabled=ke;function he(De){t=De,d.debugLog&&fi(),De?(le.debug=d.debugLog?i(r,de.DEBUG):r,le.log=d.debugLog?i(n,de.LOG):n,le.warn=d.debugLog?i(c,de.WARN):c,le.error=d.debugLog?i(l,de.ERROR):l):(le.debug=d.debugLog?i(p,de.DEBUG):p,le.log=d.debugLog?i(_,de.LOG):_,le.warn=d.debugLog?i(b,de.WARN):b,le.error=d.debugLog?i(k,de.ERROR):k)}le.toggle=he;function F(De,...Oe){switch(De){case de.DEBUG:le.debug(...Oe);break;case de.LOG:le.log(...Oe);break;case de.WARN:le.warn(...Oe);break;case de.ERROR:le.error(...Oe);break}}le.send=F})(Ei||(Ei={}));var o=Ei;var at=pt(require("big-integer"));var Ii="_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 ma(a){let e=it?it.getItem(Ii+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function _a(a,e){try{it&&it.setItem(Ii+a,JSON.stringify(e))}catch(t){}}function ga(a){it&&it.removeItem(Ii+a)}var Ci;(function(i){function a(r){return ma(r)||null}i.get=a;function e(r,n){_a(r,n)}i.set=e;function t(r){ga(r)}i.remove=t})(Ci||(Ci={}));var He=Ci;var $e=null,Ti=null,kt=[],Nt=[],Ri=[],_t=null,gt=null,yi=null,Pi=!1,bi=!1,xt,rt,Lt,pr=!1,ur=!1,Ai=null,Di="",Ut=[],Oi=null,hr=navigator.appVersion,fa=navigator.appName,Te=navigator.userAgent,mr;(function(r){r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right"})(mr||(mr={}));var ft=class{constructor(e,t=!1,i=d.videoMaxWidth,r=d.videoMaxHeight){let n=!1;if(e){n={noiseSuppression:d.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let l;gt&&(l=gt.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;_t&&(l=_t.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}},_r=class extends ft{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=d.screenFrameRate}};function Sa(){return s(this,null,function*(){$e=null,yield Vt()})}function va(){$e=null,Vt().then(()=>S.onDeviceChange())}function Vt(){return s(this,null,function*(){return $e||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Ti&&navigator.mediaDevices.addEventListener&&(Ti=C.throttle(va,1e3),navigator.mediaDevices.addEventListener("devicechange",Ti)),$e=navigator.mediaDevices.enumerateDevices().then(a=>{kt=a.filter(r=>r.kind==="videoinput"?(r.label&&(Pi=!0),!0):!1),Nt=a.filter(r=>r.kind==="audioinput"?(r.label?bi=!0:qe.isMobile()&&qe.browserName()==="Firefox"&&(bi=Pi),!0):!1),Ri=a.filter(r=>r.kind==="audiooutput");let e=He.get("videoinput"),t=He.get("audioinput"),i=He.get("audiooutput");return _t=kt.find(r=>r.deviceId===e)||null,gt=Nt.find(r=>r.deviceId===t)||null,yi=Ri.find(r=>r.deviceId===i)||null,$e=Promise.resolve(a),a}).catch(()=>($e=null,[]))))})}function Ea(){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)&&(pr=!0),/^a=mid:0$/m.test(t.sdp)&&(ur=!0),a()}).catch(a)}):Promise.resolve()})}function Bt(a,e){return s(this,null,function*(){o.debug("Try to get media",a.getNative());let t=qe.hasPermissions(a.isVideo());!t&&!e&&S.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield Sa()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?se.CAMERA_PERMISSION:se.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?se.CAMERA_ACCESS:se.MIC_ACCESS;break}if(a.canSimplify())return Bt(a.simplify(),e);let r=e||se.UNKNOWN;throw S.onPermissionsError(r),r}})}function Ia(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 se.SCREEN_PERMISSION;default:throw se.SCREEN_ACCESS}}})}function Mi(){return Ut.length||(Ut=(()=>{let a,e=!1,t=0,i=Te.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return a=/\brv[ :]+(\d+)/g.exec(Te),["IE",a&&a[1]||"Unknown",e,t];if(i[1]==="Safari"){if(a=Te.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(a=Te.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,a[1]];if(a=Te.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t];if(a=Te.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t];if(a=Te.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),a=Te.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t];if(a=Te.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t];if(a=Te.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t];if(a=Te.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=Te.match(/version\/(\d+)/i),[i[2]?i[1]:fa,a&&a[1]||i[2]||hr,e,t]})()),Ut}var qe;(function(ge){function a(){return s(this,null,function*(){return yield Ea(),Vt()})}ge.init=a;function e(){return kt}ge.getCameras=e;function t(){return Nt}ge.getMicrophones=t;function i(){return Ri}ge.getOutput=i;function r(){return kt.length>0}ge.hasCamera=r;function n(){return Nt.length>0}ge.hasMicrophone=n;function c(){return _t}ge.getSavedCamera=c;function l(){return gt}ge.getSavedMicrophone=l;function p(){return yi}ge.getSavedOutput=p;function _(){return Pi}ge.hasCameraPermission=_;function b(){return bi}ge.hasMicrophonePermission=b;function k(L=!1){return b()?r()&&L?_():!0:!1}ge.hasPermissions=k;function K(L=!1,X=!0){return s(this,null,function*(){let h=n()&&X,Z=r()&&L,H;if(!h&&!Z)H=new MediaStream;else try{H=yield Bt(new ft(h,Z))}catch(g){H=new MediaStream}return H.getVideoTracks().length||H.addTrack(F()),H.getAudioTracks().length||H.addTrack(he()),H})}ge.getUserMedia=K;function ne(){return s(this,null,function*(){return Ia(new _r(window.screen.width,window.screen.height))})}ge.getScreenMedia=ne;function T(L,X=!1){return s(this,null,function*(){let h=X?d.videoEffectMaxWidth:d.videoMaxWidth,Z=X?d.videoEffectMaxHeight:d.videoMaxHeight;return Bt(new ft(!1,L||!0,h,Z))})}ge.getUserVideo=T;function _e(L){return s(this,null,function*(){return Bt(new ft(L||!0,!1))})}ge.getUserAudio=_e;function ke(L,X){return s(this,null,function*(){let Z=(yield Vt()).find(H=>H.kind===L&&H.deviceId===X);return Z?(L==="videoinput"?_t=Z:L==="audioinput"?gt=Z:L==="audiooutput"&&(yi=Z),He.set(L,X),Z):null})}ge.saveDeviceId=ke;function he(){if(!Lt||Lt.readyState==="ended"){let L=Ne(),X=L.createMediaStreamDestination(),h=L.createGain();h.gain.value=1e-5,h.connect(X),h.connect(L.destination);let Z=L.createOscillator();Z.type="sine",Z.frequency.value=0,Z.connect(h),Z.start(),Lt=X.stream.getAudioTracks()[0]}return Object.assign(Lt.clone(),{enabled:!1})}ge.getSilentMediaTrack=he;function F(L=d.videoMinWidth,X=d.videoMinHeight){return rt||(rt=document.createElement("canvas"),rt.getContext("2d")),rt.width=L,rt.height=X,(!xt||xt.readyState==="ended")&&(xt=rt.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(xt.clone(),{enabled:!1})}ge.getBlackMediaTrack=F;function le(){if(Re()==="Edge"&&E()<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}}ge.isBrowserSupported=le;function De(){return!!navigator.mediaDevices.getDisplayMedia}ge.isScreenCapturingSupported=De;function Oe(){return pr}ge.canVP8=Oe;function R(){return ur}ge.isUnifiedPlan=R;function A(){return ge.browserName()==="Opera"&&ge.os()==="Windows"}ge.isBrokenH264=A;function O(){return!(ge.baseChromeVersion()&&ge.isMobile())}ge.canPreferH264=O;function $(){return Di||(Di=(()=>{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 X in L)if(L.hasOwnProperty(X)&&L[X].test(Te))return X;return"Unknown"})()),Di}ge.os=$;function M(){return Ai===null&&(Ai=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(hr)),Ai}ge.isMobile=M;function Re(){return Mi()[0]}ge.browserName=Re;function E(){return Mi()[1]}ge.browserVersion=E;function ve(){return Mi()[3]}ge.baseChromeVersion=ve;function Ne(){return Oi||(Oi=new(window.AudioContext||window.webkitAudioContext)),Oi}ge.getAudioContext=Ne})(qe||(qe={}));var y=qe;function gr(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.name===t.name&&i.source===t.source))return!1;return!0}function Ie(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}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(P).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,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 oe;(function(i){i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS"})(oe||(oe={}));var J;(function(i){i.audio="audio",i.video="video",i.screen="screen"})(J||(J={}));var wi=class extends Q{constructor(){super();this._stream=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=Ie();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return s(this,arguments,function*(e=[ie.AUDIO]){if(this._stream)return;let t=e.includes(ie.VIDEO),i=e.includes(ie.AUDIO);if(!y.isBrowserSupported())throw new N(se.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=C.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(),_=p&&p.groupId;if(!c&&!_)return;let b=yield navigator.mediaDevices.enumerateDevices();!e&&c&&(e=!b.find(k=>k.groupId===c)),!t&&_&&(t=!b.find(k=>k.groupId===_)),i()}))}_changeVideoInput(e=null){return s(this,null,function*(){try{let t=e?"stream":"video";if(e=e||(yield y.getUserVideo(void 0,!!this._effect)),!this._stream)e.getTracks().forEach(i=>i.stop());else{this._disableScreenCapture();let i=yield this._videoEffect(this._effect,e.getVideoTracks()[0]);this._stopLocalTrack(J.video),u.log(m.DEVICE_CHANGED,t),o.log("Video stream changed"),yield this._replaceLocalTrack(i),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.video,mediaSettings:this._mediaSettings})}}catch(t){throw u.log(m.ERROR,"change_video"),o.warn("Camera change failed",t),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(J.audio),u.log(m.DEVICE_CHANGED,"audio"),o.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.audio,mediaSettings:this._mediaSettings})}}catch(t){throw u.log(m.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=yield this._videoEffect(null,e.getVideoTracks()[0]);u.log(m.DEVICE_CHANGED,"screen"),o.log("Screen capturing started"),this._screenTrack=t,this._mediaSettings.isScreenSharingEnabled=!0,d.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack(J.video),this._sendVideoTrack=d.consumerScreenDataChannel?y.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight):t,yield this._replaceLocalTrack(t,this._sendVideoTrack)),this._triggerEvent(oe.SCREEN_STATUS,{track:t,mediaSettings:this._mediaSettings}),this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.screen,mediaSettings:this._mediaSettings})}}catch(t){throw u.log(m.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(oe.SCREEN_STATUS,{mediaSettings:this._mediaSettings}),this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.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(oe.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(m.DEVICE_CHANGED,`effect_${e}`),d.videoEffects.setEffect(e,t)}catch(i){return o.warn("Video effect failed",i),t}})}destroy(){d.videoEffects&&(this._effect=null,d.videoEffects.stopEffect()),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),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;e?(t=(yield y.getUserVideo(void 0,!!this._effect)).getVideoTracks()[0],t=yield this._videoEffect(this._effect,t)):(t=y.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight),t=yield this._videoEffect(null,t)),this._stopLocalTrack(J.video),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.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(J.audio),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.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)return i.applyConstraints({width:{ideal:e},height:{ideal:t}})})}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()})}};var ki;(function(Oe){function a(R,A,O,$,M=!1){let Re=/[\r\n]+/,E=`\r
7
- `;if(!A&&!O&&!$)return M?ve(R.split(Re)).join(E):R;function ve(H){let g=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],me="a=rtcp-fb:111",ce=H.findIndex(ee=>ee.startsWith(me));return~ce&&(H[ce]=H[ce]+E+g.join(E)),H}function Ne(H,g,me){let ce=H.split(" "),ee=ce.slice(0,3),pe;for(pe=3;pe<ce.length;pe++)me.includes(ce[pe])&&ee.push(ce[pe]);for(pe=3;pe<ce.length;pe++)!me.includes(ce[pe])&&!g.includes(ce[pe])&&ee.push(ce[pe]);return ee.join(" ")}function ge(H,g){let me=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),ce,ee=[];for(ce=0;ce<H.length;++ce){let pe=H[ce].match(me);pe&&pe.length===3&&pe[2]===g&&ee.push(pe[1])}return ee}function L(H,g,me,ce){let ee,pe="m="+g;for(ee=0;ee<H.length;++ee)if(H[ee].startsWith(pe)){H[ee]=Ne(H[ee],me,ce);break}}let X=[],h=R.split(Re);(O||A)&&(X=ge(h,"H264"));let Z=[];if($&&(Z=ge(h,"VP9")),O){let H=X.slice(0),g=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),me;for(me=0;me<h.length;++me){let ee=h[me].match(g);ee&&ee.length===3&&H.includes(ee[2])&&H.push(ee[1])}let ce=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(me=h.length;me--;){let ee=h[me].match(ce);ee&&ee.length===3&&H.includes(ee[2])&&h.splice(me,1)}L(h,"video",H,[])}else A&&L(h,"video",[],X);return $&&L(h,"video",[],Z),M&&ve(h),h.join(E)}Oe.patchSDP=a;function e(R){return R?`${R.type||"WEB_SOCKET"}_${R.id}`:"_"}Oe.getPeerIdString=e;function t(R,A){return R&&R.id===A.id&&(R.type||"WEB_SOCKET")===(A.type||"WEB_SOCKET")}Oe.comparePeerId=t;function i(R){return s(this,null,function*(){return!R||!R.getStats?Promise.resolve(null):R.getStats(null).then(A=>{let O=null,$=null;if(A.forEach(M=>{M.type==="transport"&&M.selectedCandidatePairId?$=A.get(M.selectedCandidatePairId):M.type==="candidate-pair"&&M.state==="succeeded"&&!$&&(!M.hasOwnProperty("selected")||M.selected)&&($=M)}),$&&$.localCandidateId){let M=A.get($.localCandidateId);M&&(O={type:M.candidateType,ip:M.ip||M.ipAddress,port:M.port||M.portNumber})}return O}).catch(()=>null)})}Oe.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function c(R,A){let O=String(R);return n.test(O)?(o.warn(`Already composite id [${R}] type supplied [${A}]`),O):A===z.GROUP?"g"+O:A===z.USER?"u"+O:(o.warn(`Unknown type [${A}] for id [${R}]`),O.match(r)?"u"+O:O)}Oe.composeId=c;function l(R){return c(R.id,R.idType||z.USER)}Oe.composeParticipantId=l;function p(R){return R.participant?l(R.participant):c(R.participantId,R.participantType||z.USER)}Oe.composeMessageId=p;function _(R){let A=String(R),O=A.match(n);return O?{id:Number(O[2]),type:O[1]==="g"?z.GROUP:z.USER}:(o.warn(`Unsupported compositeId [${R}]`),{id:Number(A),type:z.USER})}Oe.decomposeId=_;function b(){let R="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),A=new Array(36),O=0,$,M;for(M=0;M<36;M++)M===8||M===13||M===18||M===23?A[M]="-":M===14?A[M]="4":(O<=2&&(O=33554432+Math.random()*16777216|0),$=O&15,O=O>>4,A[M]=R[M===19?$&3|8:$]);return A.join("")}Oe.uuid=b;function k(R,A){let O;function $(){let M=this,Re=arguments;O&&window.clearTimeout(O),O=window.setTimeout(()=>{R.apply(M,Re)},A)}return $}Oe.throttle=k;function K(R){let A="",O=R.split(`
8
- `);for(let E of O)if(E.startsWith("a=fingerprint")){let ve=E.split(" ");if(ve.length===2){A=ve[1];break}}if(!A)return at.default.minusOne;let $=A.split(":"),M=at.default.zero;for(let E=Math.min(7,$.length-1);E>=0;E--){let ve=(0,at.default)($[E],16);M=M.shiftLeft(8).or(ve)}return((E,ve)=>{let Ne=ve.value;if(typeof Ne=="bigint")return(0,at.default)(BigInt.asIntN(E,Ne));let ge=at.default.one.shiftLeft(E),L=ve.and(ge.subtract(1));return L.greaterOrEquals(ge.subtract(L))?L.subtract(ge):L})(64,M)}Oe.sdpFingerprint=K;function ne(R){return s(this,null,function*(){return new Promise(A=>window.setTimeout(A,R))})}Oe.delay=ne;function T(R,A,O){let $=[];return R.getSenders().forEach(M=>_e(A,M,M.track,O,$)),$}Oe.applySettings=T;function _e(R,A,O,$,M){if(R&&O&&O.kind===J.video){let Re=O.getSettings();if(Re){let E=R.maxBitrateK?R.maxBitrateK*1024:null,ve=Re.width,Ne=Re.height,ge=ve&&Ne&&R.maxDimension?Math.max(1,Math.max(ve,Ne)/R.maxDimension):null,L=R.maxFramerate?R.maxFramerate:null,X=R.degradationPreference?R.degradationPreference:"balanced",h=$[O.id];if(h&&h.bitrate===E&&h.scaleResolutionDownBy===ge&&h.maxFramerate===L&&h.degradationPreference===X){M[O.id]=h;return}M[O.id]={bitrate:E,scaleResolutionDownBy:ge,maxFramerate:L,degradationPreference:X};let Z=A.getParameters();Z.encodings||(Z.encodings=[{}]),Z.encodings.forEach(H=>{E?H.maxBitrate=E:delete H.maxBitrate,ge?H.scaleResolutionDownBy=ge:delete H.scaleResolutionDownBy,L?H.maxFramerate=L:delete H.maxFramerate}),Z.degradationPreference=X,A.setParameters(Z)}}}Oe.applyVideoTrackSettings=_e;function ke(R,A){Array.isArray(A)||(A=[A]);for(let O of A)if(R.includes(O))return!0;return!1}Oe.includesOneOf=ke;function he(R){var A;return Object.entries(((A=R.participantState)==null?void 0:A.state)||{}).reduce((O,[$,M])=>(R.participantState&&(O[$]={ts:R.participantState.stateUpdateTs[$],state:M}),O),{})}Oe.mapParticipantState=he;function F(R){return Object.entries(R).reduce((A,[O,{state:$}])=>(A[O]=$,A),{})}Oe.mapLegacyParticipantState=F;function le(R){return R.map(A=>{let O={uid:A.externalId,mediaSettings:A.mediaSettings,status:A.status};return d.participantStateMapped&&(O.participantState=A.participantState),O})}Oe.mapSharedParticipants=le;function De(R,A){let O=Object.keys(R),$=Object.keys(A);if(O.length!==$.length)return!1;for(let M of O)if(!$.hasOwnProperty(M)||R[M].state!==A[M].state||R[M].ts!==A[M].ts)return!1;return!0}Oe.isEqualParticipantState=De})(ki||(ki={}));var C=ki;var Pe;(function(i){i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP"})(Pe||(Pe={}));var re;(function(l){function a(p){return p.length?typeof p[0]=="object"?p:p.map(_=>e(_)):[]}l.fromIds=a;function e(p,_=Pe.USER){return{id:p,type:_}}l.fromId=e;function t(p){return{id:p.id,type:p.type==="ANONYM"?Pe.ANONYM:Pe.USER}}l.fromSignaling=t;function i(p){return`{"id":"${p.id}","type":"${p.type}"}`}l.toString=i;function r(p,_=Pe.USER){return i(e(p,_))}l.fromIdToString=r;function n(p){try{return JSON.parse(p)}catch(_){throw new Error(`Failed to parse ExternalId from string '${p}'`)}}l.fromString=n;function c(p,_){return p.id===_.id&&p.type===_.type}l.compare=c})(re||(re={}));var Ce;(function(r){r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE"})(Ce||(Ce={}));var Ni=":",fr="s",Sr="m";function Je(a){return a.participantId+(a.mediaType?Ni+fr+a.mediaType:"")+(a.streamName?Ni+Sr+a.streamName:"")}function St(a){let e=a.split(Ni),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 fr:i.mediaType=Ca(r.slice(1));break;case Sr:i.streamName=r.slice(1);break;default:throw new Error("Unexpected parameter type "+r.charAt(0)+" in stream description "+a)}return i}function Ca(a){for(let e of Object.keys(Ce))if(e===a)return Ce[e];return null}function xi(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 Ft(a,e){return!(!xi(a.camera,e.camera)||!xi(a.screenSharing,e.screenSharing))}function Li(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function vr(a){return{camera:Object.assign({},a.camera),screenSharing:Object.assign({},a.screenSharing)}}function Er(a){try{return btoa(JSON.stringify(a))}catch(e){o.warn("WaitingParticipant: failed convert to string",a,e)}return null}function Ir(a){try{return JSON.parse(atob(a))}catch(e){o.warn("WaitingParticipant: failed convert from string",a,e)}return null}var vt=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(m.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,u.log(m.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(m.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),u.log(m.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===J.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Gt=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 n;if(!((n=this._output)==null?void 0:n.audioTrack))return;let e=new Audio;e.muted=!1,e.volume=this._volume,e.preload="auto";let t=()=>{o.warn("Error on play audio"),S.onAutoplayError()},i=c=>{e.srcObject=new MediaStream([c]),e.load();let l=e.play();l?l.catch(t):t()},r=()=>{var l;o.debug("Recover audio playback");let c=(l=this._output)==null?void 0:l.audioTrack;c?i(c):o.warn("Broken audio track")};e.onpause=r,e.onstalled=r,e.onerror=r,i(this._output.audioTrack),this._output.audioElement=e}_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(m.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var Ta=90,Ra=3,Ht=class extends Q{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),S.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>Ta?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Ra)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var ya=44100,Et=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=ya/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 Wt=class extends Q{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&S.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,d.voiceParams.interval)};this._interval=window.setTimeout(t,d.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,oe.SOURCE_CHANGED,r=>{r.kind===J.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new Et("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 Pa=1e3;function Ue(a,e,t=0){return e in a&&a[e]?a[e]:t}function Cr(...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 ba(a){return(e,t)=>e[a]-t[a]}function jt(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function Aa(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Da(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Ui(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=Da(t[1])?Ui(t[1]):t[1],e),{})}function Oa(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function Ma(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(Oa).then(Aa)})}function wa(a){let e=a.filter(We("type","candidate-pair")).sort(ba("priority")).find(Cr(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}})),Ui(t)}function ka(a,e){let t=jt("id",a),i=a.filter(Cr(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=jt("trackIdentifier",n)}return i.map(n=>{let c=Number(n.ssrc),l=n.mediaType||n.kind,p=n.trackId,_=n.type,b=n.codecId;if(y.browserName()==="Safari"){let K=/^.+_([\d]+)$/.exec(n.id);if(K&&(c=parseInt(K[1],10)),l=n.id.indexOf("Audio")>0?"audio":"video",e[c]){let ne=l+"-"+e[c];r[ne]&&(p=r[ne].id)}}if(!_||!c||!l)return null;let k={ssrc:c,type:_,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(b&&t[b]){let K=t[b];k.clockRate=K.clockRate,k.mimeType=K.mimeType}if(p&&t[p]){let K=t[p];k.frameHeight=K.frameHeight,k.frameWidth=K.frameWidth,k.framesDecoded=K.framesDecoded,k.framesReceived=K.framesReceived,k.framesDropped=K.framesDropped}return Ui(k)}).filter(n=>!!n)}function Na(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=jt("ssrc",a.rtps),i=jt("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,_=c.packetsReceived-l.packetsReceived;c.packetLoss=parseFloat((100*p/(p+_)).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 It(i,r){return s(this,arguments,function*(a,e,t={}){let n=yield Ma(a),c={timestamp:Date.now(),transport:wa(n),rtps:ka(n,t)};return e?Na(c,e):(yield C.delay(Pa),It(a,c,t))})}var Kt=.8,Ye=class extends Q{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=D.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,oe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,oe.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(m.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===D.IDLE?this._failedOnCreate=c:this.close(c)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==D.IDLE&&e!==D.CLOSED&&e!==D.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(m.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(D.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(f.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Ft(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(f.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(D.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(D.CLOSED)),this._triggerEvent(f.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(f.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=C.getPeerIdString(e.peerId);C.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(m.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(m.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(f.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(f.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===D.IDLE||e===D.OPENED?this._setState(D.CONNECTING):this._setState(D.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),u.log(m.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(D.CONNECTED),this._stopReconnection(),C.getPeerConnectionHostInfo(this._pc).then(e=>{e&&u.log(m.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(D.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(j.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(u.log(m.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(m.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(m.ERROR,"createOffer-direct"),i}).then(i=>s(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=Ye._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(m.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(m.ERROR,"createAnswer-direct"),e}).then(e=>s(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=Ye._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(m.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=C.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(m.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}It(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:j.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:j.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(f.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-Kt)+r*Kt,loss:this._lastNetworkStat.loss*(1-Kt)+n*Kt},l=i(c),p=t(c),_=i(this._remoteNetworkStat),b=t(this._remoteNetworkStat),k=i(this._lastNetworkStat),K=t(this._lastNetworkStat),_e=l||_?.2:p&&b?1:0,ke=Date.now();if((k!==l||K!==p||ke-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)})),_e){let he={};he[this._participantId]=he[""]=_e,this._triggerEvent(f.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=C.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(S.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=C.applySettings(this._pc,e,this._prevConsumerSettings))}};var Vi;(function(r){r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare"})(Vi||(Vi={}));var Ct=Vi;var ze=pt(require("messagepack"));var Bi=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(([T,_e])=>{let ke=St(T);this.streamDescriptionByCompactId.set(_e,ke)}),null;case 2:case 4:let p=(0,ze.decode)(r),_=[];for(let T of p){let _e=this.getStreamDescription(T);_e&&_.push(_e.participantId)}return i===2?{type:"notification",notification:w.AUDIO_ACTIVITY,activeParticipants:_}:{type:"notification",notification:w.STALLED_ACTIVITY,stalledParticipants:_};case 3:let b=(0,ze.decode)(r);return{type:"notification",notification:w.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(b))==null?void 0:n.participantId};case 5:let k=(0,ze.decode)(r);return{type:"notification",notification:w.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:k[0],maxDimension:k[1]}};case 6:let K=(0,ze.decode)(r),ne={};for(let[T,_e]of Object.entries(K)){let ke=(c=this.getStreamDescription(Number(T)))==null?void 0:c.participantId;ke&&(ne[ke]=_e/100)}return{type:"notification",notification:w.NETWORK_STATUS,statuses:ne};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],_;if(c!==null){if(_=this.getStreamDescription(c),!_){o.error(`could not uncompress participant ID ${c}`);continue}}else _=null;if(p===null){o.error("unexpected null sequenceNumber",r,n);continue}let b=Me.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,k=l?l>>>0:null;i.push({participantStreamDescription:_,streamId:b,rtpTimestamp:k,sequenceNumber:p})}return{type:"notification",notification:w.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Fi=pt(require("@vkontakte/libvpx"));var Tr;(function(t){t.VP9="vp09.00.50.08",t.VP8="vp8"})(Tr||(Tr={}));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 Ve=class{constructor(){this._worker=null}_createWorker(c,l){return s(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((p,_)=>{let b=i.join(","),k=new Blob([e,`exports.default(${b});`],{type:"application/javascript; charset=utf-8"}),K=window.URL.createObjectURL(k);this._worker=new Worker(K),this._worker.onmessage=ne=>{switch(ne.data.type){case fe.READY:p();break;case fe.ERROR:_(ne.data.error);break;case fe.FRAME:t(ne.data);break;case fe.DEBUG:o.debug(ne.data.message);break;case fe.LOG_ERROR:u.log(m.ERROR,ne.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 Ve{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)},[Fi.default,Fi.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 Qe=class extends Ve{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 xa=65536,$t=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,Qe.isBrowserSupported()?this._decoder=new Qe: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)%xa!==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 qt=1,La=1,Rr=0,yr=11,Pr=1,br=2,Ar=4,Dr=8;function Or(a,e,t,i,r,n,c){let l=0;e&&(l|=Pr),t&&(l|=br),i&&(l|=Ar),c||(l|=Dr);let p=new ArrayBuffer(yr),_=new DataView(p);if(_.setUint8(0,qt),_.setUint16(1,r),_.setUint32(3,a),_.setUint8(7,n?1:0),_.setUint16(8,Rr),_.setUint8(10,l),!c)return p;let b=new Uint8Array(p.byteLength+c.byteLength);return b.set(new Uint8Array(p),0),b.set(new Uint8Array(c),p.byteLength),b.buffer}function Mr(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&Pr),_=!!(l&br),b=!!(l&Ar),k=!!(l&Dr);if(t!==qt)throw new Error(`Unexpected protocol version. Got ${t}, expected ${qt}`);return{timestamp:r,start:p,end:_,keyframe:b,sequence:i,isVP9:n,ssrc:c,eos:k,data:a.slice(yr)}}function wr(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==qt||e.getUint8(1)!==La||e.getUint16(2)!==Rr)}var Tt=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};o.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=n=>this._onDataChannelMessage(n.data)}_onDataChannelMessage(e){var n,c;let t=Mr(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 $t(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(Qe.isBrowserSupported()||nt.isBrowserSupported())&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var Gi=pt(require("@vkontakte/libvpx"));var Ua=1e3,Rt=class extends Ve{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;})();
6
+ var ia=Object.create;var lt=Object.defineProperty;var ra=Object.getOwnPropertyDescriptor;var aa=Object.getOwnPropertyNames,Yi=Object.getOwnPropertySymbols,na=Object.getPrototypeOf,Qi=Object.prototype.hasOwnProperty,sa=Object.prototype.propertyIsEnumerable;var zi=(a,e,t)=>e in a?lt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,Xi=(a,e)=>{for(var t in e||(e={}))Qi.call(e,t)&&zi(a,t,e[t]);if(Yi)for(var t of Yi(e))sa.call(e,t)&&zi(a,t,e[t]);return a};var Zi=a=>lt(a,"__esModule",{value:!0});var is=typeof require!="undefined"?require:a=>{throw new Error('Dynamic require of "'+a+'" is not supported')};var oa=(a,e)=>{Zi(a);for(var t in e)lt(a,t,{get:e[t],enumerable:!0})},ca=(a,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of aa(e))!Qi.call(a,i)&&i!=="default"&&lt(a,i,{get:()=>e[i],enumerable:!(t=ra(e,i))||t.enumerable});return a},pt=a=>ca(Zi(lt(a!=null?ia(na(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(_){r(_)}},c=p=>{try{l(t.throw(p))}catch(_){r(_)}},l=p=>p.done?i(p.value):Promise.resolve(p.value).then(n,c);l((t=t.apply(a,e)).next())});oa(exports,{Api:()=>At,BaseApi:()=>Ze,BaseLogger:()=>et,BaseSignaling:()=>tt,CallDirection:()=>Be,CallType:()=>xe,ChatRoomEventType:()=>Ot,ConversationOption:()=>Mt,DebugMessageType:()=>de,ExternalIdType:()=>Pe,HangupReason:()=>N,HangupType:()=>P,MediaOption:()=>re,MediaType:()=>Ce,ParticipantState:()=>W,ParticipantStatus:()=>q,Signaling:()=>we,SignalingCommandType:()=>G,SignalingConnectionType:()=>Le,SignalingNotification:()=>w,UserRole:()=>je,UserType:()=>Q,Utils:()=>C,acceptCall:()=>sn,addMovie:()=>Gn,addParticipant:()=>pn,addParticipantInternal:()=>Kr,apiCall:()=>an,authorize:()=>nn,browser:()=>Qa,callInternal:()=>Hr,callTo:()=>en,captureScreen:()=>mn,changeConversationOptions:()=>bn,changeDevice:()=>hn,changeParticipantState:()=>En,changePriorities:()=>vn,changeVideoEffect:()=>qn,chatHistory:()=>Dn,chatMessage:()=>An,chatMessageInternal:()=>zr,createJoinLink:()=>wn,customData:()=>On,customDataInternal:()=>Xr,debug:()=>Kn,debugMessage:()=>$n,declineCall:()=>on,forceRelayPolicy:()=>Ln,getAnonymTokenByLink:()=>Nn,getStreamInfo:()=>Fn,getTokenForAnonym:()=>rn,getWaitingHall:()=>Yn,grantRoles:()=>Cn,grantRolesInternal:()=>qr,hangup:()=>ln,init:()=>Za,joinCall:()=>cn,joinCallByLink:()=>dn,joinCallInternal:()=>jr,muteParticipant:()=>Tn,muteParticipantInternal:()=>Jr,pinParticipant:()=>yn,pinParticipantInternal:()=>Qr,processPush:()=>tn,processPushInternal:()=>Wr,promoteParticipant:()=>Qn,recordSetRole:()=>Bn,removeHistoryRecords:()=>zn,removeJoinLink:()=>kn,removeMovie:()=>Wn,removeParticipant:()=>un,removeParticipantInternal:()=>$r,setApi:()=>Fr,setAudioStream:()=>Jn,setLocalResolution:()=>Sn,setLogger:()=>za,setMediaModifiers:()=>Pn,setSignalingFactory:()=>Gr,setStatisticsInterval:()=>jn,setVideoEffects:()=>Xa,setVideoStream:()=>_n,setVolume:()=>xn,startConversation:()=>Mn,startStream:()=>Un,stopStream:()=>Vn,toggleLocalAudio:()=>fn,toggleLocalVideo:()=>gn,unmuteRequest:()=>Rn,unmuteRequestInternal:()=>Yr,updateDisplayLayout:()=>In,updateMovie:()=>Hn});var Ji=pt(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 z=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])setTimeout(i,0,...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 z{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var Qt;(function(i){i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING"})(Qt||(Qt={}));var Be=Qt;var zt;(function(i){i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT"})(zt||(zt={}));var xe=zt;var Xt;(function(t){t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP"})(Xt||(Xt={}));var Ot=Xt;var Zt;(function(t){t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD"})(Zt||(Zt={}));var er=Zt;var ei;(function(i){i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL"})(ei||(ei={}));var Mt=ei;function tr(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function ir(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 ti;(function(T){T.CAMERA_PERMISSION="camera",T.MIC_PERMISSION="mic",T.CAMERA_ACCESS="cameralock",T.MIC_ACCESS="miclock",T.MIC_NOT_FOUND="nomic",T.SCREEN_PERMISSION="screenpermission",T.SCREEN_ACCESS="screenlock",T.CONNECTION="connection",T.NETWORK="network",T.UNKNOWN="unknown",T.UNSUPPORTED="unsupported",T.SIGNALING_FAILED="signalingfailed",T.API="api",T.AUTH="auth"})(ti||(ti={}));var se=ti;var ii;(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"})(ii||(ii={}));var P=ii;var ri;(function(i){i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING"})(ri||(ri={}));var re=ri;var ai;(function(i){i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT"})(ai||(ai={}));var ye=ai;var ni;(function(r){r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP"})(ni||(ni={}));var W=ni;var si;(function(r){r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry"})(si||(si={}));var Le=si;var oi;(function(i){i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT"})(oi||(oi={}));var Se=oi;var ci;(function(g){g.TRANSMITTED_DATA="transmitted-data",g.ACCEPTED_CALL="accepted-call",g.HUNGUP="hungup",g.PARTICIPANT_ADDED="participant-added",g.PARTICIPANT_JOINED="participant-joined",g.CLOSED_CONVERSATION="closed-conversation",g.MEDIA_SETTINGS_CHANGED="media-settings-changed",g.PARTICIPANT_STATE_CHANGED="participant-state-changed",g.RATE_CALL_DATA="rate-call-data",g.FEATURE_SET_CHANGED="feature-set-changed",g.TOPOLOGY_CHANGED="topology-changed",g.PRODUCER_UPDATED="producer-updated",g.CONSUMER_ANSWERED="consumer-answered",g.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",g.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",g.SETTINGS_UPDATE="settings-update",g.VIDEO_QUALITY_UPDATE="video-quality-update",g.REGISTERED_PEER="registered-peer",g.SWITCH_MICRO="switch-micro",g.RECORD_STARTED="record-started",g.RECORD_STOPPED="record-stopped",g.REALLOC_CON="realloc-con",g.AUDIO_ACTIVITY="audio-activity",g.SPEAKER_CHANGED="speaker-changed",g.STALLED_ACTIVITY="stalled-activity",g.CHAT_MESSAGE="chat-message",g.CUSTOM_DATA="custom-data",g.ROLES_CHANGED="roles-changed",g.MUTE_PARTICIPANT="mute-participant",g.PIN_PARTICIPANT="pin-participant",g.OPTIONS_CHANGED="options-changed",g.NETWORK_STATUS="network-status",g.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",g.PROMOTE_PARTICIPANT="promote-participant",g.CHAT_ROOM_UPDATED="chat-room-updated",g.PROMOTION_APPROVED="promotion-approved",g.JOIN_LINK_CHANGED="join-link-changed"})(ci||(ci={}));var w=ci;var di;(function(E){E.ERROR="callError",E.DEVICES="callDevices",E.CALL_SPEC_ERROR="callSpecError",E.ICE_CONNECTION_STATE="callIceConnectionState",E.ICE_CONNECTION_TYPE="callIceConnectionType",E.ICE_RESTART="callIceRestart",E.PUSH="callPush",E.OUTGOING_CALL="callStart",E.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",E.JOIN_CONVERSATION="callJoinConversation",E.ACCEPTED_OUTGOING="callAcceptedOutgoing",E.ACCEPT_INCOMING="callAcceptIncoming",E.DECLINE_INCOMING="callDeclineIncoming",E.ACCEPT_CONCURRENT="callAcceptConcurrent",E.HANGUP="callHangup",E.MEDIA_STATUS="callMediaStatus",E.DEVICE_CHANGED="callDeviceChanged",E.SOCKET_ACTION="callSocketAction",E.ADD_PARTICIPANT="callAddParticipant",E.REMOVE_PARTICIPANT="callRemoveParticipant",E.POOR_CONNECTION="callPoorConnection",E.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",E.RELAY_POLICY="callForceRelay",E.PAT_ALLOCATED="patAllocate",E.PAT_DEALLOCATED="patDeallocate",E.PAT_ERROR="patError",E.PAT_WAITING_TIME_ERROR="patWaitingTimeError",E.PAT_OUTDATED_RESPONSE="patOutdatedResponse"})(di||(di={}));var m=di;var li;(function(t){t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat"})(li||(li={}));var Me=li;var ut;(function(t){t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error"})(ut||(ut={}));var rr=ut;function ar(a){switch(a){case 1:return ut.NO_AVAILABLE_TRACKS;default:return ut.UNKNOWN_ERROR}}var pi;(function(t){t.CREATOR="CREATOR",t.ADMIN="ADMIN"})(pi||(pi={}));var je=pi;function ht(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var ui;(function(t){t.USER="USER",t.GROUP="GROUP"})(ui||(ui={}));var Q=ui;var hi=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 nr=2*1024*1024,da=512*1024,mt=100*1024,la=5,mi="_okcls_logs_session_",pa=3e4,sr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=nr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(mi)!==0)continue;let i=e.getItem(t);if(!i){dr(t);continue}let r=cr(i);this.add(t,r)}}catch(e){console.error("Storage is blocked",e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(mt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(mi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(dr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>nr||this.length>la-1||this.size+e>this.available);)this.deleteOldestItem()}};function or(){return`${mi}${Date.now()}`}function cr(a){return new Blob([a]).size}function dr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function _i(){let a=Ke.toString();if(!Ie.available||!a)return;let e=cr(a);Ie.cleanup(e);try{window.localStorage.setItem(wt,a)}catch(t){if(console.warn("Failed to write log to storage",t),Ie.storageSize=Ie.size+e,Ie.cleanup(mt+e),Ie.available>=mt+e){_i();return}if(e>mt){Ke.bisect(),_i();return}Ie.storageSize=0;return}e>da&&(Ie.add(wt,e),wt=or(),Ke.clear(),Ie.cleanup(mt))}function gi(){!Ie.available||!Ke.length||_i()}function ua(a=!1){let e=[];try{let r=window.localStorage;for(let c of Ie.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 ha(t,i),i}function ha(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 lr(a,e){!Ie.available||(Ke.push({t:Date.now(),l:a,d:e}),Si||(Si=window.setTimeout(()=>{Si=null,gi()},pa)))}function fi(){Ie||(Ie=new sr,Ke=new hi,wt=or(),window.addEventListener("beforeunload",gi))}var Ie,Ke,wt,Si=null;window.__VKCallsSDKLogs__=(a=!1)=>(Ie||fi(),gi(),ua(a));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 v=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(v._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(v._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(v._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(v._params,e)}static get(e){return v._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.4.3-beta.9"}static get debug(){return!1}static get protocolVersion(){return 5}static get platform(){return v._params.platform}static set platform(e){v._params.platform=e}static get clientType(){return v._params.clientType}static set clientType(e){v._params.clientType=e}static get device(){return v._params.device}static get apiAppId(){return 42}static get apiKey(){return v._params.apiKey}static get apiEnv(){switch(v._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 v._params.authToken}static set authToken(e){v._params.authToken=e}static get anonymToken(){return v._params.anonymToken}static set anonymToken(e){v._params.anonymToken=e}static get domain(){return v._params.domain}static get iceServers(){return v._params.iceServers}static set iceServers(e){v._params.iceServers=e}static get wssBase(){return v._params.wssBase}static set wssBase(e){v._params.wssBase=e}static get wssToken(){return v._params.wssToken}static set wssToken(e){v._params.wssToken=e}static get signalingReconnectDelay(){return v._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return v._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return v._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return v._params.waitConnectionDelay}static get waitResponseDelay(){return v._params.waitResponseDelay}static get waitMessageDelay(){return v._params.waitMessageDelay}static get debugLog(){return v._params.debugLog}static get forceRelayPolicy(){return v._params.forceRelayPolicy}static set forceRelayPolicy(e){v._params.forceRelayPolicy=e}static get videoMinWidth(){return v._params.videoMinWidth}static get videoMaxWidth(){return v._params.videoMaxWidth}static set videoMaxWidth(e){v._params.videoMaxWidth=e}static get videoMinHeight(){return v._params.videoMinHeight}static get videoMaxHeight(){return v._params.videoMaxHeight}static set videoMaxHeight(e){v._params.videoMaxHeight=e}static get videoAspectRatio(){return v._params.videoAspectRatio}static get videoFrameRate(){return v._params.videoFrameRate}static get videoFacingMode(){return v._params.videoFacingMode}static get screenFrameRate(){return v._params.screenFrameRate}static get videoEffects(){return v._params.videoEffects}static set videoEffects(e){v._params.videoEffects=e}static get videoEffectMaxWidth(){return v._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){v._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return v._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){v._params.videoEffectMaxHeight=e}static get voiceParams(){return v._params.voiceParams}static get specListenerParams(){return v._params.specListenerParams}static get iceRestartWaitTime(){return v._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return v._params.transportConnectionWaitTime}static get statisticsInterval(){return v._params.statisticsInterval}static set statisticsInterval(e){v._params.statisticsInterval=e}static get networkStatisticsInterval(){return v._params.networkStatisticsInterval}static get perfStatReportEnabled(){return v._params.perfStatReportEnabled}static get producerNotificationDataChannel(){return v._params.producerNotificationDataChannel}static get producerCommandDataChannel(){return v._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return v._params.consumerScreenDataChannel}static set consumerScreenDataChannel(e){v._params.consumerScreenDataChannel=e}static get producerScreenDataChannel(){return v._params.producerScreenDataChannel&&v._params.producerNotificationDataChannel}static set producerScreenDataChannel(e){v._params.producerScreenDataChannel=e}static get noiseSuppression(){return v._params.noiseSuppression}static set noiseSuppression(e){v._params.noiseSuppression=e}static get preferH264(){return v._params.preferH264}static get preferVP9(){return v._params.preferVP9}static get audioNack(){return v._params.audioNack}static get consumerScreenTrack(){return v._params.consumerScreenTrack&&v._params.consumerScreenDataChannel}static get producerScreenTrack(){return v._params.producerScreenTrack&&v._params.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=v._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get videoTracksCount(){return v._params.videoTracksCount}static get breakVideoPayloadTypes(){return v._params.breakVideoPayloadTypes}static get filteredMessages(){return v._params.filteredMessages}static get batchParticipantsOnStart(){return v._params.batchParticipantsOnStart}static get participantStateMapped(){return v._params.participantStateMapped}},d=v;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 Ge(a){return Object.assign({},a)}function _t(a){return a.slice()}var vi;(function(ts){function a(I,U){V("onLocalStream",I,Ge(U))}ts.onLocalStream=a;function e(I,U){V("onScreenStream",I,Ge(U))}ts.onScreenStream=e;function t(I,U){V("onLocalStreamUpdate",Ge(I),U)}ts.onLocalStreamUpdate=t;function i(I){V("onLocalStatus",I)}ts.onLocalStatus=i;function r(I,U){V("onRemoteStream",I,U)}ts.onRemoteStream=r;function n(I,U,ue){V("onRemoteLive",I,U,ue)}ts.onRemoteLive=n;function c(I,U){V("onRemoteScreenStream",I,U)}ts.onRemoteScreenStream=c;function l(I,U,ue){V("onConversation",I,Ge(U),ue)}ts.onConversation=l;function p(I,U){V("onRemoteMediaSettings",I,Ge(U))}ts.onRemoteMediaSettings=p;function _(I,U){V("onRemoteParticipantState",I,Ge(U))}ts.onRemoteParticipantState=_;function b(I,U,ue=null){V("onRemoteStatus",I,U,ue)}ts.onRemoteStatus=b;function k(I,U,ue=null){V("onParticipantStatus",I,U,ue)}ts.onParticipantStatus=k;function K(){V("onPermissionsRequested")}ts.onPermissionsRequested=K;function ne(I){V("onPermissionsError",I)}ts.onPermissionsError=ne;function T(I){V("onRemoteRemoved",I)}ts.onRemoteRemoved=T;function _e(I,U,ue){V("onCallState",I,U,Ge(ue))}ts.onCallState=_e;function ke(I,U){V("onDeviceSwitched",I,U)}ts.onDeviceSwitched=ke;function he(I){V("onUnmuteRequest",I)}ts.onUnmuteRequest=he;function F(I,U){V("onUnmutePermission",I,_t(U))}ts.onUnmutePermission=F;function le(I,U){V("onRolesChanged",I,_t(U))}ts.onRolesChanged=le;function De(I){V("onLocalRolesChanged",_t(I))}ts.onLocalRolesChanged=De;function Oe(I,U){V("onPinnedParticipant",I,U)}ts.onPinnedParticipant=Oe;function R(I){V("onLocalPin",I)}ts.onLocalPin=R;function A(I){V("onOptionsChanged",_t(I))}ts.onOptionsChanged=A;function O(){V("onCallAccepted")}ts.onCallAccepted=O;function $(){V("onRateNeeded")}ts.onRateNeeded=$;function M(I){V("onSpeakerChanged",I)}ts.onSpeakerChanged=M;function Re(I){V("onVolumesDetected",_t(I))}ts.onVolumesDetected=Re;function E(I,U){V("onLocalVolume",I,U)}ts.onLocalVolume=E;function Ee(I,U){V("onJoinStatus",I,U)}ts.onJoinStatus=Ee;function Ne(I,U){V("onHangup",I,U)}ts.onHangup=Ne;function ge(I){V("onMultipartyChatCreated",Ge(I))}ts.onMultipartyChatCreated=ge;function L(){V("onDeviceChange")}ts.onDeviceChange=L;function X(I){V("onFingerprintChange",I)}ts.onFingerprintChange=X;function h(){V("onTokenExpired")}ts.onTokenExpired=h;function Z(I,U,ue=!1){V("onChatMessage",I,U,ue)}ts.onChatMessage=Z;function H(I,U,ue=!1){V("onCustomData",I,U,ue)}ts.onCustomData=H;function g(I,U,ue,Zr,ea,ta){V("onRecordStarted",I,U,ue,Zr,ea,ta)}ts.onRecordStarted=g;function me(){V("onRecordStopped")}ts.onRecordStopped=me;function ce(I){V("onLocalNetworkStatusChanged",I)}ts.onLocalNetworkStatusChanged=ce;function ee(I){V("onNetworkStatusChanged",I)}ts.onNetworkStatusChanged=ee;function pe(I,...U){V("onDebugMessage",I,...U)}ts.onDebugMessage=pe;function Xn(I,U){let ue=Object.assign({},I,{memory:U});V("onStatistics",ue)}ts.onStatistics=Xn;function Zn(){V("onAutoplayError")}ts.onAutoplayError=Zn;function es(I,U,ue){V("onChatRoomUpdated",I,U,ue)}ts.onChatRoomUpdated=es})(vi||(vi={}));var S=vi;var de;(function(r){r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR"})(de||(de={}));var Ei;(function(le){let a="📞",e=(De,...Oe)=>{S.onDebugMessage(De,...Oe)},t=!1,i=(De,Oe)=>(...R)=>{De(...R),lr(Oe,R)},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,de.DEBUG),_=e.bind(null,de.LOG),b=e.bind(null,de.WARN),k=e.bind(null,de.ERROR);le.debug=p,le.log=_,le.warn=b,le.error=k;function ke(){return t}le.enabled=ke;function he(De){t=De,d.debugLog&&fi(),De?(le.debug=d.debugLog?i(r,de.DEBUG):r,le.log=d.debugLog?i(n,de.LOG):n,le.warn=d.debugLog?i(c,de.WARN):c,le.error=d.debugLog?i(l,de.ERROR):l):(le.debug=d.debugLog?i(p,de.DEBUG):p,le.log=d.debugLog?i(_,de.LOG):_,le.warn=d.debugLog?i(b,de.WARN):b,le.error=d.debugLog?i(k,de.ERROR):k)}le.toggle=he;function F(De,...Oe){switch(De){case de.DEBUG:le.debug(...Oe);break;case de.LOG:le.log(...Oe);break;case de.WARN:le.warn(...Oe);break;case de.ERROR:le.error(...Oe);break}}le.send=F})(Ei||(Ei={}));var o=Ei;var at=pt(require("big-integer"));var Ii="_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 ma(a){let e=it?it.getItem(Ii+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function _a(a,e){try{it&&it.setItem(Ii+a,JSON.stringify(e))}catch(t){}}function ga(a){it&&it.removeItem(Ii+a)}var Ci;(function(i){function a(r){return ma(r)||null}i.get=a;function e(r,n){_a(r,n)}i.set=e;function t(r){ga(r)}i.remove=t})(Ci||(Ci={}));var He=Ci;var $e=null,Ti=null,kt=[],Nt=[],Ri=[],gt=null,ft=null,yi=null,Pi=!1,bi=!1,xt,rt,Lt,pr=!1,ur=!1,Ai=null,Di="",Ut=[],Oi=null,hr=navigator.appVersion,fa=navigator.appName,Te=navigator.userAgent,mr;(function(r){r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right"})(mr||(mr={}));var St=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;ft&&(l=ft.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;gt&&(l=gt.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}},_r=class extends St{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 Sa(){return s(this,null,function*(){$e=null,yield Vt()})}function va(){$e=null,Vt().then(()=>S.onDeviceChange())}function Vt(){return s(this,null,function*(){return $e||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Ti&&navigator.mediaDevices.addEventListener&&(Ti=C.throttle(va,1e3),navigator.mediaDevices.addEventListener("devicechange",Ti)),$e=navigator.mediaDevices.enumerateDevices().then(a=>{kt=a.filter(r=>r.kind==="videoinput"?(r.label&&(Pi=!0),!0):!1),Nt=a.filter(r=>r.kind==="audioinput"?(r.label?bi=!0:qe.isMobile()&&qe.browserName()==="Firefox"&&(bi=Pi),!0):!1),Ri=a.filter(r=>r.kind==="audiooutput");let e=He.get("videoinput"),t=He.get("audioinput"),i=He.get("audiooutput");return gt=kt.find(r=>r.deviceId===e)||null,ft=Nt.find(r=>r.deviceId===t)||null,yi=Ri.find(r=>r.deviceId===i)||null,$e=Promise.resolve(a),a}).catch(()=>($e=null,[]))))})}function Ea(){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)&&(pr=!0),/^a=mid:0$/m.test(t.sdp)&&(ur=!0),a()}).catch(a)}):Promise.resolve()})}function Bt(a,e){return s(this,null,function*(){o.debug("Try to get media",a.getNative());let t=qe.hasPermissions(a.isVideo());!t&&!e&&S.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield Sa()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?se.CAMERA_PERMISSION:se.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?se.CAMERA_ACCESS:se.MIC_ACCESS;break}if(a.canSimplify())return Bt(a.simplify(),e);let r=e||se.UNKNOWN;throw S.onPermissionsError(r),r}})}function Ia(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 se.SCREEN_PERMISSION;default:throw se.SCREEN_ACCESS}}})}function Mi(){return Ut.length||(Ut=(()=>{let a,e=!1,t=0,i=Te.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return a=/\brv[ :]+(\d+)/g.exec(Te),["IE",a&&a[1]||"Unknown",e,t];if(i[1]==="Safari"){if(a=Te.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(a=Te.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,a[1]];if(a=Te.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t];if(a=Te.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t];if(a=Te.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),a=Te.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t];if(a=Te.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t];if(a=Te.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t];if(a=Te.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=Te.match(/version\/(\d+)/i),[i[2]?i[1]:fa,a&&a[1]||i[2]||hr,e,t]})()),Ut}var qe;(function(ge){function a(){return s(this,null,function*(){return yield Ea(),Vt()})}ge.init=a;function e(){return kt}ge.getCameras=e;function t(){return Nt}ge.getMicrophones=t;function i(){return Ri}ge.getOutput=i;function r(){return kt.length>0}ge.hasCamera=r;function n(){return Nt.length>0}ge.hasMicrophone=n;function c(){return gt}ge.getSavedCamera=c;function l(){return ft}ge.getSavedMicrophone=l;function p(){return yi}ge.getSavedOutput=p;function _(){return Pi}ge.hasCameraPermission=_;function b(){return bi}ge.hasMicrophonePermission=b;function k(L=!1){return b()?r()&&L?_():!0:!1}ge.hasPermissions=k;function K(L=!1,X=!0){return s(this,null,function*(){let h=n()&&X,Z=r()&&L,H;if(!h&&!Z)H=new MediaStream;else try{H=yield Bt(new St(h,Z))}catch(g){H=new MediaStream}return H.getVideoTracks().length||H.addTrack(F()),H.getAudioTracks().length||H.addTrack(he()),H})}ge.getUserMedia=K;function ne(){return s(this,null,function*(){return Ia(new _r(window.screen.width,window.screen.height))})}ge.getScreenMedia=ne;function T(L,X=!1){return s(this,null,function*(){let h=X?d.videoEffectMaxWidth:d.videoMaxWidth,Z=X?d.videoEffectMaxHeight:d.videoMaxHeight;return Bt(new St(!1,L||!0,h,Z))})}ge.getUserVideo=T;function _e(L){return s(this,null,function*(){return Bt(new St(L||!0,!1))})}ge.getUserAudio=_e;function ke(L,X){return s(this,null,function*(){let Z=(yield Vt()).find(H=>H.kind===L&&H.deviceId===X);return Z?(L==="videoinput"?gt=Z:L==="audioinput"?ft=Z:L==="audiooutput"&&(yi=Z),He.set(L,X),Z):null})}ge.saveDeviceId=ke;function he(){if(!Lt||Lt.readyState==="ended"){let L=Ne(),X=L.createMediaStreamDestination(),h=L.createGain();h.gain.value=1e-5,h.connect(X),h.connect(L.destination);let Z=L.createOscillator();Z.type="sine",Z.frequency.value=0,Z.connect(h),Z.start(),Lt=X.stream.getAudioTracks()[0]}return Object.assign(Lt.clone(),{enabled:!1})}ge.getSilentMediaTrack=he;function F(L=d.videoMinWidth,X=d.videoMinHeight){return rt||(rt=document.createElement("canvas"),rt.getContext("2d")),rt.width=L,rt.height=X,(!xt||xt.readyState==="ended")&&(xt=rt.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(xt.clone(),{enabled:!1})}ge.getBlackMediaTrack=F;function le(){if(Re()==="Edge"&&E()<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}}ge.isBrowserSupported=le;function De(){return!!navigator.mediaDevices.getDisplayMedia}ge.isScreenCapturingSupported=De;function Oe(){return pr}ge.canVP8=Oe;function R(){return ur}ge.isUnifiedPlan=R;function A(){return ge.browserName()==="Opera"&&ge.os()==="Windows"}ge.isBrokenH264=A;function O(){return!(ge.baseChromeVersion()&&ge.isMobile())}ge.canPreferH264=O;function $(){return Di||(Di=(()=>{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 X in L)if(L.hasOwnProperty(X)&&L[X].test(Te))return X;return"Unknown"})()),Di}ge.os=$;function M(){return Ai===null&&(Ai=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(hr)),Ai}ge.isMobile=M;function Re(){return Mi()[0]}ge.browserName=Re;function E(){return Mi()[1]}ge.browserVersion=E;function Ee(){return Mi()[3]}ge.baseChromeVersion=Ee;function Ne(){return Oi||(Oi=new(window.AudioContext||window.webkitAudioContext)),Oi}ge.getAudioContext=Ne})(qe||(qe={}));var y=qe;function gr(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.name===t.name&&i.source===t.source))return!1;return!0}function ve(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}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(P).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,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 oe;(function(i){i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS"})(oe||(oe={}));var J;(function(i){i.audio="audio",i.video="video",i.screen="screen"})(J||(J={}));var wi=class extends z{constructor(){super();this._stream=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=[re.AUDIO]){if(this._stream)return;let t=e.includes(re.VIDEO),i=e.includes(re.AUDIO);if(!y.isBrowserSupported())throw new N(se.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=C.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(),_=p&&p.groupId;if(!c&&!_)return;let b=yield navigator.mediaDevices.enumerateDevices();!e&&c&&(e=!b.find(k=>k.groupId===c)),!t&&_&&(t=!b.find(k=>k.groupId===_)),i()}))}_changeVideoInput(e=null){return s(this,null,function*(){try{let t=e?"stream":"video";if(e=e||(yield y.getUserVideo(void 0,!!this._effect)),!this._stream)e.getTracks().forEach(i=>i.stop());else{this._disableScreenCapture();let i=yield this._videoEffect(this._effect,e.getVideoTracks()[0]);this._stopLocalTrack(J.video),u.log(m.DEVICE_CHANGED,t),o.log("Video stream changed"),yield this._replaceLocalTrack(i),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.video,mediaSettings:this._mediaSettings})}}catch(t){throw u.log(m.ERROR,"change_video"),o.warn("Camera change failed",t),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(J.audio),u.log(m.DEVICE_CHANGED,"audio"),o.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.audio,mediaSettings:this._mediaSettings})}}catch(t){throw u.log(m.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=yield this._videoEffect(null,e.getVideoTracks()[0]);u.log(m.DEVICE_CHANGED,"screen"),o.log("Screen capturing started"),this._screenTrack=t,this._mediaSettings.isScreenSharingEnabled=!0,d.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack(J.video),this._sendVideoTrack=d.consumerScreenDataChannel?y.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight):t,yield this._replaceLocalTrack(t,this._sendVideoTrack)),this._triggerEvent(oe.SCREEN_STATUS,{track:t,mediaSettings:this._mediaSettings}),this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.screen,mediaSettings:this._mediaSettings})}}catch(t){throw u.log(m.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(oe.SCREEN_STATUS,{mediaSettings:this._mediaSettings}),this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.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(oe.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(m.DEVICE_CHANGED,`effect_${e}`),d.videoEffects.setEffect(e,t)}catch(i){return o.warn("Video effect failed",i),t}})}destroy(){d.videoEffects&&(this._effect=null,d.videoEffects.stopEffect()),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),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;e?(t=(yield y.getUserVideo(void 0,!!this._effect)).getVideoTracks()[0],t=yield this._videoEffect(this._effect,t)):(t=y.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight),t=yield this._videoEffect(null,t)),this._stopLocalTrack(J.video),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.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(J.audio),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent(oe.SOURCE_CHANGED,{kind:J.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)return i.applyConstraints({width:{ideal:e},height:{ideal:t}})})}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()})}};var ki;(function(Oe){function a(R,A,O,$,M=!1){let Re=/[\r\n]+/,E=`\r
7
+ `;if(!A&&!O&&!$)return M?Ee(R.split(Re)).join(E):R;function Ee(H){let g=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],me="a=rtcp-fb:111",ce=H.findIndex(ee=>ee.startsWith(me));return~ce&&(H[ce]=H[ce]+E+g.join(E)),H}function Ne(H,g,me){let ce=H.split(" "),ee=ce.slice(0,3),pe;for(pe=3;pe<ce.length;pe++)me.includes(ce[pe])&&ee.push(ce[pe]);for(pe=3;pe<ce.length;pe++)!me.includes(ce[pe])&&!g.includes(ce[pe])&&ee.push(ce[pe]);return ee.join(" ")}function ge(H,g){let me=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),ce,ee=[];for(ce=0;ce<H.length;++ce){let pe=H[ce].match(me);pe&&pe.length===3&&pe[2]===g&&ee.push(pe[1])}return ee}function L(H,g,me,ce){let ee,pe="m="+g;for(ee=0;ee<H.length;++ee)if(H[ee].startsWith(pe)){H[ee]=Ne(H[ee],me,ce);break}}let X=[],h=R.split(Re);(O||A)&&(X=ge(h,"H264"));let Z=[];if($&&(Z=ge(h,"VP9")),O){let H=X.slice(0),g=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),me;for(me=0;me<h.length;++me){let ee=h[me].match(g);ee&&ee.length===3&&H.includes(ee[2])&&H.push(ee[1])}let ce=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(me=h.length;me--;){let ee=h[me].match(ce);ee&&ee.length===3&&H.includes(ee[2])&&h.splice(me,1)}L(h,"video",H,[])}else A&&L(h,"video",[],X);return $&&L(h,"video",[],Z),M&&Ee(h),h.join(E)}Oe.patchSDP=a;function e(R){return R?`${R.type||"WEB_SOCKET"}_${R.id}`:"_"}Oe.getPeerIdString=e;function t(R,A){return R&&R.id===A.id&&(R.type||"WEB_SOCKET")===(A.type||"WEB_SOCKET")}Oe.comparePeerId=t;function i(R){return s(this,null,function*(){return!R||!R.getStats?Promise.resolve(null):R.getStats(null).then(A=>{let O=null,$=null;if(A.forEach(M=>{M.type==="transport"&&M.selectedCandidatePairId?$=A.get(M.selectedCandidatePairId):M.type==="candidate-pair"&&M.state==="succeeded"&&!$&&(!M.hasOwnProperty("selected")||M.selected)&&($=M)}),$&&$.localCandidateId){let M=A.get($.localCandidateId);M&&(O={type:M.candidateType,ip:M.ip||M.ipAddress,port:M.port||M.portNumber})}return O}).catch(()=>null)})}Oe.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function c(R,A){let O=String(R);return n.test(O)?(o.warn(`Already composite id [${R}] type supplied [${A}]`),O):A===Q.GROUP?"g"+O:A===Q.USER?"u"+O:(o.warn(`Unknown type [${A}] for id [${R}]`),O.match(r)?"u"+O:O)}Oe.composeId=c;function l(R){return c(R.id,R.idType||Q.USER)}Oe.composeParticipantId=l;function p(R){return R.participant?l(R.participant):c(R.participantId,R.participantType||Q.USER)}Oe.composeMessageId=p;function _(R){let A=String(R),O=A.match(n);return O?{id:Number(O[2]),type:O[1]==="g"?Q.GROUP:Q.USER}:(o.warn(`Unsupported compositeId [${R}]`),{id:Number(A),type:Q.USER})}Oe.decomposeId=_;function b(){let R="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),A=new Array(36),O=0,$,M;for(M=0;M<36;M++)M===8||M===13||M===18||M===23?A[M]="-":M===14?A[M]="4":(O<=2&&(O=33554432+Math.random()*16777216|0),$=O&15,O=O>>4,A[M]=R[M===19?$&3|8:$]);return A.join("")}Oe.uuid=b;function k(R,A){let O;function $(){let M=this,Re=arguments;O&&window.clearTimeout(O),O=window.setTimeout(()=>{R.apply(M,Re)},A)}return $}Oe.throttle=k;function K(R){let A="",O=R.split(`
8
+ `);for(let E of O)if(E.startsWith("a=fingerprint")){let Ee=E.split(" ");if(Ee.length===2){A=Ee[1];break}}if(!A)return at.default.minusOne;let $=A.split(":"),M=at.default.zero;for(let E=Math.min(7,$.length-1);E>=0;E--){let Ee=(0,at.default)($[E],16);M=M.shiftLeft(8).or(Ee)}return((E,Ee)=>{let Ne=Ee.value;if(typeof Ne=="bigint")return(0,at.default)(BigInt.asIntN(E,Ne));let ge=at.default.one.shiftLeft(E),L=Ee.and(ge.subtract(1));return L.greaterOrEquals(ge.subtract(L))?L.subtract(ge):L})(64,M)}Oe.sdpFingerprint=K;function ne(R){return s(this,null,function*(){return new Promise(A=>window.setTimeout(A,R))})}Oe.delay=ne;function T(R,A,O){let $=[];return R.getSenders().forEach(M=>_e(A,M,M.track,O,$)),$}Oe.applySettings=T;function _e(R,A,O,$,M){if(R&&O&&O.kind===J.video){let Re=O.getSettings();if(Re){let E=R.maxBitrateK?R.maxBitrateK*1024:null,Ee=Re.width,Ne=Re.height,ge=Ee&&Ne&&R.maxDimension?Math.max(1,Math.max(Ee,Ne)/R.maxDimension):null,L=R.maxFramerate?R.maxFramerate:null,X=R.degradationPreference?R.degradationPreference:"balanced",h=$[O.id];if(h&&h.bitrate===E&&h.scaleResolutionDownBy===ge&&h.maxFramerate===L&&h.degradationPreference===X){M[O.id]=h;return}M[O.id]={bitrate:E,scaleResolutionDownBy:ge,maxFramerate:L,degradationPreference:X};let Z=A.getParameters();Z.encodings||(Z.encodings=[{}]),Z.encodings.forEach(H=>{E?H.maxBitrate=E:delete H.maxBitrate,ge?H.scaleResolutionDownBy=ge:delete H.scaleResolutionDownBy,L?H.maxFramerate=L:delete H.maxFramerate}),Z.degradationPreference=X,A.setParameters(Z)}}}Oe.applyVideoTrackSettings=_e;function ke(R,A){Array.isArray(A)||(A=[A]);for(let O of A)if(R.includes(O))return!0;return!1}Oe.includesOneOf=ke;function he(R){var A;return Object.entries(((A=R.participantState)==null?void 0:A.state)||{}).reduce((O,[$,M])=>(R.participantState&&(O[$]={ts:R.participantState.stateUpdateTs[$],state:M}),O),{})}Oe.mapParticipantState=he;function F(R){return Object.entries(R).reduce((A,[O,{state:$}])=>(A[O]=$,A),{})}Oe.mapLegacyParticipantState=F;function le(R){return R.map(A=>{let O={uid:A.externalId,mediaSettings:A.mediaSettings,status:A.status};return d.participantStateMapped&&(O.participantState=A.participantState),O})}Oe.mapSharedParticipants=le;function De(R,A){let O=Object.keys(R),$=Object.keys(A);if(O.length!==$.length)return!1;for(let M of O)if(!$.hasOwnProperty(M)||R[M].state!==A[M].state||R[M].ts!==A[M].ts)return!1;return!0}Oe.isEqualParticipantState=De})(ki||(ki={}));var C=ki;var Pe;(function(i){i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP"})(Pe||(Pe={}));var ie;(function(l){function a(p){return p.length?typeof p[0]=="object"?p:p.map(_=>e(_)):[]}l.fromIds=a;function e(p,_=Pe.USER){return{id:p,type:_}}l.fromId=e;function t(p){return{id:p.id,type:p.type==="ANONYM"?Pe.ANONYM:Pe.USER}}l.fromSignaling=t;function i(p){return`{"id":"${p.id}","type":"${p.type}"}`}l.toString=i;function r(p,_=Pe.USER){return i(e(p,_))}l.fromIdToString=r;function n(p){try{return JSON.parse(p)}catch(_){throw new Error(`Failed to parse ExternalId from string '${p}'`)}}l.fromString=n;function c(p,_){return p.id===_.id&&p.type===_.type}l.compare=c})(ie||(ie={}));var Ce;(function(r){r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE"})(Ce||(Ce={}));var Ni=":",fr="s",Sr="m";function Je(a){return a.participantId+(a.mediaType?Ni+fr+a.mediaType:"")+(a.streamName?Ni+Sr+a.streamName:"")}function vt(a){let e=a.split(Ni),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 fr:i.mediaType=Ca(r.slice(1));break;case Sr:i.streamName=r.slice(1);break;default:throw new Error("Unexpected parameter type "+r.charAt(0)+" in stream description "+a)}return i}function Ca(a){for(let e of Object.keys(Ce))if(e===a)return Ce[e];return null}function xi(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 Ft(a,e){return!(!xi(a.camera,e.camera)||!xi(a.screenSharing,e.screenSharing))}function Li(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function vr(a){return{camera:Object.assign({},a.camera),screenSharing:Object.assign({},a.screenSharing)}}function Er(a){try{return btoa(JSON.stringify(a))}catch(e){o.warn("WaitingParticipant: failed convert to string",a,e)}return null}function Ir(a){try{return JSON.parse(atob(a))}catch(e){o.warn("WaitingParticipant: failed convert from string",a,e)}return null}var Et=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(m.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,u.log(m.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(m.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),u.log(m.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===J.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Gt=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 n;if(!((n=this._output)==null?void 0:n.audioTrack))return;let e=new Audio;e.muted=!1,e.volume=this._volume,e.preload="auto";let t=()=>{o.warn("Error on play audio"),S.onAutoplayError()},i=c=>{e.srcObject=new MediaStream([c]),e.load();let l=e.play();l?l.catch(t):t()},r=()=>{var l;o.debug("Recover audio playback");let c=(l=this._output)==null?void 0:l.audioTrack;c?i(c):o.warn("Broken audio track")};e.onpause=r,e.onstalled=r,e.onerror=r,i(this._output.audioTrack),this._output.audioElement=e}_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(m.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var Ta=90,Ra=3,Ht=class extends z{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),S.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>Ta?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Ra)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var ya=44100,It=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=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=ya/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 Wt=class extends z{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&S.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,d.voiceParams.interval)};this._interval=window.setTimeout(t,d.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,oe.SOURCE_CHANGED,r=>{r.kind===J.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new It("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var Pa=1e3;function Ue(a,e,t=0){return e in a&&a[e]?a[e]:t}function Cr(...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 ba(a){return(e,t)=>e[a]-t[a]}function jt(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function Aa(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Da(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Ui(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=Da(t[1])?Ui(t[1]):t[1],e),{})}function Oa(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function Ma(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(Oa).then(Aa)})}function wa(a){let e=a.filter(We("type","candidate-pair")).sort(ba("priority")).find(Cr(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}})),Ui(t)}function ka(a,e){let t=jt("id",a),i=a.filter(Cr(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=jt("trackIdentifier",n)}return i.map(n=>{let c=Number(n.ssrc),l=n.mediaType||n.kind,p=n.trackId,_=n.type,b=n.codecId;if(y.browserName()==="Safari"){let K=/^.+_([\d]+)$/.exec(n.id);if(K&&(c=parseInt(K[1],10)),l=n.id.indexOf("Audio")>0?"audio":"video",e[c]){let ne=l+"-"+e[c];r[ne]&&(p=r[ne].id)}}if(!_||!c||!l)return null;let k={ssrc:c,type:_,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(b&&t[b]){let K=t[b];k.clockRate=K.clockRate,k.mimeType=K.mimeType}if(p&&t[p]){let K=t[p];k.frameHeight=K.frameHeight,k.frameWidth=K.frameWidth,k.framesDecoded=K.framesDecoded,k.framesReceived=K.framesReceived,k.framesDropped=K.framesDropped}return Ui(k)}).filter(n=>!!n)}function Na(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=jt("ssrc",a.rtps),i=jt("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,_=c.packetsReceived-l.packetsReceived;c.packetLoss=parseFloat((100*p/(p+_)).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 Ct(i,r){return s(this,arguments,function*(a,e,t={}){let n=yield Ma(a),c={timestamp:Date.now(),transport:wa(n),rtps:ka(n,t)};return e?Na(c,e):(yield C.delay(Pa),Ct(a,c,t))})}var Kt=.8,Ye=class extends z{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=D.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,oe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,oe.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(m.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===D.IDLE?this._failedOnCreate=c:this.close(c)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==D.IDLE&&e!==D.CLOSED&&e!==D.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(m.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(D.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(f.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Ft(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(f.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(D.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(D.CLOSED)),this._triggerEvent(f.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(f.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=C.getPeerIdString(e.peerId);C.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(m.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(m.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(f.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(f.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===D.IDLE||e===D.OPENED?this._setState(D.CONNECTING):this._setState(D.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),u.log(m.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(D.CONNECTED),this._stopReconnection(),C.getPeerConnectionHostInfo(this._pc).then(e=>{e&&u.log(m.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(D.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(j.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(u.log(m.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(m.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(m.ERROR,"createOffer-direct"),i}).then(i=>s(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=Ye._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(m.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(m.ERROR,"createAnswer-direct"),e}).then(e=>s(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=Ye._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(m.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=C.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(m.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Ct(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:j.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:j.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(f.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-Kt)+r*Kt,loss:this._lastNetworkStat.loss*(1-Kt)+n*Kt},l=i(c),p=t(c),_=i(this._remoteNetworkStat),b=t(this._remoteNetworkStat),k=i(this._lastNetworkStat),K=t(this._lastNetworkStat),_e=l||_?.2:p&&b?1:0,ke=Date.now();if((k!==l||K!==p||ke-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)})),_e){let he={};he[this._participantId]=he[""]=_e,this._triggerEvent(f.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=C.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(S.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=C.applySettings(this._pc,e,this._prevConsumerSettings))}};var Vi;(function(r){r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare"})(Vi||(Vi={}));var Tt=Vi;var Qe=pt(require("messagepack"));var Bi=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,Qe.decode)(r);return Object.entries(l).forEach(([T,_e])=>{let ke=vt(T);this.streamDescriptionByCompactId.set(_e,ke)}),null;case 2:case 4:let p=(0,Qe.decode)(r),_=[];for(let T of p){let _e=this.getStreamDescription(T);_e&&_.push(_e.participantId)}return i===2?{type:"notification",notification:w.AUDIO_ACTIVITY,activeParticipants:_}:{type:"notification",notification:w.STALLED_ACTIVITY,stalledParticipants:_};case 3:let b=(0,Qe.decode)(r);return{type:"notification",notification:w.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(b))==null?void 0:n.participantId};case 5:let k=(0,Qe.decode)(r);return{type:"notification",notification:w.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:k[0],maxDimension:k[1]}};case 6:let K=(0,Qe.decode)(r),ne={};for(let[T,_e]of Object.entries(K)){let ke=(c=this.getStreamDescription(Number(T)))==null?void 0:c.participantId;ke&&(ne[ke]=_e/100)}return{type:"notification",notification:w.NETWORK_STATUS,statuses:ne};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],l=n[1],p=n[2],_;if(c!==null){if(_=this.getStreamDescription(c),!_){o.error(`could not uncompress participant ID ${c}`);continue}}else _=null;if(p===null){o.error("unexpected null sequenceNumber",r,n);continue}let b=Me.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,k=l?l>>>0:null;i.push({participantStreamDescription:_,streamId:b,rtpTimestamp:k,sequenceNumber:p})}return{type:"notification",notification:w.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Fi=pt(require("@vkontakte/libvpx"));var Tr;(function(t){t.VP9="vp09.00.50.08",t.VP8="vp8"})(Tr||(Tr={}));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 Ve=class{constructor(){this._worker=null}_createWorker(c,l){return s(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((p,_)=>{let b=i.join(","),k=new Blob([e,`exports.default(${b});`],{type:"application/javascript; charset=utf-8"}),K=window.URL.createObjectURL(k);this._worker=new Worker(K),this._worker.onmessage=ne=>{switch(ne.data.type){case fe.READY:p();break;case fe.ERROR:_(ne.data.error);break;case fe.FRAME:t(ne.data);break;case fe.DEBUG:o.debug(ne.data.message);break;case fe.LOG_ERROR:u.log(m.ERROR,ne.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 Ve{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)},[Fi.default,Fi.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 ze=class extends Ve{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 xa=65536,$t=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,ze.isBrowserSupported()?this._decoder=new ze: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)%xa!==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 qt=1,La=1,Rr=0,yr=11,Pr=1,br=2,Ar=4,Dr=8;function Or(a,e,t,i,r,n,c){let l=0;e&&(l|=Pr),t&&(l|=br),i&&(l|=Ar),c||(l|=Dr);let p=new ArrayBuffer(yr),_=new DataView(p);if(_.setUint8(0,qt),_.setUint16(1,r),_.setUint32(3,a),_.setUint8(7,n?1:0),_.setUint16(8,Rr),_.setUint8(10,l),!c)return p;let b=new Uint8Array(p.byteLength+c.byteLength);return b.set(new Uint8Array(p),0),b.set(new Uint8Array(c),p.byteLength),b.buffer}function Mr(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&Pr),_=!!(l&br),b=!!(l&Ar),k=!!(l&Dr);if(t!==qt)throw new Error(`Unexpected protocol version. Got ${t}, expected ${qt}`);return{timestamp:r,start:p,end:_,keyframe:b,sequence:i,isVP9:n,ssrc:c,eos:k,data:a.slice(yr)}}function wr(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==qt||e.getUint8(1)!==La||e.getUint16(2)!==Rr)}var Rt=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=Mr(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 $t(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(ze.isBrowserSupported()||nt.isBrowserSupported())&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var Gi=pt(require("@vkontakte/libvpx"));var Ua=1e3,yt=class extends Ve{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;})();
9
9
  `,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})},[Gi.default,Gi.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)},Ua),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 st=class extends Ve{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;})();
10
- `,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 Va=16*1024,Ba=11,kr=Va-Ba,Fa=65536,Hi=0,yt=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())}};st.isBrowserSupported()?this._encoder=new st(e,i):this._encoder=new Rt(e,i),this._datachannel.onmessage=r=>{wr(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=Or(e,t,i,r,Hi,this._encoder.isVP9(),n);return Hi=(Hi+1)%Fa,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+kr),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+kr,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 st.isBrowserSupported()||Rt.isBrowserSupported()}};var Nr="videochat-epi",Pt=class extends Q{constructor(e,t){super();this._previousTimestamp=0;this._signaling=t,this.subscribe(e,f.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Nr)||"",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(Nr,r.estimatedPerformanceIndex)}catch(r){}this._previousTimestamp=i}})}};var Ga=90,Ha=4294967295,be=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=D.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,oe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,oe.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,oe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Pt(this,e),this._serverSettings=i,d.consumerScreenDataChannel&&!yt.isBrowserSupported()&&(d.consumerScreenDataChannel=!1),d.producerScreenDataChannel&&!Tt.isBrowserSupported()&&(d.producerScreenDataChannel=!1),o.debug("ServerTransport: Created")}getState(){return this._state||D.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==D.IDLE&&e!==D.CLOSED&&e!==D.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(D.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(D.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Ft(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,be._closeDataChannel(this._producerNotification),be._closeDataChannel(this._producerCommand),be._closeDataChannel(this._producerScreen),be._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(f.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=be._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=C.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=be._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,Ct.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Bi,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,Ct.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,Ct.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(m.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,Ct.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(D.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==D.OPENED&&(this._setState(D.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(f.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(f.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(f.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(f.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
11
- `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Me.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 yt(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!d.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new Tt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(f.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(f.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!==J.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)})}C.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(f.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 It(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(f.REMOTE_DATA_STATS,{inbound:{topology:j.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:j.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=Me.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(f.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:be._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(m.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(m.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=C.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(m.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(m.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(f.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(f.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(m.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===D.IDLE||i===D.OPENED?this._setState(D.CONNECTING):e.iceConnectionState==="checking"&&this._setState(D.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(D.RECONNECTING);break;case"connected":this._setState(D.CONNECTED),C.getPeerConnectionHostInfo(e).then(r=>{r&&u.log(m.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(m.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(m.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(m.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(m.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&Ha,p=Math.ceil(l/Ga);return Math.min(100,Math.max(0,p))}};var f;(function(T){T.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",T.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",T.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",T.REMOTE_ALL_STALL="REMOTE_ALL_STALL",T.REMOTE_DATA_STATS="REMOTE_DATA_STATS",T.STATE_CHANGED="STATE_CHANGED",T.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",T.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",T.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",T.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",T.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",T.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",T.NETWORK_STATUS="NETWORK_STATUS",T.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED"})(f||(f={}));var D;(function(l){l.IDLE="IDLE",l.OPENED="OPENED",l.CONNECTING="CONNECTING",l.RECONNECTING="RECONNECTING",l.CONNECTED="CONNECTED",l.CLOSED="CLOSED",l.FAILED="FAILED"})(D||(D={}));var j;(function(t){t.DIRECT="DIRECT",t.SERVER="SERVER"})(j||(j={}));var Wi=class extends Q{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState=D.IDLE;this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),e===j.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===j.DIRECT&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology===j.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===j.DIRECT&&this._directTransport&&this._directTransport.open(t),this._topology===j.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===j.DIRECT&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology===j.SERVER&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,D.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(f.STATE_CHANGED,i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent(f.STATE_CHANGED,[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent(f.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(m.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology===j.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===j.DIRECT){let i=e.offerTo||[],r=e.offerToTypes||[],n=i.length&&r.length?C.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(f.TOPOLOGY_CHANGED,this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new Ye(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(f.REMOTE_TRACK_ADDED,this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener(f.REMOTE_TRACK_REMOVED,this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener(f.REMOTE_DATA_STATS,this._onDirectRemoteDataStats.bind(this)),i.addEventListener(f.STATE_CHANGED,this._onDirectTransportChanged.bind(this,e)),i.addEventListener(f.NETWORK_STATUS,this._onTransportNetworkStatus.bind(this)),i.addEventListener(f.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this,j.DIRECT))),i}_createServerTransport(){let e=new be(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(f.REMOTE_TRACK_ADDED,this._onServerRemoteTrackAdded.bind(this)),e.addEventListener(f.REMOTE_TRACK_REMOVED,this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener(f.REMOTE_ALL_STALL,this._onServerRemoteAllStall.bind(this)),e.addEventListener(f.REMOTE_DATA_STATS,this._onServerRemoteDataStats.bind(this)),e.addEventListener(f.STATE_CHANGED,this._onServerTransportChanged.bind(this)),e.addEventListener(f.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener(f.SIGNALLED_ACTIVE_PARTICIPANTS,this._onTransportActiveParticipants.bind(this)),e.addEventListener(f.SIGNALLED_SPEAKER_CHANGED,this._onTransportSpeakerChanged.bind(this)),e.addEventListener(f.SIGNALLED_STALLED_PARTICIPANTS,this._onTransportStalledParticipants.bind(this)),e.addEventListener(f.NETWORK_STATUS,this._onTransportNetworkStatus.bind(this)),e.addEventListener(f.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),e.addEventListener(f.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this,j.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===D.CONNECTED&&this._topology===j.DIRECT&&this._releaseServerTransport(!0),(t===D.CLOSED||t===D.FAILED)&&(this._releaseDirectTransport(!1),this._topology===j.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===j.DIRECT&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e===D.CONNECTED&&this._topology===j.SERVER&&this._releaseDirectTransport(!0),(e===D.CLOSED||e===D.FAILED)&&(this._releaseServerTransport(!1),this._topology===j.SERVER&&(this._allocated=[],this._opened=[])),this._topology===j.SERVER&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent(f.ACTIVE_PARTICIPANTS_NO_SIGNAL)}_onTransportActiveParticipants(e){this._topology===j.SERVER&&this._triggerEvent(f.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_onTransportStalledParticipants(e){this._topology===j.SERVER&&this._triggerEvent(f.SIGNALLED_STALLED_PARTICIPANTS,e)}_onTransportSpeakerChanged(e){this._topology===j.SERVER&&this._triggerEvent(f.SIGNALLED_SPEAKER_CHANGED,e)}_onTransportNetworkStatus(e){this._triggerEvent(f.NETWORK_STATUS,e)}_onRemoteStreamSecond(e,t){this._triggerEvent(f.REMOTE_STREAM_SECOND,e,t)}_onPeerConnectionClosed(e){this._triggerEvent(f.PEER_CONNECTION_CLOSED,e)}_onServerRemoteAllStall(e){this._topology===j.SERVER&&this._triggerEvent(f.REMOTE_ALL_STALL,e)}_onServerRemoteDataStats(e){this._triggerEvent(f.REMOTE_DATA_STATS,e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent(f.REMOTE_TRACK_ADDED,e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent(f.REMOTE_TRACK_REMOVED,e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent(f.REMOTE_DATA_STATS,e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent(f.REMOTE_TRACK_ADDED,e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent(f.REMOTE_TRACK_REMOVED,e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!==j.SERVER?(u.log(m.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(m.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Fe;(function(e){e.VOLUMES_DETECTED="VOLUMES_DETECTED"})(Fe||(Fe={}));var ji=class extends Q{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,f.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,f.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,f.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,f.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===J.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Et(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===J.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===Me.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent(Fe.VOLUMES_DETECTED,e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var ot;(function(e){e.SPEAKER_CHANGED="SPEAKER_CHANGED"})(ot||(ot={}));var Ki=class extends Q{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,Fe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,f.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,f.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,f.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(ot.SPEAKER_CHANGED,i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent(ot.SPEAKER_CHANGED,e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var Jt=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,f.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,Fe.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===D.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===D.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),u.log(m.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!==D.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),u.log(m.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(m.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Wa=1e3,ja=12e4,Y;(function(r){r.IDLE="IDLE",r.PROCESSING="PROCESSING",r.ACTIVE="ACTIVE",r.CLOSE="CLOSE"})(Y||(Y={}));var B=class extends Q{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state=Y.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;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 Gt,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Wa))}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(m.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new N(P.FAILED);B._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let l=this._mediaSource.getMediaSettings();t===xe.CHAT||e.length>1?this._logWithMediaSettings(m.OUTGOING_MULTIPARTY_CALL,l):this._logWithMediaSettings(m.OUTGOING_CALL,l);let p=yield this._startConversation(e,t,Be.OUTGOING,i,r,n,c);if(!this._conversation)throw new N(P.UNKNOWN_ERROR);if(this._participantState=W.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(P.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let _=Object.values(this._participants),b;return d.batchParticipantsOnStart&&(b=C.mapSharedParticipants(_)),S.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),S.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,b),S.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),B._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(_,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(m.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new N(P.FAILED);B._activationMutex=!0,this._state=Y.PROCESSING;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(m.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new N(P.UNKNOWN_ERROR);return S.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(o.log("In waiting hall"),B._current=this,B._activationMutex=!1,this._signaling.readyToSend(),S.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=W.ACCEPTED,!this._conversation||!this._mediaSource)throw new N(P.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(P.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=C.mapSharedParticipants(t)),S.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,i),S.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state=Y.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(P.REJECTED);B._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new N(P.UNKNOWN_ERROR);if(!n.conversation.participants.find(l=>{var p;return l.state===W.CALLED&&l.id===((p=this._conversation)==null?void 0:p.userId)}))throw o.log("Push rejected (there is an active call)"),u.log(m.PUSH,"rejected"),new N(P.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),u.log(m.PUSH,"accepted"),B._current=this,B._delayedHangup)throw new N(P.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(Ot.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>C.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return s(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new N(P.UNKNOWN_ERROR);this._state=Y.PROCESSING;let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(m.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),S.onCallAccepted(),this._state=Y.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!==Y.IDLE)throw u.log(m.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(P.UNKNOWN_ERROR);this._state=Y.PROCESSING,o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(m.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=W.ACCEPTED;let i=Object.values(this._participants),r;return d.batchParticipantsOnStart&&(r=C.mapSharedParticipants(i)),S.onCallAccepted(),S.onLocalStream(this._mediaSource.getStream(),t),S.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,r),S.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),(this._conversation.muteState===ye.MUTE||this._conversation.muteState===ye.MUTE_PERMANENT)&&(yield this._processMuteState()),this._state=Y.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!==Y.IDLE)throw u.log(m.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state=Y.PROCESSING,o.debug("Decline incoming call"),this._logWithMediaSettings(m.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=W.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(P.REJECTED)),this._close(new N(P.REJECTED))})}hangup(){return s(this,null,function*(){o.debug("Hangup");let e=this._state===Y.ACTIVE?P.HUNGUP:P.CANCELED;u.log(m.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new N(e))):S.onHangup(new N(P.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return s(this,null,function*(){if(!this._signaling.ready){this._close(new N(P.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=P.UNKNOWN_ERROR),yield this._onAddParticipant(e,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(P.FAILED):u.log(m.ERROR,e.hangup),B._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([P.CANCELED,P.NOT_FRIENDS,P.CALLEE_IS_OFFLINE,P.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===P.REJECTED&&!e.remote){S.onHangup(e,i),this.destroy();return}if(e.hangup===P.HUNGUP&&(!e.remote||this._participantState===W.CALLED)){S.onHangup(e,i),this.destroy();return}if(e.hangup===P.MISSED&&!e.remote){S.onHangup(e,i),this.destroy();return}if(e.hangup===P.SOCKET_CLOSED&&B._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===P.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state=Y.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,B._current=null,B._delayedHangup=!1,S.onHangup(e||new N(P.UNKNOWN_ERROR),i)}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}_getConversationParams(){return s(this,null,function*(){let e=yield this._api.getConversationParams();o.debug("Api.getConversationParams",e);let t=[],{turn_server:i,stun_server:r}=e;if(r&&t.push(r),i){let n=i.urls.filter((c,l,p)=>p.indexOf(c)===l);n.forEach(c=>n.push(`${c}?transport=tcp`)),t.push({urls:n,username:i.username,credential:i.credential})}d.iceServers=t,d.wssBase=e.endpoint,d.wssToken=e.token,e.client_type&&(d.clientType=e.client_type)})}_startConversation(e,t,i,r,n="",c=!1,l=!1){return s(this,null,function*(){let p=C.uuid();o.debug("Conversation: start",{conversationId:p,opponentIds:e,opponentType:t,direction:i});let _=r.includes(ie.VIDEO),b=yield this._api.startConversation(p,e,t,_,n,c,l);o.debug("Api.startConversation",b),yield this._getConversationParams();let k=yield this._connectSignaling(Le.START,b);return yield this._setConversation(b,k,i),k})}_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(ie.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(P.UNKNOWN_ERROR);o.debug("Api.joinConversation",l),yield this._getConversationParams();let p=yield this._connectSignaling(Le.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();let n=this._api.getUserId();if(!n)throw new N(P.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(Le.ACCEPT,c);return B._current&&(B._current._participantState===W.ACCEPTED||B._current._participantState===W.CALLED)?(o.log("Push rejected (busy)"),u.log(m.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(P.BUSY),Promise.reject({hangup:P.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:Ie(),participantState:{},state:W.CALLED,status:d.batchParticipantsOnStart?q.WAITING:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{}},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(P.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(K=>K.id);yield this._api.prepareUserIds(p);let _=this._api.getUserId();if(!_){let K=(t.conversation.participants||[]).find(ne=>C.comparePeerId(ne.peerId,t.peerId));if(!K)throw new N(P.UNKNOWN_ERROR);_=Number(K.id),K.idType&&(r=K.idType),this._api.setUserId(_)}let b=C.composeId(_,r),k=yield this._getUserId(b);this._conversation={userId:_,compositeUserId:b,externalId:k,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||j.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:[],muteState:ye.UNMUTE,muteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),u.log(m.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new N(P.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||j.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 wi;return this.subscribe(e,oe.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,oe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new vt(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=C.composeParticipantId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),S.onLocalRolesChanged(this._conversation.roles));continue}if(t.state===W.HUNGUP||t.state===W.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],P.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&re.fromSignaling(t.externalId),mediaSettings:Ie(t.mediaSettings),participantState:C.mapParticipantState(t),state:t.state,roles:t.roles||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),S.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){e.muteOptions&&(e.muteState===ye.MUTE||e.muteState===ye.MUTE_PERMANENT)&&this._onMuteParticipant(e.muteOptions,!1,e.muteState),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 Wi(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new Ht,this.subscribe(this._transport,f.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,f.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,f.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,f.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,f.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,f.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,f.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,f.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,f.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,f.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,f.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,f.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===W.ACCEPTED||t.state===W.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new ji(this._transport),this.subscribe(this._volumesDetector,Fe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Ki(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,ot.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Wt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Jt(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(m.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===Y.CLOSE||!this._participants[e.id]||(t===P.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:Ce.CAMERA,stopStream:!0}]),delete this._participants[e.id],S.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(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,window.clearInterval(this._cooldownQueueCleanupTimer)}_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){return s(this,null,function*(){o.debug(`Add new participant [${e}]`);let i=this._participants[e];if(i&&(i.state===W.ACCEPTED||i.state===W.CALLED)){o.warn(`Participant [${i.id}:${i.state}] is already in conversation`);return}i||(this._participants[e]=yield this._createParticipant({id:e}),i=this._participants[e]),this._setParticipantsStatus([i],q.WAITING),t?(i.state=W.HUNGUP,this._removeParticipant(i,t)):this._transport&&(i.state=W.CALLED,this._transport.allocate(i.id,!0),u.log(m.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(m.REMOVE_PARTICIPANT)}changeDevice(e){return s(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new vt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(se.UNKNOWN)})}toggleScreenCapturing(e){return s(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(se.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(m.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return s(this,null,function*(){if(this._mediaSource)return u.log(m.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:re.fromId(r.uid),c=re.toString(n);i[c]=r.priority}for(let r of Object.values(this._participants)){let n=re.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:re.fromId(r.uid),c=re.toString(n),l=this._api.getCachedOkIdByExternalId(n);if(!l){o.log(`Unknown participant external ID ${c}`);continue}let p=Je({participantId:l,mediaType:r.mediaType,streamName:r.streamName}),_=this._participants[l];_&&(_.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=St(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Ce.STREAM||i.mediaType===Ce.SCREEN)?S.onRemoteLive(r.externalId,i.streamName,null):S.onRemoteStream(r.externalId,null),u.log(m.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=St(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=rr.UNKNOWN_ERROR):p=ar(n),i.push({externalId:l.externalId,errorReason:p})}}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]+ja>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(P.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=re.fromSignaling(l.externalId);n.push(p),this._api.cacheExternalId(l.id.id,p)}else c.push(C.decomposeId(l.id.id).id)}),c.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(c))),S.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var l,p;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===Ce.SCREEN)return;let i=Je(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(m.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 _=t.participantId,b=this._participants[_];if(!b){u.log(m.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${_}`);return}let k=this._streamByStreamId.get(n);if(!k){u.log(m.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}u.log(m.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let K=(l=e.participantStreamDescription)==null?void 0:l.mediaType;if(K===Ce.STREAM||K===Ce.MOVIE)((p=e.participantStreamDescription)==null?void 0:p.streamName)&&S.onRemoteLive(b.externalId,e.participantStreamDescription.streamName,k);else{let ne=(d.producerScreenTrack?null:b.secondStream)||k;S.onRemoteStream(b.externalId,ne)}}else{o.debug(`Waiting for ${c} until stream ${n} for ${i} is switched`);let _=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),c);this._streamWaitTimerByStreamDescription.set(i,_)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Je(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Je(i)))return i}else{let i={participantId:t,mediaType:Ce.CAMERA};if(this._streamIdByStreamDescription.has(Je(i)))return i;let r={participantId:t,mediaType:Ce.SCREEN};if(this._streamIdByStreamDescription.has(Je(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?C.includesOneOf(this._conversation.roles,[je.ADMIN,je.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!C.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)})}switchParticipantDevice(e=null,t,i,r=!1){return s(this,null,function*(){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i,r)})}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=ir(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=Ir(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let c=n.participants||[],l=[],p=[],_=null;return c.length&&(c.forEach(b=>{if(b.externalId){let k=re.fromSignaling(b.externalId);l.push(k),this._api.cacheExternalId(b.id.id,k)}else p.push(C.decomposeId(b.id.id).id)}),p.length&&!l.length&&(l=yield this._api.getExternalIdsByOkIds(p)),n.hasMore&&(_=Er(c[c.length-1].id))),{participants:l,pageMarker:_,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){return s(this,null,function*(){var n;let i={movieId:e,participantId:(n=this._conversation)==null?void 0:n.compositeUserId};(t||t===0)&&(i.gain=t);let r=yield this._signaling.updateMovie(i);if(r.error)throw new Error(r.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){return s(this,null,function*(){var i;if(e<d.videoMinWidth||t<d.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");return d.videoMaxWidth=e,d.videoMaxHeight=t,(i=this._mediaSource)==null?void 0:i.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),S.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;S.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===Y.ACTIVE&&S.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===Y.ACTIVE&&(d.participantStateMapped?S.onRemoteParticipantState(i.externalId,i.participantState):S.onRemoteParticipantState(i.externalId,C.mapLegacyParticipantState(i.participantState))))}_onSignalingNotification(e){var t;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:let i=e.unmute?((t=this._conversation)==null?void 0:t.muteState)||ye.UNMUTE:e.mutePermanent?ye.MUTE_PERMANENT:ye.MUTE;return this._onMuteParticipant(e.mediaOptions||[],e.unmute||!1,i);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=C.composeParticipantId(n),l=n.roles||[];if(c===this._conversation.compositeUserId){t=Ie(n.mediaSettings),ht(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 _=Ie(n.mediaSettings);gr(_,p.mediaSettings)||this._changeRemoteMediaSettings(c,_);let b=C.mapParticipantState(n),k=p.participantState;C.isEqualParticipantState(b,k)||this._changeRemoteParticipantState(c,b),ht(l,p.roles)||this._onRolesChanged(p.id,l)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],P.HUNGUP)}(e.muteState===ye.MUTE||e.muteState===ye.MUTE_PERMANENT)&&this._onMuteParticipant(e.muteOptions,!1,e.muteState,t),e.unmuteOptions&&e.unmuteOptions.length&&this._onMuteParticipant(e.unmuteOptions,!0,e.muteState,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=C.composeMessageId(e),i=C.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new N(P.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:Ie(e.mediaSettings)}),r=this._participants[t]),r.state=W.ACCEPTED,r.mediaSettings=Ie(e.mediaSettings),this._logWithMediaSettings(m.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Be.OUTGOING&&(this._state===Y.IDLE||this._state===Y.PROCESSING)&&(this._state=Y.ACTIVE,this._changeFeatureSet()),this._state===Y.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=C.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===P.REJECTED?W.REJECTED:W.HUNGUP,this._state!==Y.CLOSE&&this._removeParticipant(i,P.HUNGUP)}_onAddedParticipant(e){return s(this,null,function*(){var r,n;o.debug(`Participant added [${e.participantId}]`);let t=C.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&&re.fromSignaling(e.participant.externalId),mediaSettings:Ie(e.participant.mediaSettings),state:e.participant.state,participantState:C.mapParticipantState(e.participant),roles:e.participant.roles||[]}),i=this._participants[t]),i.state=W.CALLED,i.mediaSettings=Ie((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=C.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],q.WAITING),this._state===Y.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=C.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&&re.fromSignaling(e.participant.externalId),mediaSettings:Ie(e.participant.mediaSettings),state:e.participant.state,participantState:C.mapParticipantState(e.participant),roles:e.participant.roles||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Be.OUTGOING&&(this._state===Y.IDLE||this._state===Y.PROCESSING)&&(this._state=Y.ACTIVE,this._changeFeatureSet()),i.state=W.ACCEPTED,i.mediaSettings=Ie(e.mediaSettings),i.participantState=C.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===Y.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=C.composeMessageId(e);this._changeRemoteMediaSettings(t,Ie(e.mediaSettings))}_onParticipantStateChanged(e){let t=C.composeMessageId(e);this._changeRemoteParticipantState(t,C.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),S.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return s(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=Ie(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=Li(this._serverSettings,t),this._signalingServerSettings=vr(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=Li(this._serverSettings,c),o.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=C.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return s(this,null,function*(){S.onDeviceSwitched(ie.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return s(this,null,function*(){let t=C.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),S.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return s(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=C.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),S.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);S.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else S.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!ht(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,S.onLocalRolesChanged(t);return}let i=this._participants[e];i&&!ht(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,S.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t,i,r){return s(this,null,function*(){!this._conversation||(this._conversation.muteOptions=e,!(this._conversation.muteState===i&&!t)&&(this._conversation.muteState=i,yield this._processMuteState(t,r)))})}_processMuteState(e=!1,t){return s(this,null,function*(){if(!this._conversation||!this._mediaSource||this._participantState!==W.ACCEPTED)return;let i=this._conversation.muteState,r=this._conversation.muteOptions,n=i===ye.MUTE_PERMANENT,c=this._mediaSource.getMediaSettings();if(e){for(let l of r)S.onUnmuteRequest(l);return}r.includes(ie.AUDIO)&&c.isAudioEnabled&&!(t&&t.isAudioEnabled)&&(S.onDeviceSwitched(ie.AUDIO,!1),yield this.toggleLocalAudio(!1)),r.includes(ie.VIDEO)&&c.isVideoEnabled&&!(t&&t.isVideoEnabled)&&(S.onDeviceSwitched(ie.VIDEO,!1),yield this.toggleLocalVideo(!1)),r.includes(ie.SCREEN_SHARING)&&c.isScreenSharingEnabled&&!(t&&t.isScreenSharingEnabled)&&(S.onDeviceSwitched(ie.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1)),S.onUnmutePermission(!n||this._isCallAdmin())})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?S.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&S.onLocalPin(!0)),this._participants[e]?S.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&S.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!tr(this._conversation.options,e)&&(this._conversation.options=e,S.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let 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,S.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),S.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){S.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,d.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){o.error("Received remote stream notification for a participant that has no track associated with it",r);return}let 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(m.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}S.onRemoteStream(i.externalId,i.secondStream||c)}else{let r=t||i.remoteStream;r&&S.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===j.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state===Y.ACTIVE,t=this._conversation.features.includes(er.ADD_PARTICIPANT);S.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&S.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}S.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(S.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return s(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===D.CONNECTED?i=q.CONNECTED:t===D.CONNECTING||t===D.OPENED?i=q.CONNECTING:t===D.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===D.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===D.CONNECTED&&S.onLocalStatus(q.CONNECTED),e===D.CONNECTING&&S.onLocalStatus(q.CONNECTING),e===D.RECONNECTING&&S.onLocalStatus(q.RECONNECT),e===D.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(P.FAILED)),this._close(new N(P.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return s(this,null,function*(){if(e.endsWith(Me.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(Me.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&&(S.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===J.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;S.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),d.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(o.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case J.audio:this._removeAudioTrack(e,t,i);break;case J.video:case J.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Me.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!==Y.CLOSE||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),S.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return s(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==j.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):S.onParticipantStatus(c.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&S.onRemoteStatus(r,t,i)}},x=B;x._delayedHangup=!1;var Yt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Yt.prototype),this.participantErrors=t}};function xr(){if(!d.apiAppId||!d.apiKey)throw new N(se.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function $i(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Ur(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${d.apiEnv.api}fb.do`,r)}function Lr(i){return s(this,arguments,function*(a,e={},t=!1){let r=Ur(a,e,t);return Ka(r)})}function Ka(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 Ur(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 ct;(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"})(ct||(ct={}));var $a=10,qa=700,Ja=3e3,bt=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 Lr(e,t,i)}catch(l){if(!l.hasOwnProperty("error_msg")&&(c++,o.debug(`${e} network error, attempt ${c}...`),c<$a))return yield C.delay(Math.min(c*qa,Ja)),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=se.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:c=P.SERVICE_DISABLED;break;case 1102:c=P.CALLEE_IS_OFFLINE;break;case 1103:c=P.NOT_FRIENDS;break;case 1104:case 1106:c=P.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=C.decomposeId(e).id;return te.isEmpty()?re.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),re.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=C.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&&S.onTokenExpired(),new N(se.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})};$i("log.externalLog",t)}init(){xr()}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 xe.USER:p.uids=t.join(",");break;case xe.GROUP:p.gid=t[0];break;case xe.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=re.fromIds(e),i=[],r={methods:[]},n=[],c=Object.keys(this._externalUidsCache),l=Object.values(this._externalUidsCache);for(let _ of t){let b=re.toString(_),k=l.indexOf(b);k>-1?i.push(Number(c[k])):(n.push(b),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:_.id,anonym:_.type===Pe.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((_,b)=>{if(_.ok){let k=Number(_.ok.ok_id);this._externalUidsCache[k]=n[b],i.push(k)}}),i})}getExternalIdsByOkIds(e){return s(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(re.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(re.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=re.toString(e),n=i.indexOf(r);return n>-1?C.composeId(t[n],z.USER):null}cacheExternalId(e,t){let i=C.decomposeId(e).id;this._externalUidsCache[i]=re.toString(t)}getConversationParams(){return s(this,null,function*(){let e={};return d.anonymToken&&(e.anonymToken=d.anonymToken),this._call("vchat.getConversationParams",e)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:P.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),$i("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]=re.fromIdToString(n,Pe.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=re.fromIdToString(n,Pe.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 qi;(function(h){h.RECOVER="recover",h.ACCEPT_CALL="accept-call",h.ADD_PARTICIPANT="add-participant",h.REMOVE_PARTICIPANT="remove-participant",h.HANGUP="hangup",h.TRANSMIT_DATA="transmit-data",h.ACCEPT_PRODUCER="accept-producer",h.ALLOCATE_CONSUMER="allocate-consumer",h.CHANGE_MEDIA_SETTINGS="change-media-settings",h.CHANGE_PARTICIPANT_STATE="change-participant-state",h.CHANGE_STREAM_PRIORITIES="change-streams-priorities",h.UPDATE_DISPLAY_LAYOUT="update-display-layout",h.REPORT_PERF_STAT="report-perf-stat",h.RECORD_START="record-start",h.RECORD_STOP="record-stop",h.RECORD_SET_ROLE="record-set-role",h.RECORD_GET_STATUS="record-get-status",h.SWITCH_MICRO="switch-micro",h.SWITCH_TOPOLOGY="switch-topology",h.REQUEST_REALLOC="request-realloc",h.CHAT_MESSAGE="chat-message",h.CHAT_HISTORY="chat-history",h.CUSTOM_DATA="custom-data",h.GRANT_ROLES="grant-roles",h.MUTE_PARTICIPANT="mute-participant",h.PIN_PARTICIPANT="pin-participant",h.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",h.CHANGE_OPTIONS="change-options",h.GET_WAITING_HALL="get-waiting-hall",h.PROMOTE_PARTICIPANT="promote-participant",h.REQUEST_TEST_MODE="request-test-mode",h.ADD_MOVIE="add-movie",h.UPDATE_MOVIE="update-movie",h.REMOVE_MOVIE="remove-movie"})(qi||(qi={}));var G=qi;var Vr="open",Br=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack],Ya=10,Ae=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="+Ae._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<Br.length;t++)Br[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(m.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=C.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)===Vr&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){u.log(m.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(m.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=(b,k=!1)=>{!i||k?l(b):(o.debug("Resending a signaling message",e,_.sequence),i--,n(_))},_={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:c,reject:p};n(_)})})}_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},Ya)})}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,Xi({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=!1,r=!1){return s(this,null,function*(){return this._sendRaw(G.MUTE_PARTICIPANT,{participantId:e,mediaOptions:t,unmute:i,mutePermanent:r})})}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===Le.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(m.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(m.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(m.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(u.log(m.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new N(P.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(se.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(u.log(m.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(m.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){u.log(m.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Ae.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(Ae.RECONNECT_MAX_DELAY,Ae.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),u.log(m.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Le.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(m.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Ae.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)!==Vr){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}Ae._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Ae.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),Ae.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(se.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Ae.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(Le.RETRY)},Ae.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},we=Ae;we.RECONNECT_DELAY=d.signalingReconnectDelay,we.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,we.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,we.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,we.WAIT_RESPONSE_DELAY=d.waitResponseDelay,we.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var dt,ae,At=null,za={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 Fr(a){ae=a}function Gr(a){dt=a}function Qa(a){At=a}function Xa(a){d.videoEffects=a}function Za(a){return s(this,null,function*(){if(d.set(a),y.browserName()==="Sferum"&&(d.platform=`SFERUM:${y.browserVersion()}`),ae||Fr(new bt),dt||Gr(()=>new we),d.debug&&(Ji.default.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${d.sdkVersion}`,a),yield y.init(),!y.isBrowserSupported())throw new N(se.UNSUPPORTED);ae.init()})}function en(n){return s(this,arguments,function*(a,e=[ie.AUDIO],t="",i=!1,r=!1){let c=[],l=[];if(Array.isArray(a)?c=a.length?a:[]:a&&(c=[a]),c.length&&(l=yield ae.getOkIdsByExternalIds(c),!l.length))throw new N(P.CALLEE_IS_OFFLINE);return Hr(l,xe.USER,e,t,i,r)})}function Hr(c){return s(this,arguments,function*(a,e=xe.USER,t,i="",r=!1,n=!1){if(x.current())throw o.error("There is already active call"),new N(P.FAILED);return new x(ae,dt(),At).onStart(a,e,t,i,r,n)})}function tn(a){return s(this,null,function*(){return Wr(a)})}function Wr(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(ae,dt(),At).onPush(a,e,t)})}function rn(a,e){return s(this,null,function*(){return ae.getTokenForAnonym(a,e)})}function an(t){return s(this,arguments,function*(a,e={}){return ae.call(a,e)})}function nn(a){return s(this,null,function*(){return a&&(d.authToken=a),ae.authorize()})}function sn(){return s(this,arguments,function*(a=[ie.AUDIO]){let e=x.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function on(){return s(this,null,function*(){let a=x.current();if(a)return a.decline()})}function cn(t){return s(this,arguments,function*(a,e=[ie.AUDIO]){return jr(a,e)})}function jr(a,e,t){return s(this,null,function*(){if(x.current())throw o.error("There is already active call"),new N(P.FAILED);return new x(ae,dt(),At).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function dn(i){return s(this,arguments,function*(a,e=[ie.AUDIO],t){if(x.current())throw o.error("There is already active call"),new N(P.FAILED);return t&&(d.anonymToken=t),new x(ae,dt(),At).onJoin({joinLink:a,mediaOptions:e})})}function ln(){return s(this,null,function*(){let a=x.current();if(a)return a.hangup();x.hangupAfterInit()})}function pn(a,e){return s(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return Kr(t[0],e)})}function Kr(a,e){return s(this,null,function*(){let t=x.current();t&&(yield t.addParticipant(C.composeId(a,z.USER),e))})}function un(a,e=!1){return s(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);return $r(t[0],e)})}function $r(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.removeParticipant(C.composeId(a,z.USER),e))})}function hn(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 mn(a){return s(this,null,function*(){let e=x.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function _n(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.setVideoStream(a,e))})}function gn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalVideo(a))})}function fn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalAudio(a))})}function Sn(a,e){return s(this,null,function*(){let t=x.current();if(t)return t.setLocalResolution(a,e)})}function vn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changePriorities(a))})}function En(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changeParticipantState(a))})}function In(a){return s(this,null,function*(){let e=x.current();e&&(yield e.updateDisplayLayout(a))})}function Cn(a,e,t=!1){return s(this,null,function*(){let i=yield ae.getOkIdsByExternalIds([a]);return qr(i[0],e,t)})}function qr(a,e,t=!1){return s(this,null,function*(){let i=x.current();i&&(yield i.grantRoles(C.composeId(a,z.USER),e,t))})}function Tn(){return s(this,arguments,function*(a=null,e=[ie.AUDIO],t=!1){let i=null;return a&&(i=(yield ae.getOkIdsByExternalIds([a]))[0]),Jr(i,e,t)})}function Jr(){return s(this,arguments,function*(a=null,e=[ie.AUDIO],t=!1){let i=x.current();if(i){let r=a?C.composeId(a,z.USER):null;yield i.switchParticipantDevice(r,e,!1,t)}})}function Rn(){return s(this,arguments,function*(a=null,e=[ie.AUDIO]){let t=null;return a&&(t=(yield ae.getOkIdsByExternalIds([a]))[0]),Yr(t,e)})}function Yr(){return s(this,arguments,function*(a=null,e=[ie.AUDIO]){let t=x.current();if(t){let i=a?C.composeId(a,z.USER):null;yield t.switchParticipantDevice(i,e,!0)}})}function yn(a,e=!1){return s(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);return zr(t[0],e)})}function zr(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.pinParticipant(C.composeId(a,z.USER),e))})}function Pn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.updateMediaModifiers(a))})}function bn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changeOptions(a))})}function An(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),Qr(a,t)})}function Qr(a,e=null){return s(this,null,function*(){let t=x.current();if(t){let i=e?C.composeId(e,z.USER):null;yield t.chatMessage(a,i)}})}function Dn(a=10){return s(this,null,function*(){let e=x.current();if(e)return e.chatHistory(a)})}function On(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),Xr(a,t)})}function Xr(a,e=null){return s(this,null,function*(){let t=x.current();if(t){let i=e?C.composeId(e,z.USER):null;yield t.customData(a,i)}})}function Mn(a="",e=!1){return s(this,null,function*(){return(yield ae.createConversation(C.uuid(),a,e)).join_link})}function wn(){return s(this,null,function*(){let a=x.current();return a?a.createJoinLink():Promise.reject()})}function kn(){return s(this,null,function*(){let a=x.current();return a?a.removeJoinLink():Promise.reject()})}function Nn(a,e){return s(this,null,function*(){return ae.getAnonymTokenByLink(a,e)})}function xn(a){let e=x.current();e&&e.setVolume(a)}function Ln(a){d.forceRelayPolicy=a}function Un(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 Vn(){return s(this,null,function*(){let a=x.current();return a?a.stopStream():Promise.reject()})}function Bn(a,e){return s(this,null,function*(){let t=x.current();if(t){let i=yield ae.getOkIdsByExternalIds([a]);return t.recordSetRole(C.composeId(i[0],z.USER),e)}return Promise.reject()})}function Fn(){return s(this,null,function*(){let a=x.current();return a?a.getStreamInfo():Promise.reject()})}function Gn(a){return s(this,null,function*(){let e=x.current();return e?e.addMovie(a):Promise.reject()})}function Hn(a,e){return s(this,null,function*(){let t=x.current();return t?t.updateMovie(a,e):Promise.reject()})}function Wn(a){return s(this,null,function*(){let e=x.current();return e?e.removeMovie(a):Promise.reject()})}function jn(a){d.statisticsInterval=a;let e=x.current();if(e)return e.updateStatisticsInterval()}function Kn(a){Ji.default.disableLog(!a),o.toggle(a)}function $n(a,...e){!d.debugLog||o.send(a,"[external]",...e)}function qn(a){return s(this,null,function*(){let e=x.current();if(e)return e.videoEffect(a)})}function Jn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.setAudioStream(a))})}function Yn(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 zn(a,e=!1){return s(this,null,function*(){let t=x.current();if(!t)throw new Error("Conversation not found");let i=yield ae.getOkIdsByExternalIds([a]);return t.promoteParticipant(C.composeId(i[0],z.USER),e)})}function Qn(a){return s(this,null,function*(){yield ae.removeHistoryRecords(a)})}
10
+ `,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 Va=16*1024,Ba=11,kr=Va-Ba,Fa=65536,Hi=0,Pt=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())}};st.isBrowserSupported()?this._encoder=new st(e,i):this._encoder=new yt(e,i),this._datachannel.onmessage=r=>{wr(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=Or(e,t,i,r,Hi,this._encoder.isVP9(),n);return Hi=(Hi+1)%Fa,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+kr),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+kr,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 st.isBrowserSupported()||yt.isBrowserSupported()}};var Nr="videochat-epi",bt=class extends z{constructor(e,t){super();this._previousTimestamp=0;this._signaling=t,this.subscribe(e,f.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Nr)||"",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(Nr,r.estimatedPerformanceIndex)}catch(r){}this._previousTimestamp=i}})}};var Ga=90,Ha=4294967295,be=class extends z{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._reconnectionPrevented=!1;this._state=D.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,oe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,oe.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,oe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new bt(this,e),this._serverSettings=i,d.consumerScreenDataChannel&&!Pt.isBrowserSupported()&&(d.consumerScreenDataChannel=!1),d.producerScreenDataChannel&&!Rt.isBrowserSupported()&&(d.producerScreenDataChannel=!1),o.debug("ServerTransport: Created")}getState(){return this._state||D.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==D.IDLE&&e!==D.CLOSED&&e!==D.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(D.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(D.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Ft(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,be._closeDataChannel(this._producerNotification),be._closeDataChannel(this._producerCommand),be._closeDataChannel(this._producerScreen),be._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(f.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=be._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=C.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=be._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,Tt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Bi,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,Tt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,Tt.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(m.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,Tt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(D.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==D.OPENED&&(this._setState(D.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(f.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(f.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(f.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(f.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
11
+ `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Me.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 Pt(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 Rt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(f.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(f.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!==J.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)})}C.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(f.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 Ct(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(f.REMOTE_DATA_STATS,{inbound:{topology:j.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:j.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=Me.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(f.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:bt.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:be._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(m.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(m.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=C.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(m.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(m.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(f.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(f.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(m.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===D.IDLE||i===D.OPENED?this._setState(D.CONNECTING):e.iceConnectionState==="checking"&&this._setState(D.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(D.RECONNECTING);break;case"connected":this._setState(D.CONNECTED),C.getPeerConnectionHostInfo(e).then(r=>{r&&u.log(m.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(m.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(m.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(m.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(m.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&Ha,p=Math.ceil(l/Ga);return Math.min(100,Math.max(0,p))}};var f;(function(T){T.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",T.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",T.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",T.REMOTE_ALL_STALL="REMOTE_ALL_STALL",T.REMOTE_DATA_STATS="REMOTE_DATA_STATS",T.STATE_CHANGED="STATE_CHANGED",T.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",T.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",T.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",T.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",T.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",T.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",T.NETWORK_STATUS="NETWORK_STATUS",T.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED"})(f||(f={}));var D;(function(l){l.IDLE="IDLE",l.OPENED="OPENED",l.CONNECTING="CONNECTING",l.RECONNECTING="RECONNECTING",l.CONNECTED="CONNECTED",l.CLOSED="CLOSED",l.FAILED="FAILED"})(D||(D={}));var j;(function(t){t.DIRECT="DIRECT",t.SERVER="SERVER"})(j||(j={}));var Wi=class extends z{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState=D.IDLE;this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),e===j.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===j.DIRECT&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology===j.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===j.DIRECT&&this._directTransport&&this._directTransport.open(t),this._topology===j.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===j.DIRECT&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology===j.SERVER&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,D.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(f.STATE_CHANGED,i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent(f.STATE_CHANGED,[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent(f.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(m.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology===j.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===j.DIRECT){let i=e.offerTo||[],r=e.offerToTypes||[],n=i.length&&r.length?C.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(f.TOPOLOGY_CHANGED,this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new Ye(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(f.REMOTE_TRACK_ADDED,this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener(f.REMOTE_TRACK_REMOVED,this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener(f.REMOTE_DATA_STATS,this._onDirectRemoteDataStats.bind(this)),i.addEventListener(f.STATE_CHANGED,this._onDirectTransportChanged.bind(this,e)),i.addEventListener(f.NETWORK_STATUS,this._onTransportNetworkStatus.bind(this)),i.addEventListener(f.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this,j.DIRECT))),i}_createServerTransport(){let e=new be(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(f.REMOTE_TRACK_ADDED,this._onServerRemoteTrackAdded.bind(this)),e.addEventListener(f.REMOTE_TRACK_REMOVED,this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener(f.REMOTE_ALL_STALL,this._onServerRemoteAllStall.bind(this)),e.addEventListener(f.REMOTE_DATA_STATS,this._onServerRemoteDataStats.bind(this)),e.addEventListener(f.STATE_CHANGED,this._onServerTransportChanged.bind(this)),e.addEventListener(f.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener(f.SIGNALLED_ACTIVE_PARTICIPANTS,this._onTransportActiveParticipants.bind(this)),e.addEventListener(f.SIGNALLED_SPEAKER_CHANGED,this._onTransportSpeakerChanged.bind(this)),e.addEventListener(f.SIGNALLED_STALLED_PARTICIPANTS,this._onTransportStalledParticipants.bind(this)),e.addEventListener(f.NETWORK_STATUS,this._onTransportNetworkStatus.bind(this)),e.addEventListener(f.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),e.addEventListener(f.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this,j.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===D.CONNECTED&&this._topology===j.DIRECT&&this._releaseServerTransport(!0),(t===D.CLOSED||t===D.FAILED)&&(this._releaseDirectTransport(!1),this._topology===j.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===j.DIRECT&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e===D.CONNECTED&&this._topology===j.SERVER&&this._releaseDirectTransport(!0),(e===D.CLOSED||e===D.FAILED)&&(this._releaseServerTransport(!1),this._topology===j.SERVER&&(this._allocated=[],this._opened=[])),this._topology===j.SERVER&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent(f.ACTIVE_PARTICIPANTS_NO_SIGNAL)}_onTransportActiveParticipants(e){this._topology===j.SERVER&&this._triggerEvent(f.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_onTransportStalledParticipants(e){this._topology===j.SERVER&&this._triggerEvent(f.SIGNALLED_STALLED_PARTICIPANTS,e)}_onTransportSpeakerChanged(e){this._topology===j.SERVER&&this._triggerEvent(f.SIGNALLED_SPEAKER_CHANGED,e)}_onTransportNetworkStatus(e){this._triggerEvent(f.NETWORK_STATUS,e)}_onRemoteStreamSecond(e,t){this._triggerEvent(f.REMOTE_STREAM_SECOND,e,t)}_onPeerConnectionClosed(e){this._triggerEvent(f.PEER_CONNECTION_CLOSED,e)}_onServerRemoteAllStall(e){this._topology===j.SERVER&&this._triggerEvent(f.REMOTE_ALL_STALL,e)}_onServerRemoteDataStats(e){this._triggerEvent(f.REMOTE_DATA_STATS,e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent(f.REMOTE_TRACK_ADDED,e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent(f.REMOTE_TRACK_REMOVED,e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent(f.REMOTE_DATA_STATS,e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent(f.REMOTE_TRACK_ADDED,e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent(f.REMOTE_TRACK_REMOVED,e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!==j.SERVER?(u.log(m.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(m.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Fe;(function(e){e.VOLUMES_DETECTED="VOLUMES_DETECTED"})(Fe||(Fe={}));var ji=class extends z{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,f.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,f.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,f.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,f.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===J.audio&&((r=this._detector)==null||r.destroy(),this._detector=new It(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,d.voiceParams.interval)};this._interval=window.setTimeout(n,d.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===J.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===Me.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent(Fe.VOLUMES_DETECTED,e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var ot;(function(e){e.SPEAKER_CHANGED="SPEAKER_CHANGED"})(ot||(ot={}));var Ki=class extends z{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,Fe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,f.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,f.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,f.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(ot.SPEAKER_CHANGED,i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent(ot.SPEAKER_CHANGED,e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var Jt=class extends z{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,f.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,Fe.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===D.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===D.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),u.log(m.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!==D.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),u.log(m.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(m.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Wa=1e3,ja=1e4,Y;(function(r){r.IDLE="IDLE",r.PROCESSING="PROCESSING",r.ACTIVE="ACTIVE",r.CLOSE="CLOSE"})(Y||(Y={}));var B=class extends z{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state=Y.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 Gt,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Wa))}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(m.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new N(P.FAILED);B._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let l=this._mediaSource.getMediaSettings();t===xe.CHAT||e.length>1?this._logWithMediaSettings(m.OUTGOING_MULTIPARTY_CALL,l):this._logWithMediaSettings(m.OUTGOING_CALL,l);let p=yield this._startConversation(e,t,Be.OUTGOING,i,r,n,c);if(!this._conversation)throw new N(P.UNKNOWN_ERROR);if(this._participantState=W.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(P.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let _=Object.values(this._participants),b;return d.batchParticipantsOnStart&&(b=C.mapSharedParticipants(_)),S.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),S.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,b),S.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),B._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(_,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(m.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new N(P.FAILED);B._activationMutex=!0,this._state=Y.PROCESSING;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(m.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new N(P.UNKNOWN_ERROR);return S.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(o.log("In waiting hall"),B._current=this,B._activationMutex=!1,this._signaling.readyToSend(),S.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=W.ACCEPTED,!this._conversation||!this._mediaSource)throw new N(P.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(P.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=C.mapSharedParticipants(t)),S.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,i),S.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state=Y.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=Q.USER,i){if(B._activationMutex)throw o.warn("Conversation: there is already running activation"),new N(P.REJECTED);B._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new N(P.UNKNOWN_ERROR);if(!n.conversation.participants.find(l=>{var p;return l.state===W.CALLED&&l.id===((p=this._conversation)==null?void 0:p.userId)}))throw o.log("Push rejected (there is an active call)"),u.log(m.PUSH,"rejected"),new N(P.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),u.log(m.PUSH,"accepted"),B._current=this,B._delayedHangup)throw new N(P.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(Mt.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>C.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return s(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new N(P.UNKNOWN_ERROR);this._state=Y.PROCESSING;let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(m.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),S.onCallAccepted(),this._state=Y.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!==Y.IDLE)throw u.log(m.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(P.UNKNOWN_ERROR);this._state=Y.PROCESSING,o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(m.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=W.ACCEPTED;let i=Object.values(this._participants),r;return d.batchParticipantsOnStart&&(r=C.mapSharedParticipants(i)),S.onCallAccepted(),S.onLocalStream(this._mediaSource.getStream(),t),S.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,r),S.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),(this._conversation.muteState===ye.MUTE||this._conversation.muteState===ye.MUTE_PERMANENT)&&(yield this._processMuteState()),this._state=Y.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!==Y.IDLE)throw u.log(m.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state=Y.PROCESSING,o.debug("Decline incoming call"),this._logWithMediaSettings(m.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=W.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(P.REJECTED)),this._close(new N(P.REJECTED))})}hangup(){return s(this,null,function*(){o.debug("Hangup");let e=this._state===Y.ACTIVE?P.HUNGUP:P.CANCELED;u.log(m.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new N(e))):S.onHangup(new N(P.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return s(this,null,function*(){if(!this._signaling.ready){this._close(new N(P.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=P.UNKNOWN_ERROR);let 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(P.FAILED):u.log(m.ERROR,e.hangup),B._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([P.CANCELED,P.NOT_FRIENDS,P.CALLEE_IS_OFFLINE,P.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===P.REJECTED&&!e.remote){S.onHangup(e,i),this.destroy();return}if(e.hangup===P.HUNGUP&&(!e.remote||this._participantState===W.CALLED)){S.onHangup(e,i),this.destroy();return}if(e.hangup===P.MISSED&&!e.remote){S.onHangup(e,i),this.destroy();return}if(e.hangup===P.SOCKET_CLOSED&&B._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===P.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state=Y.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,B._current=null,B._delayedHangup=!1,S.onHangup(e||new N(P.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;o.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),u.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(){return s(this,null,function*(){let e=yield this._api.getConversationParams();o.debug("Api.getConversationParams",e);let t=[],{turn_server:i,stun_server:r}=e;if(r&&t.push(r),i){let n=i.urls.filter((c,l,p)=>p.indexOf(c)===l);n.forEach(c=>n.push(`${c}?transport=tcp`)),t.push({urls:n,username:i.username,credential:i.credential})}d.iceServers=t,d.wssBase=e.endpoint,d.wssToken=e.token,e.client_type&&(d.clientType=e.client_type)})}_startConversation(e,t,i,r,n="",c=!1,l=!1){return s(this,null,function*(){let p=C.uuid();o.debug("Conversation: start",{conversationId:p,opponentIds:e,opponentType:t,direction:i});let _=r.includes(re.VIDEO),b=yield this._api.startConversation(p,e,t,_,n,c,l);o.debug("Api.startConversation",b),yield this._getConversationParams();let k=yield this._connectSignaling(Le.START,b);return yield this._setConversation(b,k,i),k})}_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(re.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(P.UNKNOWN_ERROR);o.debug("Api.joinConversation",l),yield this._getConversationParams();let p=yield this._connectSignaling(Le.JOIN,l);return yield this._setConversation(l,p,Be.JOINING),p})}_prepareConversation(r){return s(this,arguments,function*(e,t=Q.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i}),yield this._getConversationParams();let n=this._api.getUserId();if(!n)throw new N(P.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(Le.ACCEPT,c);return B._current&&(B._current._participantState===W.ACCEPTED||B._current._participantState===W.CALLED)?(o.log("Push rejected (busy)"),u.log(m.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(P.BUSY),Promise.reject({hangup:P.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:W.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{}},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(P.NETWORK_ERROR),t),t}})}_setConversation(n,c,l){return s(this,arguments,function*(e,t,i,r=Q.USER){let p=t.conversation.participants.map(K=>K.id);yield this._api.prepareUserIds(p);let _=this._api.getUserId();if(!_){let K=(t.conversation.participants||[]).find(ne=>C.comparePeerId(ne.peerId,t.peerId));if(!K)throw new N(P.UNKNOWN_ERROR);_=Number(K.id),K.idType&&(r=K.idType),this._api.setUserId(_)}let b=C.composeId(_,r),k=yield this._getUserId(b);this._conversation={userId:_,compositeUserId:b,externalId:k,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||j.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:[],muteState:ye.UNMUTE,muteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),u.log(m.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new N(P.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||j.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 wi;return this.subscribe(e,oe.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,oe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new Et(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=C.composeParticipantId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),S.onLocalRolesChanged(this._conversation.roles));continue}if(t.state===W.HUNGUP||t.state===W.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],P.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&ie.fromSignaling(t.externalId),mediaSettings:ve(t.mediaSettings),participantState:C.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?q.WAITING:null}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),S.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){e.muteOptions&&(e.muteState===ye.MUTE||e.muteState===ye.MUTE_PERMANENT)&&this._onMuteParticipant(e.muteOptions,!1,e.muteState),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(Ot.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Wi(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new Ht,this.subscribe(this._transport,f.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,f.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,f.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,f.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,f.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,f.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,f.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,f.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,f.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,f.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,f.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,f.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===W.ACCEPTED||t.state===W.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new ji(this._transport),this.subscribe(this._volumesDetector,Fe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Ki(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,ot.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Wt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Jt(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(m.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===Y.CLOSE||!this._participants[e.id]||(t===P.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:Ce.CAMERA,stopStream:!0}]),delete this._participants[e.id],S.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(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&&ie.fromSignaling(t.externalId),mediaSettings:ve(t.mediaSettings),state:t.state,roles:t.roles||[]}),r=this._participants[e]),this._setParticipantsStatus([r],q.WAITING),i?(r.state=W.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=W.CALLED,this._transport.allocate(r.id,!0),u.log(m.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(m.REMOVE_PARTICIPANT)}changeDevice(e){return s(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new Et(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(se.UNKNOWN)})}toggleScreenCapturing(e){return s(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(se.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(m.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return s(this,null,function*(){if(this._mediaSource)return u.log(m.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=Je({participantId:l,mediaType:r.mediaType,streamName:r.streamName}),_=this._participants[l];_&&(_.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=vt(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Ce.STREAM||i.mediaType===Ce.SCREEN)?S.onRemoteLive(r.externalId,i.streamName,null):S.onRemoteStream(r.externalId,null),u.log(m.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=vt(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=rr.UNKNOWN_ERROR):p=ar(n),i.push({externalId:l.externalId,errorReason:p})}}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]+ja>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(P.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(C.decomposeId(l.id.id).id)}),c.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(c))),S.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var l,p;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===Ce.SCREEN)return;let i=Je(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(m.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 _=t.participantId,b=this._participants[_];if(!b){u.log(m.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${_}`);return}let k=this._streamByStreamId.get(n);if(!k){u.log(m.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}u.log(m.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let K=(l=e.participantStreamDescription)==null?void 0:l.mediaType;if(K===Ce.STREAM||K===Ce.MOVIE)((p=e.participantStreamDescription)==null?void 0:p.streamName)&&S.onRemoteLive(b.externalId,e.participantStreamDescription.streamName,k);else{let ne=(d.producerScreenTrack?null:b.secondStream)||k;S.onRemoteStream(b.externalId,ne)}}else{o.debug(`Waiting for ${c} until stream ${n} for ${i} is switched`);let _=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),c);this._streamWaitTimerByStreamDescription.set(i,_)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Je(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Je(i)))return i}else{let i={participantId:t,mediaType:Ce.CAMERA};if(this._streamIdByStreamDescription.has(Je(i)))return i;let r={participantId:t,mediaType:Ce.SCREEN};if(this._streamIdByStreamDescription.has(Je(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?C.includesOneOf(this._conversation.roles,[je.ADMIN,je.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!C.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)})}switchParticipantDevice(e=null,t,i,r=!1){return s(this,null,function*(){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i,r)})}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=ir(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=Ir(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let c=n.participants||[],l=[],p=[],_=null;return c.length&&(c.forEach(b=>{if(b.externalId){let k=ie.fromSignaling(b.externalId);l.push(k),this._api.cacheExternalId(b.id.id,k)}else p.push(C.decomposeId(b.id.id).id)}),p.length&&!l.length&&(l=yield this._api.getExternalIdsByOkIds(p)),n.hasMore&&(_=Er(c[c.length-1].id))),{participants:l,pageMarker:_,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){return s(this,null,function*(){var n;let i={movieId:e,participantId:(n=this._conversation)==null?void 0:n.compositeUserId};(t||t===0)&&(i.gain=t);let r=yield this._signaling.updateMovie(i);if(r.error)throw new Error(r.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){return s(this,null,function*(){var i;if(e<d.videoMinWidth||t<d.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");return d.videoMaxWidth=e,d.videoMaxHeight=t,(i=this._mediaSource)==null?void 0:i.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),S.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;S.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===Y.ACTIVE&&S.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===Y.ACTIVE&&(d.participantStateMapped?S.onRemoteParticipantState(i.externalId,i.participantState):S.onRemoteParticipantState(i.externalId,C.mapLegacyParticipantState(i.participantState))))}_onSignalingNotification(e){var t;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:let i=e.unmute?((t=this._conversation)==null?void 0:t.muteState)||ye.UNMUTE:e.mutePermanent?ye.MUTE_PERMANENT:ye.MUTE;return this._onMuteParticipant(e.mediaOptions||[],e.unmute||!1,i);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=C.composeParticipantId(n),l=n.roles||[];if(c===this._conversation.compositeUserId){t=ve(n.mediaSettings),ht(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 _=ve(n.mediaSettings);gr(_,p.mediaSettings)||this._changeRemoteMediaSettings(c,_);let b=C.mapParticipantState(n),k=p.participantState;C.isEqualParticipantState(b,k)||this._changeRemoteParticipantState(c,b),ht(l,p.roles)||this._onRolesChanged(p.id,l)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],P.HUNGUP)}(e.muteState===ye.MUTE||e.muteState===ye.MUTE_PERMANENT)&&this._onMuteParticipant(e.muteOptions,!1,e.muteState,t),e.unmuteOptions&&e.unmuteOptions.length&&this._onMuteParticipant(e.unmuteOptions,!0,e.muteState,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=C.composeMessageId(e),i=C.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new N(P.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=W.ACCEPTED,r.mediaSettings=ve(e.mediaSettings),this._logWithMediaSettings(m.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Be.OUTGOING&&(this._state===Y.IDLE||this._state===Y.PROCESSING)&&(this._state=Y.ACTIVE,this._changeFeatureSet()),this._state===Y.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=C.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===P.REJECTED?W.REJECTED:W.HUNGUP,this._state!==Y.CLOSE&&this._removeParticipant(i,P.HUNGUP)}_onAddedParticipant(e){return s(this,null,function*(){var r,n;o.debug(`Participant added [${e.participantId}]`);let t=C.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&&ie.fromSignaling(e.participant.externalId),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:C.mapParticipantState(e.participant),roles:e.participant.roles||[]}),i=this._participants[t]),i.state=W.CALLED,i.mediaSettings=ve((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=C.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],q.WAITING),this._state===Y.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=C.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&&ie.fromSignaling(e.participant.externalId),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:C.mapParticipantState(e.participant),roles:e.participant.roles||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Be.OUTGOING&&(this._state===Y.IDLE||this._state===Y.PROCESSING)&&(this._state=Y.ACTIVE,this._changeFeatureSet()),i.state=W.ACCEPTED,i.mediaSettings=ve(e.mediaSettings),i.participantState=C.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===Y.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=C.composeMessageId(e);this._changeRemoteMediaSettings(t,ve(e.mediaSettings))}_onParticipantStateChanged(e){let t=C.composeMessageId(e);this._changeRemoteParticipantState(t,C.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),S.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return 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=Li(this._serverSettings,t),this._signalingServerSettings=vr(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=Li(this._serverSettings,c),o.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=C.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return s(this,null,function*(){S.onDeviceSwitched(re.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return s(this,null,function*(){let t=C.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),S.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return s(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=C.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),S.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);S.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else S.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!ht(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,S.onLocalRolesChanged(t);return}let i=this._participants[e];i&&!ht(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,S.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t,i,r){return s(this,null,function*(){!this._conversation||(this._conversation.muteOptions=e,!(this._conversation.muteState===i&&!t)&&(this._conversation.muteState=i,yield this._processMuteState(t,r)))})}_processMuteState(e=!1,t){return s(this,null,function*(){if(!this._conversation||!this._mediaSource||this._participantState!==W.ACCEPTED)return;let i=this._conversation.muteState,r=this._conversation.muteOptions,n=i===ye.MUTE_PERMANENT,c=this._mediaSource.getMediaSettings();if(e){for(let l of r)S.onUnmuteRequest(l);return}r.includes(re.AUDIO)&&c.isAudioEnabled&&!(t&&t.isAudioEnabled)&&(S.onDeviceSwitched(re.AUDIO,!1),yield this.toggleLocalAudio(!1)),r.includes(re.VIDEO)&&c.isVideoEnabled&&!(t&&t.isVideoEnabled)&&(S.onDeviceSwitched(re.VIDEO,!1),yield this.toggleLocalVideo(!1)),r.includes(re.SCREEN_SHARING)&&c.isScreenSharingEnabled&&!(t&&t.isScreenSharingEnabled)&&(S.onDeviceSwitched(re.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1)),S.onUnmutePermission(!n||this._isCallAdmin(),r)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?S.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&S.onLocalPin(!0)),this._participants[e]?S.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&S.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!tr(this._conversation.options,e)&&(this._conversation.options=e,S.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let 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,S.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),S.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){S.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,d.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){o.error("Received remote stream notification for a participant that has no track associated with it",r);return}let 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(m.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}S.onRemoteStream(i.externalId,i.secondStream||c)}else{let r=t||i.remoteStream;r&&S.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===j.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state===Y.ACTIVE,t=this._conversation.features.includes(er.ADD_PARTICIPANT);S.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&S.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}S.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(S.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return s(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===D.CONNECTED?i=q.CONNECTED:t===D.CONNECTING||t===D.OPENED?i=q.CONNECTING:t===D.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===D.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===D.CONNECTED&&S.onLocalStatus(q.CONNECTED),e===D.CONNECTING&&S.onLocalStatus(q.CONNECTING),e===D.RECONNECTING&&S.onLocalStatus(q.RECONNECT),e===D.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(P.FAILED)),this._close(new N(P.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return s(this,null,function*(){if(e.endsWith(Me.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(Me.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&&(S.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===J.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;S.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),d.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(o.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case J.audio:this._removeAudioTrack(e,t,i);break;case J.video:case J.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Me.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!==Y.CLOSE||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),S.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return s(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==j.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):S.onParticipantStatus(c.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&S.onRemoteStatus(r,t,i)}},x=B;x._delayedHangup=!1;var Yt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Yt.prototype),this.participantErrors=t}};function xr(){if(!d.apiAppId||!d.apiKey)throw new N(se.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function $i(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Ur(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${d.apiEnv.api}fb.do`,r)}function Lr(i){return s(this,arguments,function*(a,e={},t=!1){let r=Ur(a,e,t);return Ka(r)})}function Ka(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 Ur(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 ct;(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"})(ct||(ct={}));var $a=10,qa=700,Ja=3e3,At=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 Lr(e,t,i)}catch(l){if(!l.hasOwnProperty("error_msg")&&(c++,o.debug(`${e} network error, attempt ${c}...`),c<$a))return yield C.delay(Math.min(c*qa,Ja)),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=se.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:c=P.SERVICE_DISABLED;break;case 1102:c=P.CALLEE_IS_OFFLINE;break;case 1103:c=P.NOT_FRIENDS;break;case 1104:case 1106:c=P.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=C.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=C.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&&S.onTokenExpired(),new N(se.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})};$i("log.externalLog",t)}init(){xr()}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 xe.USER:p.uids=t.join(",");break;case xe.GROUP:p.gid=t[0];break;case xe.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 _ of t){let b=ie.toString(_),k=l.indexOf(b);k>-1?i.push(Number(c[k])):(n.push(b),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:_.id,anonym:_.type===Pe.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((_,b)=>{if(_.ok){let k=Number(_.ok.ok_id);this._externalUidsCache[k]=n[b],i.push(k)}}),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?C.composeId(t[n],Q.USER):null}cacheExternalId(e,t){let i=C.decomposeId(e).id;this._externalUidsCache[i]=ie.toString(t)}getConversationParams(){return s(this,null,function*(){let e={};return d.anonymToken&&(e.anonymToken=d.anonymToken),this._call("vchat.getConversationParams",e)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:P.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),$i("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,Pe.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=ie.fromIdToString(n,Pe.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 qi;(function(h){h.RECOVER="recover",h.ACCEPT_CALL="accept-call",h.ADD_PARTICIPANT="add-participant",h.REMOVE_PARTICIPANT="remove-participant",h.HANGUP="hangup",h.TRANSMIT_DATA="transmit-data",h.ACCEPT_PRODUCER="accept-producer",h.ALLOCATE_CONSUMER="allocate-consumer",h.CHANGE_MEDIA_SETTINGS="change-media-settings",h.CHANGE_PARTICIPANT_STATE="change-participant-state",h.CHANGE_STREAM_PRIORITIES="change-streams-priorities",h.UPDATE_DISPLAY_LAYOUT="update-display-layout",h.REPORT_PERF_STAT="report-perf-stat",h.RECORD_START="record-start",h.RECORD_STOP="record-stop",h.RECORD_SET_ROLE="record-set-role",h.RECORD_GET_STATUS="record-get-status",h.SWITCH_MICRO="switch-micro",h.SWITCH_TOPOLOGY="switch-topology",h.REQUEST_REALLOC="request-realloc",h.CHAT_MESSAGE="chat-message",h.CHAT_HISTORY="chat-history",h.CUSTOM_DATA="custom-data",h.GRANT_ROLES="grant-roles",h.MUTE_PARTICIPANT="mute-participant",h.PIN_PARTICIPANT="pin-participant",h.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",h.CHANGE_OPTIONS="change-options",h.GET_WAITING_HALL="get-waiting-hall",h.PROMOTE_PARTICIPANT="promote-participant",h.REQUEST_TEST_MODE="request-test-mode",h.ADD_MOVIE="add-movie",h.UPDATE_MOVIE="update-movie",h.REMOVE_MOVIE="remove-movie"})(qi||(qi={}));var G=qi;var Vr="open",Br=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack],Ya=10,Ae=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="+Ae._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<Br.length;t++)Br[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(m.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=C.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)===Vr&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){u.log(m.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(m.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=(b,k=!1)=>{!i||k?l(b):(o.debug("Resending a signaling message",e,_.sequence),i--,n(_))},_={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:c,reject:p};n(_)})})}_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},Ya)})}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,Xi({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=!1,r=!1){return s(this,null,function*(){return this._sendRaw(G.MUTE_PARTICIPANT,{participantId:e,mediaOptions:t,unmute:i,mutePermanent:r})})}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===Le.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(m.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(m.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(m.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(u.log(m.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new N(P.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(se.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(u.log(m.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(m.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){u.log(m.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Ae.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(Ae.RECONNECT_MAX_DELAY,Ae.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),u.log(m.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Le.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(m.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Ae.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)!==Vr){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}Ae._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Ae.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),Ae.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(se.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Ae.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(Le.RETRY)},Ae.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},we=Ae;we.RECONNECT_DELAY=d.signalingReconnectDelay,we.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,we.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,we.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,we.WAIT_RESPONSE_DELAY=d.waitResponseDelay,we.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var dt,ae,Dt=null,Qa={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 Fr(a){ae=a}function Gr(a){dt=a}function za(a){Dt=a}function Xa(a){d.videoEffects=a}function Za(a){return s(this,null,function*(){if(d.set(a),y.browserName()==="Sferum"&&(d.platform=`SFERUM:${y.browserVersion()}`),ae||Fr(new At),dt||Gr(()=>new we),d.debug&&(Ji.default.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${d.sdkVersion}`,a),yield y.init(),!y.isBrowserSupported())throw new N(se.UNSUPPORTED);ae.init()})}function en(n){return s(this,arguments,function*(a,e=[re.AUDIO],t="",i=!1,r=!1){let c=[],l=[];if(Array.isArray(a)?c=a.length?a:[]:a&&(c=[a]),c.length&&(l=yield ae.getOkIdsByExternalIds(c),!l.length))throw new N(P.CALLEE_IS_OFFLINE);return Hr(l,xe.USER,e,t,i,r)})}function Hr(c){return s(this,arguments,function*(a,e=xe.USER,t,i="",r=!1,n=!1){if(x.current())throw o.error("There is already active call"),new N(P.FAILED);return new x(ae,dt(),Dt).onStart(a,e,t,i,r,n)})}function tn(a){return s(this,null,function*(){return Wr(a)})}function Wr(i){return s(this,arguments,function*(a,e=Q.USER,t){if(a===x.id())throw new Error("Push has already been processed");return new x(ae,dt(),Dt).onPush(a,e,t)})}function rn(a,e){return s(this,null,function*(){return ae.getTokenForAnonym(a,e)})}function an(t){return s(this,arguments,function*(a,e={}){return ae.call(a,e)})}function nn(a){return s(this,null,function*(){return a&&(d.authToken=a),ae.authorize()})}function sn(){return s(this,arguments,function*(a=[re.AUDIO]){let e=x.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function on(){return s(this,null,function*(){let a=x.current();if(a)return a.decline()})}function cn(t){return s(this,arguments,function*(a,e=[re.AUDIO]){return jr(a,e)})}function jr(a,e,t){return s(this,null,function*(){if(x.current())throw o.error("There is already active call"),new N(P.FAILED);return new x(ae,dt(),Dt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function dn(i){return s(this,arguments,function*(a,e=[re.AUDIO],t){if(x.current())throw o.error("There is already active call"),new N(P.FAILED);return t&&(d.anonymToken=t),new x(ae,dt(),Dt).onJoin({joinLink:a,mediaOptions:e})})}function ln(){return s(this,null,function*(){let a=x.current();if(a)return a.hangup();x.hangupAfterInit()})}function pn(a,e){return s(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return Kr(t[0],e)})}function Kr(a,e){return s(this,null,function*(){let t=x.current();t&&(yield t.addParticipant(C.composeId(a,Q.USER),e))})}function un(a,e=!1){return s(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);return $r(t[0],e)})}function $r(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.removeParticipant(C.composeId(a,Q.USER),e))})}function hn(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 mn(a){return s(this,null,function*(){let e=x.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function _n(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.setVideoStream(a,e))})}function gn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalVideo(a))})}function fn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalAudio(a))})}function Sn(a,e){return s(this,null,function*(){let t=x.current();if(t)return t.setLocalResolution(a,e)})}function vn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changePriorities(a))})}function En(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changeParticipantState(a))})}function In(a){return s(this,null,function*(){let e=x.current();e&&(yield e.updateDisplayLayout(a))})}function Cn(a,e,t=!1){return s(this,null,function*(){let i=yield ae.getOkIdsByExternalIds([a]);return qr(i[0],e,t)})}function qr(a,e,t=!1){return s(this,null,function*(){let i=x.current();i&&(yield i.grantRoles(C.composeId(a,Q.USER),e,t))})}function Tn(){return s(this,arguments,function*(a=null,e=[re.AUDIO],t=!1){let i=null;return a&&(i=(yield ae.getOkIdsByExternalIds([a]))[0]),Jr(i,e,t)})}function Jr(){return s(this,arguments,function*(a=null,e=[re.AUDIO],t=!1){let i=x.current();if(i){let r=a?C.composeId(a,Q.USER):null;yield i.switchParticipantDevice(r,e,!1,t)}})}function Rn(){return s(this,arguments,function*(a=null,e=[re.AUDIO]){let t=null;return a&&(t=(yield ae.getOkIdsByExternalIds([a]))[0]),Yr(t,e)})}function Yr(){return s(this,arguments,function*(a=null,e=[re.AUDIO]){let t=x.current();if(t){let i=a?C.composeId(a,Q.USER):null;yield t.switchParticipantDevice(i,e,!0)}})}function yn(a,e=!1){return s(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);return Qr(t[0],e)})}function Qr(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.pinParticipant(C.composeId(a,Q.USER),e))})}function Pn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.updateMediaModifiers(a))})}function bn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changeOptions(a))})}function An(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),zr(a,t)})}function zr(a,e=null){return s(this,null,function*(){let t=x.current();if(t){let i=e?C.composeId(e,Q.USER):null;yield t.chatMessage(a,i)}})}function Dn(a=10){return s(this,null,function*(){let e=x.current();if(e)return e.chatHistory(a)})}function On(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),Xr(a,t)})}function Xr(a,e=null){return s(this,null,function*(){let t=x.current();if(t){let i=e?C.composeId(e,Q.USER):null;yield t.customData(a,i)}})}function Mn(a="",e=!1){return s(this,null,function*(){return(yield ae.createConversation(C.uuid(),a,e)).join_link})}function wn(){return s(this,null,function*(){let a=x.current();return a?a.createJoinLink():Promise.reject()})}function kn(){return s(this,null,function*(){let a=x.current();return a?a.removeJoinLink():Promise.reject()})}function Nn(a,e){return s(this,null,function*(){return ae.getAnonymTokenByLink(a,e)})}function xn(a){let e=x.current();e&&e.setVolume(a)}function Ln(a){d.forceRelayPolicy=a}function Un(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 Vn(){return s(this,null,function*(){let a=x.current();return a?a.stopStream():Promise.reject()})}function Bn(a,e){return s(this,null,function*(){let t=x.current();if(t){let i=yield ae.getOkIdsByExternalIds([a]);return t.recordSetRole(C.composeId(i[0],Q.USER),e)}return Promise.reject()})}function Fn(){return s(this,null,function*(){let a=x.current();return a?a.getStreamInfo():Promise.reject()})}function Gn(a){return s(this,null,function*(){let e=x.current();return e?e.addMovie(a):Promise.reject()})}function Hn(a,e){return s(this,null,function*(){let t=x.current();return t?t.updateMovie(a,e):Promise.reject()})}function Wn(a){return s(this,null,function*(){let e=x.current();return e?e.removeMovie(a):Promise.reject()})}function jn(a){d.statisticsInterval=a;let e=x.current();if(e)return e.updateStatisticsInterval()}function Kn(a){Ji.default.disableLog(!a),o.toggle(a)}function $n(a,...e){!d.debugLog||o.send(a,"[external]",...e)}function qn(a){return s(this,null,function*(){let e=x.current();if(e)return e.videoEffect(a)})}function Jn(a){return s(this,null,function*(){let e=x.current();e&&(yield e.setAudioStream(a))})}function Yn(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 Qn(a,e=!1){return s(this,null,function*(){let t=x.current();if(!t)throw new Error("Conversation not found");let i=yield ae.getOkIdsByExternalIds([a]);return t.promoteParticipant(C.composeId(i[0],Q.USER),e)})}function zn(a){return s(this,null,function*(){yield ae.removeHistoryRecords(a)})}