@vkontakte/calls-sdk 2.4.4-beta.9 → 2.4.4-dev.717e1c2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CallsSDK.d.ts +15 -12
- package/abstract/BaseSignaling.d.ts +7 -7
- package/calls-sdk.cjs.js +9 -8
- package/calls-sdk.esm.js +9 -8
- package/classes/Conversation.d.ts +17 -14
- package/classes/DebugInfo.d.ts +2 -2
- package/classes/MediaSource.d.ts +11 -0
- package/classes/SpeakerDetector.d.ts +2 -2
- package/classes/SpecListener.d.ts +3 -3
- package/classes/screenshare/BaseStreamBuilder.d.ts +25 -0
- package/classes/screenshare/ScreenCaptureReceiver.d.ts +2 -2
- package/classes/screenshare/StreamBuilder.d.ts +6 -10
- package/classes/screenshare/WebmBuilder.d.ts +19 -0
- package/classes/transport/DirectTransport.d.ts +2 -2
- package/classes/transport/ServerTransport.d.ts +2 -2
- package/classes/transport/Statistics.d.ts +2 -2
- package/classes/transport/Transport.d.ts +5 -5
- package/default/Api.d.ts +1 -1
- package/default/Signaling.d.ts +7 -7
- package/enums/HangupType.d.ts +1 -0
- package/package.json +4 -2
- package/static/External.d.ts +18 -18
- package/static/Params.d.ts +23 -22
- package/static/Utils.d.ts +12 -4
- package/types/ConversationParams.d.ts +1 -0
- package/types/ConversationResponse.d.ts +4 -0
- package/types/ExternalId.d.ts +17 -1
- package/types/MediaSettings.d.ts +5 -1
- package/types/Participant.d.ts +11 -3
- package/types/ParticipantLayout.d.ts +2 -2
- package/types/ParticipantPriority.d.ts +3 -3
- package/types/ParticipantStreamDescription.d.ts +2 -2
- package/types/SignalingMessage.d.ts +25 -17
- package/utils/Media.d.ts +4 -0
package/calls-sdk.esm.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/calls-sdk v2.4.4-
|
|
3
|
-
* Tue,
|
|
2
|
+
* @vkontakte/calls-sdk v2.4.4-dev.717e1c2.0
|
|
3
|
+
* Tue, 07 Dec 2021 12:33:29 GMT
|
|
4
|
+
* https://st.mycdn.me/static/callssdk/2-4-4/doc/
|
|
4
5
|
*/
|
|
5
6
|
|
|
6
|
-
var jr=Object.defineProperty;var Xi=Object.getOwnPropertySymbols;var Kr=Object.prototype.hasOwnProperty,$r=Object.prototype.propertyIsEnumerable;var Zi=(a,e,t)=>e in a?jr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,er=(a,e)=>{for(var t in e||(e={}))Kr.call(e,t)&&Zi(a,t,e[t]);if(Xi)for(var t of Xi(e))$r.call(e,t)&&Zi(a,t,e[t]);return a};var qa=typeof require!="undefined"?require:a=>{throw new Error('Dynamic require of "'+a+'" is not supported')};var s=(a,e,t)=>new Promise((i,r)=>{var n=p=>{try{l(t.next(p))}catch(f){r(f)}},c=p=>{try{l(t.throw(p))}catch(f){r(f)}},l=p=>p.done?i(p.value):Promise.resolve(p.value).then(n,c);l((t=t.apply(a,e)).next())});import Hr from"webrtc-adapter";var dt=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 lt=class{log(e,t,i=!1){}destroy(){}};var Q=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var pt=class extends Q{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 Fe=Qt;var zt;(function(i){i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT"})(zt||(zt={}));var Le=zt;var Xt;(function(t){t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP"})(Xt||(Xt={}));var Zt=Xt;var ei;(function(t){t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD"})(ei||(ei={}));var tr=ei;var ti;(function(i){i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL"})(ti||(ti={}));var ii=ti;function ir(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function rr(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 ri;(function(R){R.CAMERA_PERMISSION="camera",R.MIC_PERMISSION="mic",R.CAMERA_ACCESS="cameralock",R.MIC_ACCESS="miclock",R.MIC_NOT_FOUND="nomic",R.SCREEN_PERMISSION="screenpermission",R.SCREEN_ACCESS="screenlock",R.CONNECTION="connection",R.NETWORK="network",R.UNKNOWN="unknown",R.UNSUPPORTED="unsupported",R.SIGNALING_FAILED="signalingfailed",R.API="api",R.AUTH="auth"})(ri||(ri={}));var ae=ri;var ai;(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"})(ai||(ai={}));var A=ai;var ni;(function(i){i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING"})(ni||(ni={}));var ue=ni;var si;(function(i){i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT"})(si||(si={}));var Ge=si;var oi;(function(r){r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP"})(oi||(oi={}));var H=oi;var ci;(function(r){r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry"})(ci||(ci={}));var Ue=ci;var di;(function(i){i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT"})(di||(di={}));var Se=di;var li;(function(m){m.TRANSMITTED_DATA="transmitted-data",m.ACCEPTED_CALL="accepted-call",m.HUNGUP="hungup",m.PARTICIPANT_ADDED="participant-added",m.PARTICIPANT_JOINED="participant-joined",m.CLOSED_CONVERSATION="closed-conversation",m.MEDIA_SETTINGS_CHANGED="media-settings-changed",m.PARTICIPANT_STATE_CHANGED="participant-state-changed",m.RATE_CALL_DATA="rate-call-data",m.FEATURE_SET_CHANGED="feature-set-changed",m.TOPOLOGY_CHANGED="topology-changed",m.PRODUCER_UPDATED="producer-updated",m.CONSUMER_ANSWERED="consumer-answered",m.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",m.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",m.SETTINGS_UPDATE="settings-update",m.VIDEO_QUALITY_UPDATE="video-quality-update",m.REGISTERED_PEER="registered-peer",m.SWITCH_MICRO="switch-micro",m.RECORD_STARTED="record-started",m.RECORD_STOPPED="record-stopped",m.REALLOC_CON="realloc-con",m.AUDIO_ACTIVITY="audio-activity",m.SPEAKER_CHANGED="speaker-changed",m.STALLED_ACTIVITY="stalled-activity",m.CHAT_MESSAGE="chat-message",m.CUSTOM_DATA="custom-data",m.ROLES_CHANGED="roles-changed",m.MUTE_PARTICIPANT="mute-participant",m.PIN_PARTICIPANT="pin-participant",m.OPTIONS_CHANGED="options-changed",m.NETWORK_STATUS="network-status",m.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",m.PROMOTE_PARTICIPANT="promote-participant",m.CHAT_ROOM_UPDATED="chat-room-updated",m.PROMOTION_APPROVED="promotion-approved",m.JOIN_LINK_CHANGED="join-link-changed"})(li||(li={}));var k=li;var pi;(function(h){h.ERROR="callError",h.DEVICES="callDevices",h.CALL_SPEC_ERROR="callSpecError",h.ICE_CONNECTION_STATE="callIceConnectionState",h.ICE_CONNECTION_TYPE="callIceConnectionType",h.ICE_RESTART="callIceRestart",h.PUSH="callPush",h.OUTGOING_CALL="callStart",h.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",h.JOIN_CONVERSATION="callJoinConversation",h.ACCEPTED_OUTGOING="callAcceptedOutgoing",h.ACCEPT_INCOMING="callAcceptIncoming",h.DECLINE_INCOMING="callDeclineIncoming",h.ACCEPT_CONCURRENT="callAcceptConcurrent",h.HANGUP="callHangup",h.MEDIA_STATUS="callMediaStatus",h.DEVICE_CHANGED="callDeviceChanged",h.SOCKET_ACTION="callSocketAction",h.ADD_PARTICIPANT="callAddParticipant",h.REMOVE_PARTICIPANT="callRemoveParticipant",h.POOR_CONNECTION="callPoorConnection",h.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",h.RELAY_POLICY="callForceRelay",h.PAT_ALLOCATED="patAllocate",h.PAT_DEALLOCATED="patDeallocate",h.PAT_ERROR="patError",h.PAT_WAITING_TIME_ERROR="patWaitingTimeError",h.PAT_OUTDATED_RESPONSE="patOutdatedResponse"})(pi||(pi={}));var g=pi;var ui;(function(t){t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat"})(ui||(ui={}));var Ae=ui;var ut;(function(t){t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error"})(ut||(ut={}));var ar=ut;function nr(a){switch(a){case 1:return ut.NO_AVAILABLE_TRACKS;default:return ut.UNKNOWN_ERROR}}var mi;(function(t){t.CREATOR="CREATOR",t.ADMIN="ADMIN"})(mi||(mi={}));var ze=mi;function mt(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var hi;(function(t){t.USER="USER",t.GROUP="GROUP"})(hi||(hi={}));var ee=hi;var _i=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 sr=2*1024*1024,qr=512*1024,ht=100*1024,Jr=5,gi="_okcls_logs_session_",Yr=3e4,or=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=sr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(gi)!==0)continue;let i=e.getItem(t);if(!i){lr(t);continue}let r=dr(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(ht)}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(gi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(lr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>sr||this.length>Jr-1||this.size+e>this.available);)this.deleteOldestItem()}};function cr(){return`${gi}${Date.now()}`}function dr(a){return new Blob([a]).size}function lr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function fi(){let a=je.toString();if(!Ee.available||!a)return;let e=dr(a);Ee.cleanup(e);try{window.localStorage.setItem(Ot,a)}catch(t){if(console.warn("Failed to write log to storage",t),Ee.storageSize=Ee.size+e,Ee.cleanup(ht+e),Ee.available>=ht+e){fi();return}if(e>ht){je.bisect(),fi();return}Ee.storageSize=0;return}e>qr&&(Ee.add(Ot,e),Ot=cr(),je.clear(),Ee.cleanup(ht))}function Si(){!Ee.available||!je.length||fi()}function Qr(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=je.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 zr(t,i),i}function zr(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 pr(a,e){!Ee.available||(je.push({t:Date.now(),l:a,d:e}),Ei||(Ei=window.setTimeout(()=>{Ei=null,Si()},Yr)))}function vi(){Ee||(Ee=new or,je=new _i,Ot=cr(),window.addEventListener("beforeunload",Si))}var Ee,je,Ot,Ei=null;window.__VKCallsSDKLogs__=(a=!1)=>(Ee||vi(),Si(),Qr(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 E=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(E._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(E._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(E._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(te.accessToken=e.apiAuth.accessToken,te.sessionKey=e.apiAuth.sessionKey,te.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(E._params,e)}static get(e){return E._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.4.4-beta.9"}static get debug(){return!1}static get protocolVersion(){return 5}static get platform(){return E._params.platform}static set platform(e){E._params.platform=e}static get clientType(){return E._params.clientType}static set clientType(e){E._params.clientType=e}static get device(){return E._params.device}static get apiAppId(){return 42}static get apiKey(){return E._params.apiKey}static get apiEnv(){switch(E._params.apiEnv){case"TEST":return{api:"https://apitest.ok.ru/api/",connect:"https://test.ok.ru/"};case"VIDEOTEST":return{api:"https://videotestapi.ok.ru/api/",connect:"https://test.ok.ru/"};case"DEV":return{api:"https://1.api.an-eremeev.devdc.odkl.ru/api/",connect:"https://1.web.an-eremeev.devdc.odkl.ru/"};default:return{api:"https://api.ok.ru/",connect:"https://connect.ok.ru/"}}}static get authToken(){return E._params.authToken}static set authToken(e){E._params.authToken=e}static get anonymToken(){return E._params.anonymToken}static set anonymToken(e){E._params.anonymToken=e}static get domain(){return E._params.domain}static get iceServers(){return E._params.iceServers}static set iceServers(e){E._params.iceServers=e}static get wssBase(){return E._params.wssBase}static set wssBase(e){E._params.wssBase=e}static get wssToken(){return E._params.wssToken}static set wssToken(e){E._params.wssToken=e}static get signalingReconnectDelay(){return E._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return E._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return E._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return E._params.waitConnectionDelay}static get waitResponseDelay(){return E._params.waitResponseDelay}static get waitMessageDelay(){return E._params.waitMessageDelay}static get debugLog(){return E._params.debugLog}static get forceRelayPolicy(){return E._params.forceRelayPolicy}static set forceRelayPolicy(e){E._params.forceRelayPolicy=e}static get videoMinWidth(){return E._params.videoMinWidth}static get videoMaxWidth(){return E._params.videoMaxWidth}static set videoMaxWidth(e){E._params.videoMaxWidth=e}static get videoMinHeight(){return E._params.videoMinHeight}static get videoMaxHeight(){return E._params.videoMaxHeight}static set videoMaxHeight(e){E._params.videoMaxHeight=e}static get videoAspectRatio(){return E._params.videoAspectRatio}static get videoFrameRate(){return E._params.videoFrameRate}static get videoFacingMode(){return E._params.videoFacingMode}static get screenFrameRate(){return E._params.screenFrameRate}static get videoEffects(){return E._params.videoEffects}static set videoEffects(e){E._params.videoEffects=e}static get videoEffectMaxWidth(){return E._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){E._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return E._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){E._params.videoEffectMaxHeight=e}static get voiceParams(){return E._params.voiceParams}static get specListenerParams(){return E._params.specListenerParams}static get iceRestartWaitTime(){return E._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return E._params.transportConnectionWaitTime}static get statisticsInterval(){return E._params.statisticsInterval}static set statisticsInterval(e){E._params.statisticsInterval=e}static get networkStatisticsInterval(){return E._params.networkStatisticsInterval}static get perfStatReportEnabled(){return E._params.perfStatReportEnabled}static get producerNotificationDataChannel(){return E._params.producerNotificationDataChannel}static get producerCommandDataChannel(){return E._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return E._params.consumerScreenDataChannel}static set consumerScreenDataChannel(e){E._params.consumerScreenDataChannel=e}static get producerScreenDataChannel(){return E._params.producerScreenDataChannel&&E._params.producerNotificationDataChannel}static set producerScreenDataChannel(e){E._params.producerScreenDataChannel=e}static get noiseSuppression(){return E._params.noiseSuppression}static set noiseSuppression(e){E._params.noiseSuppression=e}static get preferH264(){return E._params.preferH264}static get preferVP9(){return E._params.preferVP9}static get audioNack(){return E._params.audioNack}static get consumerScreenTrack(){return E._params.consumerScreenTrack&&E._params.consumerScreenDataChannel}static get producerScreenTrack(){return E._params.producerScreenTrack&&E._params.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=E._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get videoTracksCount(){return E._params.videoTracksCount}static get breakVideoPayloadTypes(){return E._params.breakVideoPayloadTypes}static get filteredMessages(){return E._params.filteredMessages}static get batchParticipantsOnStart(){return E._params.batchParticipantsOnStart}static get participantStateMapped(){return E._params.participantStateMapped}},d=E;d._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"PROD",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!1,producerScreenTrack:!1,videoTracksCount:0,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!1};var q;(function(p){p.WAITING_HALL="WAITING_HALL",p.WAITING="WAITING",p.CONNECTING="CONNECTING",p.CONNECTED="CONNECTED",p.RECONNECT="RECONNECT",p.ERROR="ERROR",p.HANGUP="HANGUP",p.PERMISSIONS="PERMISSIONS"})(q||(q={}));function V(a,...e){let t=d.get(a);t&&setTimeout(t,0,...e)}function Ve(a){return Object.assign({},a)}function Xe(a){return a.slice()}var Ii;(function(pe){function a(T,U){V("onLocalStream",T,Ve(U))}pe.onLocalStream=a;function e(T,U){V("onScreenStream",T,Ve(U))}pe.onScreenStream=e;function t(T,U){V("onLocalStreamUpdate",Ve(T),U)}pe.onLocalStreamUpdate=t;function i(T){V("onLocalStatus",T)}pe.onLocalStatus=i;function r(T,U){V("onRemoteStream",T,U)}pe.onRemoteStream=r;function n(T,U,de){V("onRemoteLive",T,U,de)}pe.onRemoteLive=n;function c(T,U){V("onRemoteScreenStream",T,U)}pe.onRemoteScreenStream=c;function l(T,U,de,ct){V("onConversation",T,Ve(U),ct)}pe.onConversation=l;function p(T,U){V("onRemoteMediaSettings",T,Ve(U))}pe.onRemoteMediaSettings=p;function f(T,U){V("onRemoteParticipantState",T,Ve(U))}pe.onRemoteParticipantState=f;function b(T,U,de=null){V("onRemoteStatus",T,U,de)}pe.onRemoteStatus=b;function M(T,U,de=null){V("onParticipantStatus",T,U,de)}pe.onParticipantStatus=M;function j(){V("onPermissionsRequested")}pe.onPermissionsRequested=j;function re(T){V("onPermissionsError",T)}pe.onPermissionsError=re;function R(T){V("onRemoteRemoved",T)}pe.onRemoteRemoved=R;function ge(T,U,de){V("onCallState",T,U,Ve(de))}pe.onCallState=ge;function De(T,U){V("onDeviceSwitched",T,U)}pe.onDeviceSwitched=De;function he(T,U,de,ct=!1,Jt=!1,Yt=null,Wr=null){V("onMuteStates",Ve(T),Xe(U),Xe(de),ct,Jt,Yt,Wr)}pe.onMuteStates=he;function F(T,U){V("onRolesChanged",T,Xe(U))}pe.onRolesChanged=F;function le(T){V("onLocalRolesChanged",Xe(T))}pe.onLocalRolesChanged=le;function Pe(T,U){V("onPinnedParticipant",T,U)}pe.onPinnedParticipant=Pe;function be(T){V("onLocalPin",T)}pe.onLocalPin=be;function ot(T){V("onOptionsChanged",Xe(T))}pe.onOptionsChanged=ot;function Qi(){V("onCallAccepted")}pe.onCallAccepted=Qi;function zi(){V("onRateNeeded")}pe.onRateNeeded=zi;function C(T){V("onSpeakerChanged",T)}pe.onSpeakerChanged=C;function y(T){V("onVolumesDetected",Xe(T))}pe.onVolumesDetected=y;function O(T,U){V("onLocalVolume",T,U)}pe.onLocalVolume=O;function h(T,U){V("onJoinStatus",T,U)}pe.onJoinStatus=h;function D(T,U){V("onHangup",T,U)}pe.onHangup=D;function Te(T){V("onMultipartyChatCreated",Ve(T))}pe.onMultipartyChatCreated=Te;function z(){V("onDeviceChange")}pe.onDeviceChange=z;function L(T){V("onFingerprintChange",T)}pe.onFingerprintChange=L;function X(){V("onTokenExpired")}pe.onTokenExpired=X;function _(T,U,de=!1){V("onChatMessage",T,U,de)}pe.onChatMessage=_;function K(T,U,de=!1){V("onCustomData",T,U,de)}pe.onCustomData=K;function ce(T,U,de,ct,Jt,Yt){V("onRecordStarted",T,U,de,ct,Jt,Yt)}pe.onRecordStarted=ce;function m(){V("onRecordStopped")}pe.onRecordStopped=m;function xe(T){V("onLocalNetworkStatusChanged",T)}pe.onLocalNetworkStatusChanged=xe;function Y(T){V("onNetworkStatusChanged",T)}pe.onNetworkStatusChanged=Y;function Me(T,...U){V("onDebugMessage",T,...U)}pe.onDebugMessage=Me;function _e(T,U){let de=Object.assign({},T,{memory:U});V("onStatistics",de)}pe.onStatistics=_e;function oe(){V("onAutoplayError")}pe.onAutoplayError=oe;function Z(T,U,de){V("onChatRoomUpdated",T,U,de)}pe.onChatRoomUpdated=Z})(Ii||(Ii={}));var v=Ii;var me;(function(r){r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR"})(me||(me={}));var Ci;(function(le){let a="📞",e=(Pe,...be)=>{v.onDebugMessage(Pe,...be)},t=!1,i=(Pe,be)=>(...ot)=>{Pe(...ot),pr(be,ot)},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,me.DEBUG),f=e.bind(null,me.LOG),b=e.bind(null,me.WARN),M=e.bind(null,me.ERROR);le.debug=p,le.log=f,le.warn=b,le.error=M;function De(){return t}le.enabled=De;function he(Pe){t=Pe,d.debugLog&&vi(),Pe?(le.debug=d.debugLog?i(r,me.DEBUG):r,le.log=d.debugLog?i(n,me.LOG):n,le.warn=d.debugLog?i(c,me.WARN):c,le.error=d.debugLog?i(l,me.ERROR):l):(le.debug=d.debugLog?i(p,me.DEBUG):p,le.log=d.debugLog?i(f,me.LOG):f,le.warn=d.debugLog?i(b,me.WARN):b,le.error=d.debugLog?i(M,me.ERROR):M)}le.toggle=he;function F(Pe,...be){switch(Pe){case me.DEBUG:le.debug(...be);break;case me.LOG:le.log(...be);break;case me.WARN:le.warn(...be);break;case me.ERROR:le.error(...be);break}}le.send=F})(Ci||(Ci={}));var o=Ci;import St from"big-integer";var Ti="_okcls_",Ze=(()=>{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 Xr(a){let e=Ze?Ze.getItem(Ti+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function Zr(a,e){try{Ze&&Ze.setItem(Ti+a,JSON.stringify(e))}catch(t){}}function ea(a){Ze&&Ze.removeItem(Ti+a)}var Ri;(function(i){function a(r){return Xr(r)||null}i.get=a;function e(r,n){Zr(r,n)}i.set=e;function t(r){ea(r)}i.remove=t})(Ri||(Ri={}));var He=Ri;var Ke=null,yi=null,Dt=[],Mt=[],Pi=[],_t=null,gt=null,bi=null,Ai=!1,Oi=!1,wt,et,kt,ur=!1,mr=!1,Di=null,Mi="",Nt=[],wi=null,hr=navigator.appVersion,ta=navigator.appName,Ce=navigator.userAgent,ki;(function(r){r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right"})(ki||(ki={}));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 ia(){return s(this,null,function*(){Ke=null,yield xt()})}function ra(){Ke=null,xt().then(()=>v.onDeviceChange())}function xt(){return s(this,null,function*(){return Ke||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!yi&&navigator.mediaDevices.addEventListener&&(yi=I.throttle(ra,1e3),navigator.mediaDevices.addEventListener("devicechange",yi)),Ke=navigator.mediaDevices.enumerateDevices().then(a=>{Dt=a.filter(r=>r.kind==="videoinput"?(r.label&&(Ai=!0),!0):!1),Mt=a.filter(r=>r.kind==="audioinput"?(r.label?Oi=!0:$e.isMobile()&&$e.browserName()==="Firefox"&&(Oi=Ai),!0):!1),Pi=a.filter(r=>r.kind==="audiooutput");let e=He.get("videoinput"),t=He.get("audioinput"),i=He.get("audiooutput");return _t=Dt.find(r=>r.deviceId===e)||null,gt=Mt.find(r=>r.deviceId===t)||null,bi=Pi.find(r=>r.deviceId===i)||null,Ke=Promise.resolve(a),a}).catch(()=>(Ke=null,[]))))})}function aa(){return s(this,null,function*(){return $e.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(ur=!0),/^a=mid:0$/m.test(t.sdp)&&(mr=!0),a()}).catch(a)}):Promise.resolve()})}function Lt(a,e){return s(this,null,function*(){o.debug("Try to get media",a.getNative());let t=$e.hasPermissions(a.isVideo());!t&&!e&&v.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield ia()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?ae.CAMERA_PERMISSION:ae.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?ae.CAMERA_ACCESS:ae.MIC_ACCESS;break}if(a.canSimplify())return Lt(a.simplify(),e);let r=e||ae.UNKNOWN;throw v.onPermissionsError(r),r}})}function na(a){return s(this,null,function*(){o.debug("Try to get screen",a.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(a.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(o.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw ae.SCREEN_PERMISSION;default:throw ae.SCREEN_ACCESS}}})}function Ni(){return Nt.length||(Nt=(()=>{let a,e=!1,t=0,i=Ce.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return a=/\brv[ :]+(\d+)/g.exec(Ce),["IE",a&&a[1]||"Unknown",e,t];if(i[1]==="Safari"){if(a=Ce.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(a=Ce.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,a[1]];if(a=Ce.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t];if(a=Ce.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t];if(a=Ce.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),a=Ce.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t];if(a=Ce.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t];if(a=Ce.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t];if(a=Ce.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t]}return a=Ce.match(/version\/(\d+)/i),[i[2]?i[1]:ta,a&&a[1]||i[2]||hr,e,t]})()),Nt}var $e;(function(z){function a(){return s(this,null,function*(){return yield aa(),xt()})}z.init=a;function e(){return Dt}z.getCameras=e;function t(){return Mt}z.getMicrophones=t;function i(){return Pi}z.getOutput=i;function r(){return Dt.length>0}z.hasCamera=r;function n(){return Mt.length>0}z.hasMicrophone=n;function c(){return _t}z.getSavedCamera=c;function l(){return gt}z.getSavedMicrophone=l;function p(){return bi}z.getSavedOutput=p;function f(){return Ai}z.hasCameraPermission=f;function b(){return Oi}z.hasMicrophonePermission=b;function M(L=!1){return b()?r()&&L?f():!0:!1}z.hasPermissions=M;function j(L=!1,X=!0){return s(this,null,function*(){let _=n()&&X,K=r()&&L,ce;if(!_&&!K)ce=new MediaStream;else try{ce=yield Lt(new ft(_,K))}catch(m){ce=new MediaStream}return ce.getVideoTracks().length||ce.addTrack(F()),ce.getAudioTracks().length||ce.addTrack(he()),ce})}z.getUserMedia=j;function re(){return s(this,null,function*(){return na(new _r(window.screen.width,window.screen.height))})}z.getScreenMedia=re;function R(L,X=!1){return s(this,null,function*(){let _=X?d.videoEffectMaxWidth:d.videoMaxWidth,K=X?d.videoEffectMaxHeight:d.videoMaxHeight;return Lt(new ft(!1,L||!0,_,K))})}z.getUserVideo=R;function ge(L){return s(this,null,function*(){return Lt(new ft(L||!0,!1))})}z.getUserAudio=ge;function De(L,X){return s(this,null,function*(){let K=(yield xt()).find(ce=>ce.kind===L&&ce.deviceId===X);return K?(L==="videoinput"?_t=K:L==="audioinput"?gt=K:L==="audiooutput"&&(bi=K),He.set(L,X),K):null})}z.saveDeviceId=De;function he(){if(!kt||kt.readyState==="ended"){let L=Te(),X=L.createMediaStreamDestination(),_=L.createGain();_.gain.value=1e-5,_.connect(X),_.connect(L.destination);let K=L.createOscillator();K.type="sine",K.frequency.value=0,K.connect(_),K.start(),kt=X.stream.getAudioTracks()[0]}return Object.assign(kt.clone(),{enabled:!1})}z.getSilentMediaTrack=he;function F(L=d.videoMinWidth,X=d.videoMinHeight){return et||(et=document.createElement("canvas"),et.getContext("2d")),et.width=L,et.height=X,(!wt||wt.readyState==="ended")&&(wt=et.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(wt.clone(),{enabled:!1})}z.getBlackMediaTrack=F;function le(){if(O()==="Edge"&&h()<70)return!1;try{let L=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&L.RTCPeerConnection&&L.RTCIceCandidate&&L.RTCSessionDescription&&L.HTMLCanvasElement&&L.HTMLCanvasElement.prototype.captureStream&&L.RTCRtpSender&&L.RTCRtpSender.prototype.replaceTrack&&L.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(L){return!1}}z.isBrowserSupported=le;function Pe(){return!!navigator.mediaDevices.getDisplayMedia}z.isScreenCapturingSupported=Pe;function be(){return ur}z.canVP8=be;function ot(){return mr}z.isUnifiedPlan=ot;function Qi(){return z.browserName()==="Opera"&&z.os()==="Windows"}z.isBrokenH264=Qi;function zi(){return!(z.baseChromeVersion()&&z.isMobile())}z.canPreferH264=zi;function C(){return Mi||(Mi=(()=>{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(Ce))return X;return"Unknown"})()),Mi}z.os=C;function y(){return Di===null&&(Di=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(hr)),Di}z.isMobile=y;function O(){return Ni()[0]}z.browserName=O;function h(){return Ni()[1]}z.browserVersion=h;function D(){return Ni()[3]}z.baseChromeVersion=D;function Te(){return wi||(wi=new(window.AudioContext||window.webkitAudioContext)),wi}z.getAudioContext=Te})($e||($e={}));var P=$e;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(A).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 lt{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:{},uid:this._api.getUserId()};typeof t!="undefined"&&(r.custom.param=t),this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch(),this._externalLogger&&this._externalLogger.log(e,t,i)}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){u._instance||(u._instance=new u(e,t))}static log(e,t,i=!1){u._instance&&u._instance.log(e,t,i)}static destroy(){u._instance&&u._instance.destroy(),u._instance=null}};var ne;(function(i){i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS"})(ne||(ne={}));var $;(function(i){i.audio="audio",i.video="video",i.screen="screen"})($||($={}));var xi=class extends Q{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=[ue.AUDIO]){if(this._stream)return;let t=e.includes(ue.VIDEO),i=e.includes(ue.AUDIO);if(!P.isBrowserSupported())throw new N(ae.UNSUPPORTED);try{this._stream=yield P.getUserMedia(t,i),this._mediaSettings.isVideoEnabled=t&&this._stream.getVideoTracks().filter(r=>r.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=i&&this._stream.getAudioTracks().filter(r=>r.enabled).length>0||!1}catch(r){throw new N(r)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t=!1){let i=this.getStream(),r=this._getSendAudioTrack(),n=this.getSendVideoTrack(t);if(!i||!r&&!n)throw new Error("No local stream found");r&&e.addTrack(r,i),n&&e.addTrack(n,i)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return s(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return s(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=I.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);navigator.mediaDevices.addEventListener("devicechange",()=>s(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),c=n&&n.groupId,l=this._stream.getVideoTracks()[0],p=l&&l.enabled&&l.getSettings(),f=p&&p.groupId;if(!c&&!f)return;let b=yield navigator.mediaDevices.enumerateDevices();!e&&c&&(e=!b.find(M=>M.groupId===c)),!t&&f&&(t=!b.find(M=>M.groupId===f)),i()}))}_changeVideoInput(e=null){return s(this,null,function*(){try{let t=e?"stream":"video";if(e=e||(yield P.getUserVideo(void 0,!!this._effect)),!this._stream)e.getTracks().forEach(i=>i.stop());else{d.consumerScreenTrack||this._disableScreenCapture();let i=yield this._videoEffect(this._effect,e.getVideoTracks()[0]);this._stopLocalTrack($.video),u.log(g.DEVICE_CHANGED,t),o.log("Video stream changed"),yield this._replaceLocalTrack(i),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent(ne.SOURCE_CHANGED,{kind:$.video,mediaSettings:this._mediaSettings})}}catch(t){throw u.log(g.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 P.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack($.audio),u.log(g.DEVICE_CHANGED,"audio"),o.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent(ne.SOURCE_CHANGED,{kind:$.audio,mediaSettings:this._mediaSettings})}}catch(t){throw u.log(g.ERROR,"change_audio"),o.error("Microphone change failed",t),t}})}_changeScreen(e){return s(this,null,function*(){try{if(e=e||(yield P.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=d.consumerScreenTrack?t:yield this._videoEffect(null,t);u.log(g.DEVICE_CHANGED,"screen"),o.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,d.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack($.video),this._sendVideoTrack=d.consumerScreenDataChannel?P.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent(ne.SCREEN_STATUS,{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent(ne.SOURCE_CHANGED,{kind:$.screen,mediaSettings:this._mediaSettings})}}catch(t){throw u.log(g.ERROR,"screen"),o.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent(ne.SCREEN_STATUS,{mediaSettings:this._mediaSettings}),this._triggerEvent(ne.SOURCE_CHANGED,{kind:$.screen,mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return s(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,n;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(n=this._stream)==null||n.addTrack(e),this._triggerEvent(ne.TRACK_REPLACED,e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return s(this,null,function*(){if(!d.videoEffects)return t;try{return u.log(g.DEVICE_CHANGED,`effect_${e}`),d.videoEffects.setEffect(e,t)}catch(i){return o.warn("Video effect failed",i),t}})}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 P.getUserVideo(void 0,!!this._effect)).getVideoTracks()[0],t=yield this._videoEffect(this._effect,t)):(t=P.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight),t=yield this._videoEffect(null,t)),this._stopLocalTrack($.video),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent(ne.SOURCE_CHANGED,{kind:$.video,mediaSettings:this._mediaSettings})})}toggleAudio(e){return s(this,null,function*(){if(!this._stream)return;let t;e?t=(yield P.getUserAudio()).getAudioTracks()[0]:t=P.getSilentMediaTrack(),this._stopLocalTrack($.audio),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent(ne.SOURCE_CHANGED,{kind:$.audio,mediaSettings:this._mediaSettings})})}setResolution(e,t){return s(this,null,function*(){if(!d.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled)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 Li;(function(zi){function a(C,y,O,h,D=!1){let Te=/[\r\n]+/,z=`\r
|
|
7
|
-
`;if(!
|
|
8
|
-
`);for(let z of O)if(z.startsWith("a=fingerprint")){let L=z.split(" ");if(L.length===2){y=L[1];break}}if(!y)return St.minusOne;let h=y.split(":"),D=St.zero;for(let z=Math.min(7,h.length-1);z>=0;z--){let L=St(h[z],16);D=D.shiftLeft(8).or(L)}return((z,L)=>{let X=L.value;if(typeof X=="bigint")return St(BigInt.asIntN(z,X));let _=St.one.shiftLeft(z),K=L.and(_.subtract(1));return K.greaterOrEquals(_.subtract(K))?K.subtract(_):K})(64,D)}zi.sdpFingerprint=j;function re(C){return s(this,null,function*(){return new Promise(y=>window.setTimeout(y,C))})}zi.delay=re;function R(C,y,O){let h=[];return C.getSenders().forEach(D=>ge(y,D,D.track,O,h)),h}zi.applySettings=R;function ge(C,y,O,h,D){if(C&&O&&O.kind===$.video){let Te=O.getSettings();if(Te){let z=C.maxBitrateK?C.maxBitrateK*1024:null,L=Te.width,X=Te.height,_=L&&X&&C.maxDimension?Math.max(1,Math.max(L,X)/C.maxDimension):null,K=C.maxFramerate?C.maxFramerate:null,ce=C.degradationPreference?C.degradationPreference:"balanced",m=h[O.id];if(m&&m.bitrate===z&&m.scaleResolutionDownBy===_&&m.maxFramerate===K&&m.degradationPreference===ce){D[O.id]=m;return}D[O.id]={bitrate:z,scaleResolutionDownBy:_,maxFramerate:K,degradationPreference:ce};let xe=y.getParameters();xe.encodings||(xe.encodings=[{}]),xe.encodings.forEach(Y=>{z?Y.maxBitrate=z:delete Y.maxBitrate,_?Y.scaleResolutionDownBy=_:delete Y.scaleResolutionDownBy,K?Y.maxFramerate=K:delete Y.maxFramerate}),xe.degradationPreference=ce,y.setParameters(xe)}}}zi.applyVideoTrackSettings=ge;function De(C,y){Array.isArray(y)||(y=[y]);for(let O of y)if(C.includes(O))return!0;return!1}zi.includesOneOf=De;function he(C){var y;return Object.entries(((y=C.participantState)==null?void 0:y.state)||{}).reduce((O,[h,D])=>(C.participantState&&(O[h]={ts:C.participantState.stateUpdateTs[h],state:D}),O),{})}zi.mapParticipantState=he;function F(C){return Object.entries(C).reduce((y,[O,{state:h}])=>(y[O]=h,y),{})}zi.mapLegacyParticipantState=F;function le(C){return C.map(y=>{let O={uid:y.externalId,mediaSettings:y.mediaSettings,status:y.status,muteStates:y.muteStates,unmuteOptions:y.unmuteOptions};return d.participantStateMapped&&(O.participantState=y.participantState),O})}zi.mapSharedParticipants=le;function Pe(C,y){let O=Object.keys(C),h=Object.keys(y);if(O.length!==h.length)return!1;for(let D of O)if(!h.hasOwnProperty(D)||C[D].state!==y[D].state||C[D].ts!==y[D].ts)return!1;return!0}zi.isEqualParticipantState=Pe;function be(C,y){let O=Object.keys(C),h=Object.keys(y);if(O.length!==h.length)return!1;for(let D of O)if(!y.hasOwnProperty(D)||C[D]!==y[D])return!1;return!0}zi.isObjectsEquals=be;function ot(C,y){if(C.length!==y.length)return!1;for(let O of C)if(y.indexOf(O)<0)return!1;return!0}zi.isArraysEquals=ot;function Qi(C){return!Object.keys(C).length}zi.isEmptyObject=Qi})(Li||(Li={}));var I=Li;var Oe;(function(i){i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP"})(Oe||(Oe={}));var ie;(function(l){function a(p){return p.length?typeof p[0]=="object"?p:p.map(f=>e(f)):[]}l.fromIds=a;function e(p,f=Oe.USER){return{id:p,type:f}}l.fromId=e;function t(p){return{id:p.id,type:p.type==="ANONYM"?Oe.ANONYM:Oe.USER}}l.fromSignaling=t;function i(p){return`{"id":"${p.id}","type":"${p.type}"}`}l.toString=i;function r(p,f=Oe.USER){return i(e(p,f))}l.fromIdToString=r;function n(p){try{return JSON.parse(p)}catch(f){throw new Error(`Failed to parse ExternalId from string '${p}'`)}}l.fromString=n;function c(p,f){return p.id===f.id&&p.type===f.type}l.compare=c})(ie||(ie={}));var Ie;(function(r){r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE"})(Ie||(Ie={}));var Ui=":",fr="s",Sr="m";function qe(a){return a.participantId+(a.mediaType?Ui+fr+a.mediaType:"")+(a.streamName?Ui+Sr+a.streamName:"")}function vt(a){let e=a.split(Ui),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=sa(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 sa(a){for(let e of Object.keys(Ie))if(e===a)return Ie[e];return null}function Vi(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 Ut(a,e){return!(!Vi(a.camera,e.camera)||!Vi(a.screenSharing,e.screenSharing))}function Bi(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(g.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,u.log(g.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(o.log("Failed to fix RV"),u.log(g.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),u.log(g.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,o.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===$.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Vt=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"),v.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=P.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw u.log(g.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var oa=90,ca=3,Bt=class extends Q{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),v.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>oa?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=ca)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var da=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=P.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=da/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 Ft=class extends Q{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&v.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,d.voiceParams.interval)};this._interval=window.setTimeout(t,d.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,ne.SOURCE_CHANGED,r=>{r.kind===$.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 la=1e3;function we(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 pa(a){return(e,t)=>e[a]-t[a]}function Gt(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function ua(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function ma(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Fi(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=ma(t[1])?Fi(t[1]):t[1],e),{})}function ha(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function _a(a){return s(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...a.getReceivers().map(t=>t.getStats())),e.push(...a.getSenders().map(t=>t.getStats()))):e.push(a.getStats()),Promise.all(e).then(ha).then(ua)})}function ga(a){let e=a.filter(We("type","candidate-pair")).sort(pa("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}})),Fi(t)}function fa(a,e){let t=Gt("id",a),i=a.filter(Cr(We("type","inbound-rtp"),We("type","outbound-rtp")));P.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(P.browserName()==="Safari"){let n=a.filter(We("type","track"));r=Gt("trackIdentifier",n)}return i.map(n=>{let c=Number(n.ssrc),l=n.mediaType||n.kind,p=n.trackId,f=n.type,b=n.codecId;if(P.browserName()==="Safari"){let j=/^.+_([\d]+)$/.exec(n.id);if(j&&(c=parseInt(j[1],10)),l=n.id.indexOf("Audio")>0?"audio":"video",e[c]){let re=l+"-"+e[c];r[re]&&(p=r[re].id)}}if(!f||!c||!l)return null;let M={ssrc:c,type:f,kind:l,bytesReceived:we(n,"bytesReceived"),bytesSent:we(n,"bytesSent"),jitter:we(n,"jitter"),packetsLost:we(n,"packetsLost"),packetsReceived:we(n,"packetsReceived"),packetsSent:we(n,"packetsSent"),fractionLost:we(n,"fractionLost"),pliCount:we(n,"pliCount"),firCount:we(n,"firCount"),nackCount:we(n,"nackCount"),userId:e[c]};if(b&&t[b]){let j=t[b];M.clockRate=j.clockRate,M.mimeType=j.mimeType}if(p&&t[p]){let j=t[p];M.frameHeight=j.frameHeight,M.frameWidth=j.frameWidth,M.framesDecoded=j.framesDecoded,M.framesReceived=j.framesReceived,M.framesDropped=j.framesDropped}return Fi(M)}).filter(n=>!!n)}function Sa(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=Gt("ssrc",a.rtps),i=Gt("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let c=t[n],l=i[n];if(!(!c||!l)){if(c.bytesReceived&&c.bytesReceived>l.bytesReceived&&(c.bandwidth=Math.round((c.bytesReceived-l.bytesReceived)/r)),c.bytesSent&&c.bytesSent>l.bytesSent&&(c.bandwidth=Math.round((c.bytesSent-l.bytesSent)/r)),c.packetsReceived)if(c.packetsReceived>l.packetsReceived||c.packetsLost>l.packetsLost){let p=c.packetsLost-l.packetsLost,f=c.packetsReceived-l.packetsReceived;c.packetLoss=parseFloat((100*p/(p+f)).toFixed(2))}else c.packetLoss=0;c.framesDropped&&l.framesDropped&&c.framesDropped>l.framesDropped&&(c.framesDroppedDelta=parseFloat(((c.framesDropped-l.framesDropped)/r).toFixed(0)))}}),a}function Ct(i,r){return s(this,arguments,function*(a,e,t={}){let n=yield _a(a),c={timestamp:Date.now(),transport:ga(n),rtps:fa(n,t)};return e?Sa(c,e):(yield I.delay(la),Ct(a,c,t))})}var Ht=.8,Je=class extends Q{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=w.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=n,this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ne.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ne.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:d.iceServers,iceTransportPolicy:d.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(c){u.log(g.ERROR,"addTrack-direct"),o.error("Unable to add media source tracks",c,{participantId:this._participantId}),this._failedOnCreate=c;return}this._createOffer(!1).catch(c=>{this._state===w.IDLE?this._failedOnCreate=c:this.close(c)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==w.IDLE&&e!==w.CLOSED&&e!==w.FAILED&&this._startStatInterval()}open(e=null){return s(this,null,function*(){if(this._isOpen){o.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(o.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(i){u.log(g.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(w.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(S.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Ut(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(S.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(o.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(w.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(w.CLOSED)),this._triggerEvent(S.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(S.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case k.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case k.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 k.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((n=e.data.sdk)==null?void 0:n.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=I.getPeerIdString(e.peerId);I.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return s(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){o.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw u.log(g.ERROR,"addIceCandidate-direct"),o.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else o.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return s(this,null,function*(){if(!this._remoteCandidates[e]){o.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return s(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){o.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw u.log(g.ERROR,"setRemoteDescription-direct"),o.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){o.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(S.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(S.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return s(this,null,function*(){e.candidate&&this._signaling.ready&&(o.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(o.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>s(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(o.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===w.IDLE||e===w.OPENED?this._setState(w.CONNECTING):this._setState(w.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),u.log(g.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(w.CONNECTED),this._stopReconnection(),I.getPeerConnectionHostInfo(this._pc).then(e=>{e&&u.log(g.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(w.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(o.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},d.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(o.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(W.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(u.log(g.ICE_RESTART),o.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):o.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,o.error("Ice restart failed",{participantId:this._participantId}),u.log(g.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return s(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return o.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw o.error("Unable to create offer",i,{participantId:this._participantId}),u.log(g.ERROR,"createOffer-direct"),i}).then(i=>s(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=Je._patchDescription(i),o.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw o.error("Unable to set local description",i,{participantId:this._participantId}),u.log(g.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return s(this,null,function*(){return o.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw o.error("Unable to create answer",e,{participantId:this._participantId}),u.log(g.ERROR,"createAnswer-direct"),e}).then(e=>s(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=Je._patchDescription(e),o.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw o.error("Unable to set local description",e,{participantId:this._participantId}),u.log(g.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!P.baseChromeVersion();return e.sdp=I.patchSDP(e.sdp,d.preferH264&&P.canPreferH264(),P.isBrokenH264(),d.preferVP9,t&&d.audioNack),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{o.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),u.log(g.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Ct(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:W.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:W.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(S.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,d.statisticsInterval)})};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=he=>he.rtt<=this._networkLimits.goodNet.rtt&&he.loss<=this._networkLimits.goodNet.loss,i=he=>he.rtt>=this._networkLimits.badNet.rtt||he.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((he,F)=>Math.max(he,F.packetLoss||0),0),c={rtt:this._lastNetworkStat.rtt*(1-Ht)+r*Ht,loss:this._lastNetworkStat.loss*(1-Ht)+n*Ht},l=i(c),p=t(c),f=i(this._remoteNetworkStat),b=t(this._remoteNetworkStat),M=i(this._lastNetworkStat),j=t(this._lastNetworkStat),ge=l||f?.2:p&&b?1:0,De=Date.now();if((M!==l||j!==p||De-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},c)},null).catch(he=>{o.warn("Unable to send [bad-net]",he)})),ge){let he={};he[this._participantId]=he[""]=ge,this._triggerEvent(S.NETWORK_STATUS,he)}this._lastNetworkStat.rtt=c.rtt,this._lastNetworkStat.loss=c.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=I.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(v.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=I.applySettings(this._pc,e,this._prevConsumerSettings))}};var Gi;(function(r){r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare"})(Gi||(Gi={}));var Tt=Gi;import{decode as tt}from"messagepack";var Hi=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=tt(r);return Object.entries(l).forEach(([R,ge])=>{let De=vt(R);this.streamDescriptionByCompactId.set(ge,De)}),null;case 2:case 4:let p=tt(r),f=[];for(let R of p){let ge=this.getStreamDescription(R);ge&&f.push(ge.participantId)}return i===2?{type:"notification",notification:k.AUDIO_ACTIVITY,activeParticipants:f}:{type:"notification",notification:k.STALLED_ACTIVITY,stalledParticipants:f};case 3:let b=tt(r);return{type:"notification",notification:k.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(b))==null?void 0:n.participantId};case 5:let M=tt(r);return{type:"notification",notification:k.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:M[0],maxDimension:M[1]}};case 6:let j=tt(r),re={};for(let[R,ge]of Object.entries(j)){let De=(c=this.getStreamDescription(Number(R)))==null?void 0:c.participantId;De&&(re[De]=ge/100)}return{type:"notification",notification:k.NETWORK_STATUS,statuses:re};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return o.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=tt(e),i=[];for(let[r,n]of Object.entries(t)){let c=n[0],l=n[1],p=n[2],f;if(c!==null){if(f=this.getStreamDescription(c),!f){o.error(`could not uncompress participant ID ${c}`);continue}}else f=null;if(p===null){o.error("unexpected null sequenceNumber",r,n);continue}let b=Ae.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,M=l?l>>>0:null;i.push({participantStreamDescription:f,streamId:b,rtpTimestamp:M,sequenceNumber:p})}return{type:"notification",notification:k.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};import Rr from"@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 ke=class{constructor(){this._worker=null}_createWorker(c,l){return s(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((p,f)=>{let b=i.join(","),M=new Blob([e,`exports.default(${b});`],{type:"application/javascript; charset=utf-8"}),j=window.URL.createObjectURL(M);this._worker=new Worker(j),this._worker.onmessage=re=>{switch(re.data.type){case fe.READY:p();break;case fe.ERROR:f(re.data.error);break;case fe.FRAME:t(re.data);break;case fe.DEBUG:o.debug(re.data.message);break;case fe.LOG_ERROR:u.log(g.ERROR,re.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 it=class extends ke{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)},[Rr,Rr.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 Ye=class extends ke{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 va=65536,Wt=class{constructor(e,t){this._decoderReady=!1;this._decoderQueue=[];this._chunks=[];this._onStream=()=>{};this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;o.debug(`StreamBuilder started for participant [${e}]`),this._participantId=e,this._onStream=t,this._useImageBitmap="ImageBitmap"in window,Ye.isBrowserSupported()?this._decoder=new Ye:this._decoder=new it,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)%va!==e.sequence){o.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData();this._decodeFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe})}}destroy(){this._decoder.destroy(),this._removeStream(),this._chunks=[],o.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}};var jt=1,Ea=1,yr=0,Pr=11,br=1,Ar=2,Or=4,Dr=8;function Mr(a,e,t,i,r,n,c){let l=0;e&&(l|=br),t&&(l|=Ar),i&&(l|=Or),c||(l|=Dr);let p=new ArrayBuffer(Pr),f=new DataView(p);if(f.setUint8(0,jt),f.setUint16(1,r),f.setUint32(3,a),f.setUint8(7,n?1:0),f.setUint16(8,yr),f.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 wr(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&br),f=!!(l&Ar),b=!!(l&Or),M=!!(l&Dr);if(t!==jt)throw new Error(`Unexpected protocol version. Got ${t}, expected ${jt}`);return{timestamp:r,start:p,end:f,keyframe:b,sequence:i,isVP9:n,ssrc:c,eos:M,data:a.slice(Pr)}}function kr(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==jt||e.getUint8(1)!==Ea||e.getUint16(2)!==yr)}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=wr(e),i=(c=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:c.participantId;if(!i){o.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];r||(r=new Wt(i,l=>this._onStream(i,l)),this._streamBuilders[i]=r),r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,o.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(Ye.isBrowserSupported()||it.isBrowserSupported())&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};import Nr from"@vkontakte/libvpx";var Ia=1e3,yt=class extends ke{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
|
-
`,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})},[
|
|
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 Ca=16*1024,Ta=11,xr=Ca-Ta,Ra=65536,Wi=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())}};rt.isBrowserSupported()?this._encoder=new rt(e,i):this._encoder=new yt(e,i),this._datachannel.onmessage=r=>{kr(r.data)&&(o.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>o.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,n){let c=Mr(e,t,i,r,Wi,this._encoder.isVP9(),n);return Wi=(Wi+1)%Ra,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+xr),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+xr,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),o.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return rt.isBrowserSupported()||yt.isBrowserSupported()}};var Lr="videochat-epi",bt=class extends Q{constructor(e,t){super();this._previousTimestamp=0;this._signaling=t,this.subscribe(e,S.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Lr)||"",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(Lr,r.estimatedPerformanceIndex)}catch(r){}this._previousTimestamp=i}})}};var ya=90,Pa=4294967295,Re=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=w.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ne.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ne.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,ne.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new 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||w.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==w.IDLE&&e!==w.CLOSED&&e!==w.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(w.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(w.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Ut(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,Re._closeDataChannel(this._producerNotification),Re._closeDataChannel(this._producerCommand),Re._closeDataChannel(this._producerScreen),Re._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(S.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){o.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{o.debug(`[${t}] data channel opened`),r.onerror=n=>{o.error(`[${t}] data channel error`,n)},i(r)}}_openConnection(e=!1){o.debug("ServerTransport: Open single connection");let t={};P.baseChromeVersion()&&(t.sdpSemantics=Re._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=I.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Re._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,Tt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Hi,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(g.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(w.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==w.OPENED&&(this._setState(w.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(S.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(S.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(S.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(S.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
|
|
11
|
-
`).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Ae.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(S.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(S.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!d.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==$.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(P.getBlackMediaTrack()).catch(l=>{o.error("Could not disable video upload",l)});return}let c=this._mediaSource.getSendVideoTrack();if(!r&&n&&c){o.log("Enabling video upload"),this._disabledSenders.delete(i);let l=i.track;l.enabled=c.enabled,i.replaceTrack(c).then(()=>l.stop()).catch(p=>{o.error("Could not enable video upload",p)})}I.applyVideoTrackSettings(e,i,c!=null?c:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(S.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,d.statisticsInterval)};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return s(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Ct(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(S.REMOTE_DATA_STATS,{inbound:{topology:W.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:W.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(c=>c.type==="inbound-rtp"&&c.kind==="audio"&&this._ssrcMap[c.ssrc]==="mix");if(!t)return;let i=Ae.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let c=t.bytesReceived-r.bytesReceived;c>=0&&c<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(S.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex: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:Re._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return s(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,o.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(o.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw o.error("[single] unable to set remote offer",i),u.log(g.ERROR,"setRemoteDescription-single"),i}).then(()=>s(this,null,function*(){if(o.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw o.error("[single] unable to create answer",i),u.log(g.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=I.patchSDP(i.sdp,!1,P.isBrokenH264(),!1),i)).then(i=>s(this,null,function*(){if(o.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw o.error("[single] unable to set local answer",i),u.log(g.ERROR,"setLocalDescription-single"),i}).then(i=>s(this,null,function*(){o.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),o.debug("[single] remote offer has been processed")})).catch(i=>{o.warn("[single] unable to send local answer",i),u.log(g.ERROR,"acceptProducer")}).then(()=>s(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){o.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return s(this,null,function*(){if(!!this._isOpen)switch(e.notification){case k.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case k.REALLOC_CON:this._reconnect();break;case k.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case k.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case k.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case k.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return s(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),d.breakVideoPayloadTypes&&(o.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){o.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent(S.REMOTE_TRACK_REMOVED,i.id,i,n.track)}),i.getTracks().find(n=>n.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(S.REMOTE_TRACK_ADDED,i.id,i,t.track)):o.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){o.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(o.debug("[single] connection state changed",{state:e.connectionState},t),u.log(g.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===w.IDLE||i===w.OPENED?this._setState(w.CONNECTING):e.iceConnectionState==="checking"&&this._setState(w.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(w.RECONNECTING);break;case"connected":this._setState(w.CONNECTED),I.getPeerConnectionHostInfo(e).then(r=>{r&&u.log(g.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(d.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{o.error("ServerTransport: Unable to replace track",r),u.log(g.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=P.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(P.browserName(),P.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return u.log(g.PAT_WAITING_TIME_ERROR,"noConnection"),o.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return u.log(g.PAT_WAITING_TIME_ERROR,"noReceiver"),o.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return o.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let c=r[0].rtpTimestamp;if(!Number.isInteger(c))return u.log(g.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),o.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${c}`),0;let l=t-c&Pa,p=Math.ceil(l/ya);return Math.min(100,Math.max(0,p))}};var S;(function(R){R.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",R.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",R.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",R.REMOTE_ALL_STALL="REMOTE_ALL_STALL",R.REMOTE_DATA_STATS="REMOTE_DATA_STATS",R.STATE_CHANGED="STATE_CHANGED",R.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",R.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",R.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",R.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",R.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",R.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",R.NETWORK_STATUS="NETWORK_STATUS",R.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED"})(S||(S={}));var w;(function(l){l.IDLE="IDLE",l.OPENED="OPENED",l.CONNECTING="CONNECTING",l.RECONNECTING="RECONNECTING",l.CONNECTED="CONNECTED",l.CLOSED="CLOSED",l.FAILED="FAILED"})(w||(w={}));var W;(function(t){t.DIRECT="DIRECT",t.SERVER="SERVER"})(W||(W={}));var ji=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=w.IDLE;this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),e===W.SERVER&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){o.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology===W.DIRECT&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology===W.SERVER&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){o.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){o.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology===W.DIRECT&&this._directTransport&&this._directTransport.open(t),this._topology===W.SERVER&&this._serverTransport&&(this._serverTransport.open(),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),o.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&o.warn(`The participant [${e}] transport has already deallocated`),this._topology===W.DIRECT&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology===W.SERVER&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,w.CLOSED)),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent(S.STATE_CHANGED,i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent(S.STATE_CHANGED,[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent(S.LOCAL_STATE_CHANGED,e))}_onSignalingNotification(e){if(e.notification===k.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===k.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(o.log(`Topology changed ${this._topology} -> ${e.topology}`),u.log(g.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology===W.SERVER&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology===W.DIRECT){let i=e.offerTo||[],r=e.offerToTypes||[],n=i.length&&r.length?I.composeId(i[0],r[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){o.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&o.warn("Topology changed to DIRECT, but the allocated participants count more then one");let c=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=n===c;this._directTransport=this._createDirectTransport(c,l)}this._opened.indexOf(c)>=0&&this._directTransport.open()}this._triggerEvent(S.TOPOLOGY_CHANGED,this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new Je(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),this._dtListeners&&this._dtListeners.length>0&&o.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener(S.REMOTE_TRACK_ADDED,this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener(S.REMOTE_TRACK_REMOVED,this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener(S.REMOTE_DATA_STATS,this._onDirectRemoteDataStats.bind(this)),i.addEventListener(S.STATE_CHANGED,this._onDirectTransportChanged.bind(this,e)),i.addEventListener(S.NETWORK_STATUS,this._onTransportNetworkStatus.bind(this)),i.addEventListener(S.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this,W.DIRECT))),i}_createServerTransport(){let e=new Re(this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!1),this._stListeners&&this._stListeners.length>0&&o.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener(S.REMOTE_TRACK_ADDED,this._onServerRemoteTrackAdded.bind(this)),e.addEventListener(S.REMOTE_TRACK_REMOVED,this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener(S.REMOTE_ALL_STALL,this._onServerRemoteAllStall.bind(this)),e.addEventListener(S.REMOTE_DATA_STATS,this._onServerRemoteDataStats.bind(this)),e.addEventListener(S.STATE_CHANGED,this._onServerTransportChanged.bind(this)),e.addEventListener(S.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener(S.SIGNALLED_ACTIVE_PARTICIPANTS,this._onTransportActiveParticipants.bind(this)),e.addEventListener(S.SIGNALLED_SPEAKER_CHANGED,this._onTransportSpeakerChanged.bind(this)),e.addEventListener(S.SIGNALLED_STALLED_PARTICIPANTS,this._onTransportStalledParticipants.bind(this)),e.addEventListener(S.NETWORK_STATUS,this._onTransportNetworkStatus.bind(this)),e.addEventListener(S.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),e.addEventListener(S.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this,W.SERVER))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;d.noiseSuppression!==e&&(d.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t===w.CONNECTED&&this._topology===W.DIRECT&&this._releaseServerTransport(!0),(t===w.CLOSED||t===w.FAILED)&&(this._releaseDirectTransport(!1),this._topology===W.DIRECT)){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology===W.DIRECT&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e===w.CONNECTED&&this._topology===W.SERVER&&this._releaseDirectTransport(!0),(e===w.CLOSED||e===w.FAILED)&&(this._releaseServerTransport(!1),this._topology===W.SERVER&&(this._allocated=[],this._opened=[])),this._topology===W.SERVER&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent(S.ACTIVE_PARTICIPANTS_NO_SIGNAL)}_onTransportActiveParticipants(e){this._topology===W.SERVER&&this._triggerEvent(S.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_onTransportStalledParticipants(e){this._topology===W.SERVER&&this._triggerEvent(S.SIGNALLED_STALLED_PARTICIPANTS,e)}_onTransportSpeakerChanged(e){this._topology===W.SERVER&&this._triggerEvent(S.SIGNALLED_SPEAKER_CHANGED,e)}_onTransportNetworkStatus(e){this._triggerEvent(S.NETWORK_STATUS,e)}_onRemoteStreamSecond(e,t){this._triggerEvent(S.REMOTE_STREAM_SECOND,e,t)}_onPeerConnectionClosed(e){this._triggerEvent(S.PEER_CONNECTION_CLOSED,e)}_onServerRemoteAllStall(e){this._topology===W.SERVER&&this._triggerEvent(S.REMOTE_ALL_STALL,e)}_onServerRemoteDataStats(e){this._triggerEvent(S.REMOTE_DATA_STATS,e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent(S.REMOTE_TRACK_ADDED,e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent(S.REMOTE_TRACK_REMOVED,e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent(S.REMOTE_DATA_STATS,e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent(S.REMOTE_TRACK_ADDED,e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent(S.REMOTE_TRACK_REMOVED,e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!==W.SERVER?(u.log(g.PAT_WAITING_TIME_ERROR,"wrongTopology"),o.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(u.log(g.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Be;(function(e){e.VOLUMES_DETECTED="VOLUMES_DETECTED"})(Be||(Be={}));var Ki=class extends Q{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,S.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,S.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,S.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,S.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===$.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===$.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===Ae.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent(Be.VOLUMES_DETECTED,e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var at;(function(e){e.SPEAKER_CHANGED="SPEAKER_CHANGED"})(at||(at={}));var $i=class extends Q{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,Be.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,S.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,S.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,S.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>d.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*d.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent(at.SPEAKER_CHANGED,i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent(at.SPEAKER_CHANGED,e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var Kt=class extends Q{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,S.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,Be.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===w.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===w.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),u.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==w.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),u.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),u.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var ba=1e3,Aa=1e4,J;(function(r){r.IDLE="IDLE",r.PROCESSING="PROCESSING",r.ACTIVE="ACTIVE",r.CLOSE="CLOSE"})(J||(J={}));var B=class extends Q{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state=J.IDLE;this._participantState=H.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._signalingServerSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;u.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),u.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new Vt,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),ba))}static current(){return B._current}static hangupAfterInit(){B._activationMutex&&!B._current&&(B._delayedHangup=!0)}static id(){var e,t;return((t=(e=B._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,c=!1){return s(this,null,function*(){if(B._activationMutex)throw u.log(g.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new N(A.FAILED);B._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let l=this._mediaSource.getMediaSettings();t===Le.CHAT||e.length>1?this._logWithMediaSettings(g.OUTGOING_MULTIPARTY_CALL,l):this._logWithMediaSettings(g.OUTGOING_CALL,l);let p=yield this._startConversation(e,t,Fe.OUTGOING,i,r,n,c);if(!this._conversation)throw new N(A.UNKNOWN_ERROR);if(this._participantState=H.ACCEPTED,this._signaling.changeMediaSettings(l),yield this._registerParticipants(p.conversation.participants),this._processConnectionData(p),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new N(A.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let f=Object.values(this._participants),b;return d.batchParticipantsOnStart&&(b=I.mapSharedParticipants(f)),v.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),v.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,b),v.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),B._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(f,q.WAITING),this._conversation}catch(l){throw this._close(l,"Unable to start conversation"),l}finally{B._activationMutex=!1}})}onJoin(e){return s(this,null,function*(){if(B._activationMutex)throw u.log(g.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new N(A.FAILED);B._activationMutex=!0,this._state=J.PROCESSING;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new N(A.UNKNOWN_ERROR);return v.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(o.log("In waiting hall"),B._current=this,B._activationMutex=!1,this._signaling.readyToSend(),v.onLocalStatus(q.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw B._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return s(this,null,function*(){o.debug("Join conversation part 2"),B._activationMutex=!0;try{if(this._participantState=H.ACCEPTED,!this._conversation||!this._mediaSource)throw new N(A.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(A.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=I.mapSharedParticipants(t)),v.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),v.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state=J.ACTIVE,this._changeFeatureSet(),B._current=this,d.batchParticipantsOnStart||this._setParticipantsStatus(t,q.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{B._activationMutex=!1}})}onPush(r){return s(this,arguments,function*(e,t=ee.USER,i){if(B._activationMutex)throw o.warn("Conversation: there is already running activation"),new N(A.REJECTED);B._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new N(A.UNKNOWN_ERROR);if(!n.conversation.participants.find(l=>{var p;return l.state===H.CALLED&&l.id===((p=this._conversation)==null?void 0:p.userId)}))throw o.log("Push rejected (there is an active call)"),u.log(g.PUSH,"rejected"),new N(A.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),u.log(g.PUSH,"accepted"),B._current=this,B._delayedHangup)throw new N(A.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(ii.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>I.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return s(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new N(A.UNKNOWN_ERROR);this._state=J.PROCESSING;let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),v.onCallAccepted(),this._state=J.ACTIVE,this._participantState=H.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return s(this,null,function*(){if(this._state!==J.IDLE)throw u.log(g.ERROR,"acceptIncoming"),o.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new N(A.UNKNOWN_ERROR);this._state=J.PROCESSING,o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=H.ACCEPTED;let i=Object.values(this._participants),r;d.batchParticipantsOnStart&&(r=I.mapSharedParticipants(i)),v.onCallAccepted(),v.onLocalStream(this._mediaSource.getStream(),t),v.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),v.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(Ge.MUTE)||n.includes(Ge.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state=J.ACTIVE,this._changeFeatureSet(),d.batchParticipantsOnStart||this._setParticipantsStatus(i,q.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return s(this,null,function*(){var e;if(this._state!==J.IDLE)throw u.log(g.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state=J.PROCESSING,o.debug("Decline incoming call"),this._logWithMediaSettings(g.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=H.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(A.REJECTED)),this._close(new N(A.REJECTED))})}hangup(){return s(this,null,function*(){o.debug("Hangup");let e=this._state===J.ACTIVE?A.HUNGUP:A.CANCELED;u.log(g.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new N(e))):v.onHangup(new N(A.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return s(this,null,function*(){if(!this._signaling.ready){this._close(new N(A.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=A.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(e,n,r)})}removeParticipant(e,t=!1){return s(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){if(!this._transport)return;let i=[];for(let r of e)(r.state===H.CALLED||r.state===H.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===H.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&o.error(t,e),o.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(A.FAILED):u.log(g.ERROR,e.hangup),B._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([A.CANCELED,A.NOT_FRIENDS,A.CALLEE_IS_OFFLINE,A.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===A.REJECTED&&!e.remote){v.onHangup(e,i),this.destroy();return}if(e.hangup===A.HUNGUP&&(!e.remote||this._participantState===H.CALLED)){v.onHangup(e,i),this.destroy();return}if(e.hangup===A.MISSED&&!e.remote){v.onHangup(e,i),this.destroy();return}if(e.hangup===A.SOCKET_CLOSED&&B._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===A.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state=J.CLOSE,this._participantState=H.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),u.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,v.onHangup(e||new N(A.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;o.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),u.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return s(this,null,function*(){let t=yield this._api.getConversationParams(e);o.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let c=r.urls.filter((l,p,f)=>f.indexOf(l)===p);c.forEach(l=>c.push(`${l}?transport=tcp`)),i.push({urls:c,username:r.username,credential:r.credential})}d.iceServers=i,d.wssBase=t.endpoint,d.wssToken=t.token,t.client_type&&(d.clientType=t.client_type)})}_startConversation(e,t,i,r,n="",c=!1,l=!1){return s(this,null,function*(){let p=I.uuid();o.debug("Conversation: start",{conversationId:p,opponentIds:e,opponentType:t,direction:i});let f=r.includes(ue.VIDEO),b=yield this._api.startConversation(p,e,t,f,n,c,l);o.debug("Api.startConversation",b),yield this._getConversationParams(b.id);let M=yield this._connectSignaling(Ue.START,b);return yield this._setConversation(b,M,i),M})}_joinConversation(e){return s(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n}=e;o.debug("Conversation: join",{conversationId:t,joinLink:n});let c=i.includes(ue.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(A.UNKNOWN_ERROR);o.debug("Api.joinConversation",l),yield this._getConversationParams(l.id);let p=yield this._connectSignaling(Ue.JOIN,l);return yield this._setConversation(l,p,Fe.JOINING),p})}_prepareConversation(r){return s(this,arguments,function*(e,t=ee.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i}),yield this._getConversationParams(e);let n=this._api.getUserId();if(!n)throw new N(A.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(Ue.ACCEPT,c);return B._current&&(B._current._participantState===H.ACCEPTED||B._current._participantState===H.CALLED)?(o.log("Push rejected (busy)"),u.log(g.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(A.BUSY),Promise.reject({hangup:A.BUSY})):(B._current&&(B._current.destroy(),B._current=null),yield this._setConversation(c,l,Fe.INCOMING,t),l)})}_createParticipant(e){return s(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:ve(),participantState:{},state:H.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);return e.externalId?this._api.cacheExternalId(t.id,e.externalId):t.externalId=yield this._getUserId(t.id),t})}_getUserId(e){return s(this,null,function*(){try{return yield this._api.userId(e)}catch(t){throw this._close(new N(A.NETWORK_ERROR),t),t}})}_setConversation(n,c,l){return s(this,arguments,function*(e,t,i,r=ee.USER){let p=t.conversation.participants.map(j=>j.id);yield this._api.prepareUserIds(p);let f=this._api.getUserId();if(!f){let j=(t.conversation.participants||[]).find(re=>I.comparePeerId(re.peerId,t.peerId));if(!j)throw new N(A.UNKNOWN_ERROR);f=Number(j.id),j.idType&&(r=j.idType),this._api.setUserId(f)}let b=I.composeId(f,r),M=yield this._getUserId(b);this._conversation={userId:f,compositeUserId:b,externalId:M,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||W.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),u.log(g.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new N(A.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||W.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new xi;return this.subscribe(e,ne.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,ne.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=I.composeParticipantId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),v.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===H.HUNGUP||t.state===H.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],A.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&ie.fromSignaling(t.externalId),mediaSettings:ve(t.mediaSettings),participantState:I.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?q.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),v.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){I.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Zt.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new ji(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new Bt,this.subscribe(this._transport,S.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,S.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,S.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,S.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,S.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,S.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,S.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,S.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,S.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,S.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,S.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,S.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Fe.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===H.ACCEPTED||t.state===H.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new Ki(this._transport),this.subscribe(this._volumesDetector,Be.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new $i(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,at.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Ft(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Kt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=P.getCameras().length,t=P.getMicrophones().length;o.debug("Cameras: "+e+(P.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(P.hasMicrophonePermission()?"✔":"✖")),u.log(g.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){u.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===H.CALLED||e.state===H.ACCEPTED||this._state===J.CLOSE||!this._participants[e.id]||(t===A.HUNGUP?this._setParticipantsStatus([e],q.HANGUP):this._setParticipantsStatus([e],q.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Ie.CAMERA,stopStream:!0}]),delete this._participants[e.id],v.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){o.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return s(this,null,function*(){o.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===H.ACCEPTED||r.state===H.CALLED)){o.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&ie.fromSignaling(t.externalId),mediaSettings:ve(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],q.WAITING),i?(r.state=H.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=H.CALLED,this._transport.allocate(r.id,!0),u.log(g.ADD_PARTICIPANT))})}_onRemoveParticipant(e){o.debug(`Remove participant [${e}]`);let t=this._participants[e];if(!t){o.warn(`Participant [${e}] isn't in conversation`);return}this._transport&&this._transport.close(t.id),u.log(g.REMOVE_PARTICIPANT)}changeDevice(e){return s(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new Et(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ae.UNKNOWN)})}toggleScreenCapturing(e){return s(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ae.UNKNOWN)})}setVideoStream(e,t=!1){return s(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return s(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return s(this,null,function*(){if(this._mediaSource)return u.log(g.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return s(this,null,function*(){if(this._mediaSource)return u.log(g.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return s(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let n=typeof r.uid=="object"?r.uid:ie.fromId(r.uid),c=ie.toString(n);i[c]=r.priority}for(let r of Object.values(this._participants)){let n=ie.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return s(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}updateDisplayLayout(e){return s(this,null,function*(){if(e.length<1||!this._signaling.ready)return;o.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:ie.fromId(r.uid),c=ie.toString(n),l=this._api.getCachedOkIdByExternalId(n);if(!l){o.log(`Unknown participant external ID ${c}`);continue}let p=qe({participantId:l,mediaType:r.mediaType,streamName:r.streamName}),f=this._participants[l];f&&(f.lastRequestedLayouts[p]=r),B._isStopStreaming(r)?this._streamIdByStreamDescription.has(p)&&!this._cooldownTimestampByStreamDescription.has(p)&&this._cooldownTimestampByStreamDescription.set(p,Date.now()):(this._cooldownTimestampByStreamDescription.delete(p),!this._streamIdByStreamDescription.has(p)&&d.videoTracksCount>0&&this._streamIdByStreamDescription.set(p,null),t[p]=B._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>d.videoTracksCount;){let r=i.next();if(r.done){o.error("Cannot accommodate all streaming requests: tracks available "+d.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]=B._layoutToString({stopStream:!0})}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(o.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=vt(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Ie.STREAM||i.mediaType===Ie.SCREEN)?v.onRemoteLive(r.externalId,i.streamName,null):v.onRemoteStream(r.externalId,null),u.log(g.PAT_DEALLOCATED)):o.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return s(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,n]of Object.entries(t.errorCodeByParticipantId||{})){let c=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=ar.UNKNOWN_ERROR):p=nr(n),i.push({externalId:l.externalId,errorReason:p})}}if(i&&i.length)throw new $t("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+Aa>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(A.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return s(this,arguments,function*(e,t=0,i=[]){o.log(`Chat room updated: ${e}`);let n=[],c=[];i.length&&(i.forEach(l=>{if(l.externalId){let p=ie.fromSignaling(l.externalId);n.push(p),this._api.cacheExternalId(l.id.id,p)}else c.push(I.decomposeId(l.id.id).id)}),c.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(c))),v.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var l,p;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===Ie.SCREEN)return;let i=qe(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){o.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),u.log(g.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,c=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(c<=0){this._streamWaitTimerByStreamDescription.delete(i);let f=t.participantId,b=this._participants[f];if(!b){u.log(g.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${f}`);return}let M=this._streamByStreamId.get(n);if(!M){u.log(g.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}u.log(g.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let j=(l=e.participantStreamDescription)==null?void 0:l.mediaType;if(j===Ie.STREAM||j===Ie.MOVIE)((p=e.participantStreamDescription)==null?void 0:p.streamName)&&v.onRemoteLive(b.externalId,e.participantStreamDescription.streamName,M);else{let re=(d.producerScreenTrack?null:b.secondStream)||M;v.onRemoteStream(b.externalId,re)}}else{o.debug(`Waiting for ${c} until stream ${n} for ${i} is switched`);let f=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),c);this._streamWaitTimerByStreamDescription.set(i,f)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(qe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(qe(i)))return i}else{let i={participantId:t,mediaType:Ie.CAMERA};if(this._streamIdByStreamDescription.has(qe(i)))return i;let r={participantId:t,mediaType:Ie.SCREEN};if(this._streamIdByStreamDescription.has(qe(r)))return r}return o.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?I.includesOneOf(this._conversation.roles,[ze.ADMIN,ze.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!I.includesOneOf(this._conversation.roles,[ze.ADMIN,ze.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return s(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return s(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return s(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return s(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return s(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=rr(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=[],f=null;return c.length&&(c.forEach(b=>{if(b.externalId){let M=ie.fromSignaling(b.externalId);l.push(M),this._api.cacheExternalId(b.id.id,M)}else p.push(I.decomposeId(b.id.id).id)}),p.length&&!l.length&&(l=yield this._api.getExternalIdsByOkIds(p)),n.hasMore&&(f=Er(c[c.length-1].id))),{participants:l,pageMarker:f,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return s(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return s(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return s(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return s(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return s(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return s(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return s(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t){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),v.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return s(this,null,function*(){var t;if(o.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;v.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){o.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state===J.ACTIVE&&v.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){o.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state===J.ACTIVE&&(d.participantStateMapped?v.onRemoteParticipantState(i.externalId,i.participantState):v.onRemoteParticipantState(i.externalId,I.mapLegacyParticipantState(i.participantState))))}_onSignalingNotification(e){switch(e.notification){case k.ACCEPTED_CALL:return this._onAcceptedCall(e);case k.HUNGUP:return this._onHungup(e);case k.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case k.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case k.CLOSED_CONVERSATION:return this._onClosedConversation(e);case k.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case k.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case k.RATE_CALL_DATA:return this._onNeedRate();case k.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case k.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case k.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case k.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case k.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case k.REGISTERED_PEER:return this._onPeerRegistered(e);case k.SWITCH_MICRO:return this._onMicSwitched(e);case k.CHAT_MESSAGE:return this._onChatMessage(e);case k.CUSTOM_DATA:return this._onCustomData(e);case k.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case k.RECORD_STOPPED:return this._onRecordInfo(null);case k.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case k.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case k.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case k.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case k.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case k.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case k.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return s(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let c=I.composeParticipantId(n),l=n.roles||[];if(c===this._conversation.compositeUserId){t=ve(n.mediaSettings),mt(this._conversation.roles,l)||this._onRolesChanged(c,l);continue}r.push(c);let p=this._participants[c];if(!p)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let f=ve(n.mediaSettings);gr(f,p.mediaSettings)||this._changeRemoteMediaSettings(c,f);let b=I.mapParticipantState(n),M=p.participantState;I.isEqualParticipantState(b,M)||this._changeRemoteParticipantState(c,b),mt(l,p.roles)||this._onRolesChanged(p.id,l)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],A.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){o.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return s(this,null,function*(){let t=I.composeMessageId(e),i=I.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new N(A.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:ve(e.mediaSettings)}),r=this._participants[t]),r.state=H.ACCEPTED,r.mediaSettings=ve(e.mediaSettings),this._logWithMediaSettings(g.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Fe.OUTGOING&&(this._state===J.IDLE||this._state===J.PROCESSING)&&(this._state=J.ACTIVE,this._changeFeatureSet()),this._state===J.ACTIVE&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){o.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=I.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new N(e.reason));return}let i=this._participants[t];if(!i){o.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===A.REJECTED?H.REJECTED:H.HUNGUP,this._state!==J.CLOSE&&this._removeParticipant(i,A.HUNGUP)}_onAddedParticipant(e){return s(this,null,function*(){var r,n;o.debug(`Participant added [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state!==H.HUNGUP&&i.state!==H.REJECTED){o.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&ie.fromSignaling(e.participant.externalId),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:I.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=H.CALLED,i.mediaSettings=ve((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=I.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],q.WAITING),this._state===J.ACTIVE&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onJoinedParticipant(e){return s(this,null,function*(){var r;o.debug(`Participant joined [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state===H.ACCEPTED){o.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&ie.fromSignaling(e.participant.externalId),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:I.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Fe.OUTGOING&&(this._state===J.IDLE||this._state===J.PROCESSING)&&(this._state=J.ACTIVE,this._changeFeatureSet()),i.state=H.ACCEPTED,i.mediaSettings=ve(e.mediaSettings),i.participantState=I.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],q.CONNECTED):this._setParticipantsStatus([i],q.WAITING),this._state===J.ACTIVE&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id])),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new N(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=I.composeMessageId(e);this._changeRemoteMediaSettings(t,ve(e.mediaSettings))}_onParticipantStateChanged(e){let t=I.composeMessageId(e);this._changeRemoteParticipantState(t,I.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),v.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return s(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ve(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),d.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Bi(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=Bi(this._serverSettings,c),o.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=I.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return s(this,null,function*(){v.onDeviceSwitched(ue.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return s(this,null,function*(){let t=I.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),v.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return s(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=I.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),v.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return s(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getUserId(e.initiator);v.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else v.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!mt(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,v.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!mt(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,v.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return s(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],c=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){o.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let l=this._participants[e.participantId];l&&(o.debug(`Mute states for participant [${e.participantId}] changed`,i),v.onMuteStates(i,r,n,e.muteAll,e.unmute,l.externalId,c==null?void 0:c.externalId));return}I.isObjectsEquals(this._conversation.muteStates,i)&&I.isArraysEquals(this._conversation.unmuteOptions,r)&&!n.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(n,e.muteAll,e.unmute,t,c)))})}_processMuteState(){return s(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==H.ACCEPTED)return;let c=Object.assign({},this._conversation.muteStates),l=this._conversation.unmuteOptions,p=this._mediaSource.getMediaSettings(),f=Object.entries(c);for(let[b,M]of f)if(!(M!==Ge.MUTE&&M!==Ge.MUTE_PERMANENT)&&(this._isCallAdmin()&&M===Ge.MUTE_PERMANENT&&(c[b]=Ge.MUTE),!!e.includes(b)))switch(b){case ue.VIDEO:p.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(v.onDeviceSwitched(ue.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case ue.AUDIO:p.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(v.onDeviceSwitched(ue.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case ue.SCREEN_SHARING:p.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(v.onDeviceSwitched(ue.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}v.onMuteStates(c,l,e,t,i,null,n==null?void 0:n.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?v.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&v.onLocalPin(!0)),this._participants[e]?v.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&v.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!ir(this._conversation.options,e)&&(this._conversation.options=e,v.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let n;if(i===this._conversation.compositeUserId||i==="")n=this._conversation.networkRating;else if(this._participants[i])n=this._participants[i].networkRating;else continue;if(n!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,v.onLocalNetworkStatusChanged(r);else{let c=this._participants[i];c.networkRating=r,t.push({uid:c.externalId,rating:r})}}if(t.length===0)return;o.log("Received network status update: ",e),v.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){v.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,d.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){o.error("Received remote stream notification for a participant that has no track associated with it",r);return}let n=this._streamIdByStreamDescription.get(r);if(!n||this._streamWaitTimerByStreamDescription.has(r)){o.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let c=this._streamByStreamId.get(n);if(!c){u.log(g.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}v.onRemoteStream(i.externalId,i.secondStream||c)}else{let r=t||i.remoteStream;r&&v.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===W.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state===J.ACTIVE,t=this._conversation.features.includes(tr.ADD_PARTICIPANT);v.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&v.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}v.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(v.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return s(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===w.CONNECTED?i=q.CONNECTED:t===w.CONNECTING||t===w.OPENED?i=q.CONNECTING:t===w.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===w.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===w.CONNECTED&&v.onLocalStatus(q.CONNECTED),e===w.CONNECTING&&v.onLocalStatus(q.CONNECTING),e===w.RECONNECTING&&v.onLocalStatus(q.RECONNECT),e===w.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(A.FAILED)),this._close(new N(A.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return s(this,null,function*(){if(e.endsWith(Ae.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(Ae.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))o.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{o.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(o.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],q.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(v.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===$.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;v.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),d.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(o.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case $.audio:this._removeAudioTrack(e,t,i);break;case $.video:case $.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Ae.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;!P.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!==J.CLOSE||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),v.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return s(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==W.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,c)=>(c.status!==t&&(c.status=t,d.batchParticipantsOnStart?n.push(c.externalId):v.onParticipantStatus(c.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&v.onRemoteStatus(r,t,i)}},x=B;x._delayedHangup=!1;var $t=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,$t.prototype),this.participantErrors=t}};function Ur(){if(!d.apiAppId||!d.apiKey)throw new N(ae.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function qi(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Br(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${d.apiEnv.api}fb.do`,r)}function Vr(i){return s(this,arguments,function*(a,e={},t=!1){let r=Br(a,e,t);return Oa(r)})}function Oa(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 Br(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 Qe;(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"})(Qe||(Qe={}));var nt;(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"})(nt||(nt={}));var Da=10,Ma=700,wa=3e3,qt=class extends dt{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 Vr(e,t,i)}catch(l){if(!l.hasOwnProperty("error_msg")&&(c++,o.debug(`${e} network error, attempt ${c}...`),c<Da))return yield I.delay(Math.min(c*Ma,wa)),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=ae.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:c=A.SERVICE_DISABLED;break;case 1102:c=A.CALLEE_IS_OFFLINE;break;case 1103:c=A.NOT_FRIENDS;break;case 1104:case 1106:c=A.EXTERNAL_API_ERROR;break}throw new N(c,{message:n.error_msg,code:n.error_code})}})}userId(e){return s(this,null,function*(){let t=I.decomposeId(e).id;return te.isEmpty()?ie.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),ie.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return s(this,null,function*(){te.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return s(this,null,function*(){if(!this._uuid){let t=He.get("uuid");t||(t=I.uuid(),He.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:d.appVersion,client_type:"SDK_JS"}};return d.authToken&&(e.session_data.auth_token=d.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),te.sessionKey=t.session_key,te.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&v.onTokenExpired(),new N(ae.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})};qi("log.externalLog",t)}init(){Ur()}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 Le.USER:p.uids=t.join(",");break;case Le.GROUP:p.gid=t[0];break;case Le.CHAT:p.chatId=t[0];break}return c&&(p.createJoinLink=!0),n&&(p.payload=n),d.domain&&(p.domainId=d.domain),l&&(p.requireAuthToJoin=!0),this._startConversation(p)})}_startConversation(e){return s(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return s(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return s(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return s(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1){return s(this,null,function*(){let i={joinLink:e,isVideo:t};return d.anonymToken&&(i.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return s(this,null,function*(){let t=ie.fromIds(e),i=[],r={methods:[]},n=[],c=Object.keys(this._externalUidsCache),l=Object.values(this._externalUidsCache);for(let f of t){let b=ie.toString(f),M=l.indexOf(b);M>-1?i.push(Number(c[M])):(n.push(b),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:f.id,anonym:f.type===Oe.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((f,b)=>{if(f.ok){let M=Number(f.ok.ok_id);this._externalUidsCache[M]=n[b],i.push(M)}}),i})}getExternalIdsByOkIds(e){return s(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(ie.fromString(this._externalUidsCache[n])):i.push(n);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let n of i)r.hasOwnProperty(n)&&t.push(ie.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=ie.toString(e),n=i.indexOf(r);return n>-1?I.composeId(t[n],ee.USER):null}cacheExternalId(e,t){let i=I.decomposeId(e).id;this._externalUidsCache[i]=ie.toString(t)}getConversationParams(e){return s(this,null,function*(){let t={};return d.anonymToken&&(t.anonymToken=d.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:A.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),qi("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,Oe.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=ie.fromIdToString(n,Oe.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 Ji;(function(_){_.RECOVER="recover",_.ACCEPT_CALL="accept-call",_.ADD_PARTICIPANT="add-participant",_.REMOVE_PARTICIPANT="remove-participant",_.HANGUP="hangup",_.TRANSMIT_DATA="transmit-data",_.ACCEPT_PRODUCER="accept-producer",_.ALLOCATE_CONSUMER="allocate-consumer",_.CHANGE_MEDIA_SETTINGS="change-media-settings",_.CHANGE_PARTICIPANT_STATE="change-participant-state",_.CHANGE_STREAM_PRIORITIES="change-streams-priorities",_.UPDATE_DISPLAY_LAYOUT="update-display-layout",_.REPORT_PERF_STAT="report-perf-stat",_.RECORD_START="record-start",_.RECORD_STOP="record-stop",_.RECORD_SET_ROLE="record-set-role",_.RECORD_GET_STATUS="record-get-status",_.SWITCH_MICRO="switch-micro",_.SWITCH_TOPOLOGY="switch-topology",_.REQUEST_REALLOC="request-realloc",_.CHAT_MESSAGE="chat-message",_.CHAT_HISTORY="chat-history",_.CUSTOM_DATA="custom-data",_.GRANT_ROLES="grant-roles",_.MUTE_PARTICIPANT="mute-participant",_.PIN_PARTICIPANT="pin-participant",_.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",_.CHANGE_OPTIONS="change-options",_.GET_WAITING_HALL="get-waiting-hall",_.PROMOTE_PARTICIPANT="promote-participant",_.REQUEST_TEST_MODE="request-test-mode",_.ADD_MOVIE="add-movie",_.UPDATE_MOVIE="update-movie",_.REMOVE_MOVIE="remove-movie"})(Ji||(Ji={}));var G=Ji;var Fr="open",Gr=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0],ka=10,ye=class extends pt{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="+ye._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<Gr.length;t++)Gr[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return s(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){u.log(g.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return s(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=I.decomposeId(t.participantId);t=Object.assign({},t,{participantId:n.id,participantType:n.type})}return this._sendRaw(e,t,i)})}_sendRaw(r){return s(this,arguments,function*(e,t={},i=0){let n=c=>{var p;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(c),((p=this.producerCommandDataChannel)==null?void 0:p.readyState)===Fr&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){u.log(g.SOCKET_ACTION,"not_opened"),o.warn("Socket not opened"),c.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(u.log(g.SOCKET_ACTION,"invalid_state"),o.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(c),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((c,l)=>{let p=(b,M=!1)=>{!i||M?l(b):(o.debug("Resending a signaling message",e,f.sequence),i--,n(f))},f={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:c,reject:p};n(f)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return s(this,null,function*(){return this._send(G.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return s(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return s(this,null,function*(){return this._send(G.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return s(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return s(this,null,function*(){return this._send(G.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return s(this,null,function*(){return this._send(G.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},ka)})}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,er({participantId:e},t))})}removeParticipant(e,t=!1){return s(this,null,function*(){return this._send(G.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return s(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(G.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return s(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(G.ACCEPT_PRODUCER,i)})}changePriorities(e){return s(this,null,function*(){return this._send(G.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return s(this,null,function*(){return this._send(G.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return s(this,null,function*(){return this._send(G.ADD_MOVIE,e)})}updateMovie(e){return s(this,null,function*(){return this._send(G.UPDATE_MOVIE,e)})}removeMovie(e){return s(this,null,function*(){return this._send(G.REMOVE_MOVIE,e)})}startStream(e){return s(this,null,function*(){return this._send(G.RECORD_START,e)})}stopStream(){return s(this,null,function*(){return this._send(G.RECORD_STOP)})}recordSetRole(e,t){return s(this,null,function*(){return this._send(G.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return s(this,null,function*(){return this._send(G.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return s(this,null,function*(){return this._send(G.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return s(this,null,function*(){return this._send(G.REQUEST_REALLOC)})}reportPerfStat(e){return s(this,null,function*(){return this._send(G.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return s(this,null,function*(){return this._send(G.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return s(this,null,function*(){return this._send(G.CHAT_HISTORY,{count:e})})}customData(e,t){return s(this,null,function*(){return this._send(G.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return s(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(G.GRANT_ROLES,r)})}muteParticipant(e,t,i){return s(this,null,function*(){return this._sendRaw(G.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return s(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(G.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return s(this,null,function*(){return this._send(G.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return s(this,null,function*(){return this._send(G.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return s(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(G.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return s(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(G.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ue.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),o.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){o.debug("Socket opened"),u.log(g.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){u.log(g.SOCKET_ACTION,"parse_error"),o.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(o.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(Se.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Se.NOTIFICATION,{type:"notification",notification:k.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(Se.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(u.log(g.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(u.log(g.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new N(A.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(Se.NOTIFICATION,{notification:k.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(ae.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(u.log(g.SOCKET_ACTION,"unknown_message"),o.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(Se.FAILED,e)}_onError(e){u.log(g.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){u.log(g.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<ye.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(ye.RECONNECT_MAX_DELAY,ye.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),u.log(g.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ue.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],u.log(g.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),ye.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)!==Fr){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}ye._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),ye.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),ye.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(ae.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},ye.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(Ue.RETRY)},ye.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Ne=ye;Ne.RECONNECT_DELAY=d.signalingReconnectDelay,Ne.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,Ne.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,Ne.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,Ne.WAIT_RESPONSE_DELAY=d.waitResponseDelay,Ne.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var Yi;(function(t){t.KING="KING",t.PAWN="PAWN"})(Yi||(Yi={}));var Na=Yi;var st,se,At=null,Fp={getCameras:P.getCameras,getMicrophones:P.getMicrophones,getOutput:P.getOutput,hasCamera:P.hasCamera,hasMicrophone:P.hasMicrophone,getSavedCamera:P.getSavedCamera,getSavedMicrophone:P.getSavedMicrophone,getSavedOutput:P.getSavedOutput,hasCameraPermission:P.hasCameraPermission,hasMicrophonePermission:P.hasMicrophonePermission,hasPermissions:P.hasPermissions,getUserMedia:P.getUserMedia,getUserVideo:P.getUserVideo,getUserAudio:P.getUserAudio,saveDeviceId:P.saveDeviceId,isBrowserSupported:P.isBrowserSupported,isScreenCapturingSupported:P.isScreenCapturingSupported,os:P.os,isMobile:P.isMobile,browserName:P.browserName,browserVersion:P.browserVersion,baseChromeVersion:P.baseChromeVersion,getAudioContext:P.getAudioContext};function xa(a){se=a}function La(a){st=a}function Gp(a){At=a}function Hp(a){d.videoEffects=a}function Wp(a){return s(this,null,function*(){if(d.set(a),P.browserName()==="Sferum"&&(d.platform=`SFERUM:${P.browserVersion()}`),se||xa(new qt),st||La(()=>new Ne),d.debug&&(Hr.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${d.sdkVersion}`,a),yield P.init(),!P.isBrowserSupported())throw new N(ae.UNSUPPORTED);se.init()})}function jp(n){return s(this,arguments,function*(a,e=[ue.AUDIO],t="",i=!1,r=!1){let c=[],l=[];if(Array.isArray(a)?c=a.length?a:[]:a&&(c=[a]),c.length&&(l=yield se.getOkIdsByExternalIds(c),!l.length))throw new N(A.CALLEE_IS_OFFLINE);return Ua(l,Le.USER,e,t,i,r)})}function Ua(c){return s(this,arguments,function*(a,e=Le.USER,t,i="",r=!1,n=!1){if(x.current())throw o.error("There is already active call"),new N(A.FAILED);return new x(se,st(),At).onStart(a,e,t,i,r,n)})}function Kp(a){return s(this,null,function*(){return Va(a)})}function Va(i){return s(this,arguments,function*(a,e=ee.USER,t){if(a===x.id())throw new Error("Push has already been processed");return new x(se,st(),At).onPush(a,e,t)})}function $p(a,e){return s(this,null,function*(){return se.getTokenForAnonym(a,e)})}function qp(t){return s(this,arguments,function*(a,e={}){return se.call(a,e)})}function Jp(a){return s(this,null,function*(){return a&&(d.authToken=a),se.authorize()})}function Yp(){return s(this,arguments,function*(a=[ue.AUDIO]){let e=x.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function Qp(){return s(this,null,function*(){let a=x.current();if(a)return a.decline()})}function zp(t){return s(this,arguments,function*(a,e=[ue.AUDIO]){return Ba(a,e)})}function Ba(a,e,t){return s(this,null,function*(){if(x.current())throw o.error("There is already active call"),new N(A.FAILED);return new x(se,st(),At).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function Xp(i){return s(this,arguments,function*(a,e=[ue.AUDIO],t){if(x.current())throw o.error("There is already active call"),new N(A.FAILED);return t&&(d.anonymToken=t),new x(se,st(),At).onJoin({joinLink:a,mediaOptions:e})})}function Zp(){return s(this,null,function*(){let a=x.current();if(a)return a.hangup();x.hangupAfterInit()})}function eu(a,e){return s(this,null,function*(){let t=yield se.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return Fa(t[0],e)})}function Fa(a,e){return s(this,null,function*(){let t=x.current();t&&(yield t.addParticipant(I.composeId(a,ee.USER),e))})}function tu(a,e=!1){return s(this,null,function*(){let t=yield se.getOkIdsByExternalIds([a]);return Ga(t[0],e)})}function Ga(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.removeParticipant(I.composeId(a,ee.USER),e))})}function iu(a,e){return s(this,null,function*(){let t=yield P.saveDeviceId(a,e),i=x.current();return t&&i?i.changeDevice(a):Promise.reject()})}function ru(a){return s(this,null,function*(){let e=x.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function au(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.setVideoStream(a,e))})}function nu(a){return s(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalVideo(a))})}function su(a){return s(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalAudio(a))})}function ou(a,e){return s(this,null,function*(){let t=x.current();if(t)return t.setLocalResolution(a,e)})}function cu(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changePriorities(a))})}function du(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changeParticipantState(a))})}function lu(a){return s(this,null,function*(){let e=x.current();e&&(yield e.updateDisplayLayout(a))})}function pu(a,e,t=!1){return s(this,null,function*(){let i=yield se.getOkIdsByExternalIds([a]);return Ha(i[0],e,t)})}function Ha(a,e,t=!1){return s(this,null,function*(){let i=x.current();i&&(yield i.grantRoles(I.composeId(a,ee.USER),e,t))})}function uu(){return s(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield se.getOkIdsByExternalIds([a]))[0]),Wa(i,e,t)})}function Wa(){return s(this,arguments,function*(a=null,e,t=[]){let i=x.current();if(i){let r=a?I.composeId(a,ee.USER):null;yield i.muteParticipant(r,e,t)}})}function mu(a,e=!1){return s(this,null,function*(){let t=yield se.getOkIdsByExternalIds([a]);return ja(t[0],e)})}function ja(a,e=!1){return s(this,null,function*(){let t=x.current();t&&(yield t.pinParticipant(I.composeId(a,ee.USER),e))})}function hu(a){return s(this,null,function*(){let e=x.current();e&&(yield e.updateMediaModifiers(a))})}function _u(a){return s(this,null,function*(){let e=x.current();e&&(yield e.changeOptions(a))})}function gu(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield se.getOkIdsByExternalIds([e]))[0]),Ka(a,t)})}function Ka(a,e=null){return s(this,null,function*(){let t=x.current();if(t){let i=e?I.composeId(e,ee.USER):null;yield t.chatMessage(a,i)}})}function fu(a=10){return s(this,null,function*(){let e=x.current();if(e)return e.chatHistory(a)})}function Su(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield se.getOkIdsByExternalIds([e]))[0]),$a(a,t)})}function $a(a,e=null){return s(this,null,function*(){let t=x.current();if(t){let i=e?I.composeId(e,ee.USER):null;yield t.customData(a,i)}})}function vu(a="",e=!1){return s(this,null,function*(){return(yield se.createConversation(I.uuid(),a,e)).join_link})}function Eu(){return s(this,null,function*(){let a=x.current();return a?a.createJoinLink():Promise.reject()})}function Iu(){return s(this,null,function*(){let a=x.current();return a?a.removeJoinLink():Promise.reject()})}function Cu(a,e){return s(this,null,function*(){return se.getAnonymTokenByLink(a,e)})}function Tu(a){let e=x.current();e&&e.setVolume(a)}function Ru(a){d.forceRelayPolicy=a}function yu(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 Pu(){return s(this,null,function*(){let a=x.current();return a?a.stopStream():Promise.reject()})}function bu(a,e){return s(this,null,function*(){let t=x.current();if(t){let i=yield se.getOkIdsByExternalIds([a]);return t.recordSetRole(I.composeId(i[0],ee.USER),e)}return Promise.reject()})}function Au(){return s(this,null,function*(){let a=x.current();return a?a.getStreamInfo():Promise.reject()})}function Ou(a){return s(this,null,function*(){let e=x.current();return e?e.addMovie(a):Promise.reject()})}function Du(a,e){return s(this,null,function*(){let t=x.current();return t?t.updateMovie(a,e):Promise.reject()})}function Mu(a){return s(this,null,function*(){let e=x.current();return e?e.removeMovie(a):Promise.reject()})}function wu(a){d.statisticsInterval=a;let e=x.current();if(e)return e.updateStatisticsInterval()}function ku(a){Hr.disableLog(!a),o.toggle(a)}function Nu(a,...e){!d.debugLog||o.send(a,"[external]",...e)}function xu(a){return s(this,null,function*(){let e=x.current();if(e)return e.videoEffect(a)})}function Lu(a){return s(this,null,function*(){let e=x.current();e&&(yield e.setAudioStream(a))})}function Uu(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 Vu(a,e=!1){return s(this,null,function*(){let t=x.current();if(!t)throw new Error("Conversation not found");let i=yield se.getOkIdsByExternalIds([a]);return t.promoteParticipant(I.composeId(i[0],ee.USER),e)})}function Bu(a){return s(this,null,function*(){yield se.removeHistoryRecords(a)})}export{qt as Api,dt as BaseApi,lt as BaseLogger,pt as BaseSignaling,Fe as CallDirection,Le as CallType,Zt as ChatRoomEventType,ii as ConversationOption,me as DebugMessageType,Oe as ExternalIdType,ki as FacingMode,ae as FatalError,N as HangupReason,A as HangupType,ue as MediaOption,$ as MediaTrackKind,Ie as MediaType,Ge as MuteState,H as ParticipantState,q as ParticipantStatus,Na as RecordRole,Ne as Signaling,G as SignalingCommandType,Ue as SignalingConnectionType,k as SignalingNotification,ze as UserRole,ee as UserType,I as Utils,Yp as acceptCall,Ou as addMovie,eu as addParticipant,Fa as addParticipantInternal,qp as apiCall,Jp as authorize,Fp as browser,Ua as callInternal,jp as callTo,ru as captureScreen,_u as changeConversationOptions,iu as changeDevice,du as changeParticipantState,cu as changePriorities,xu as changeVideoEffect,fu as chatHistory,gu as chatMessage,Ka as chatMessageInternal,Eu as createJoinLink,Su as customData,$a as customDataInternal,ku as debug,Nu as debugMessage,Qp as declineCall,Ru as forceRelayPolicy,Cu as getAnonymTokenByLink,Au as getStreamInfo,$p as getTokenForAnonym,Uu as getWaitingHall,pu as grantRoles,Ha as grantRolesInternal,Zp as hangup,Wp as init,zp as joinCall,Xp as joinCallByLink,Ba as joinCallInternal,uu as muteParticipant,Wa as muteParticipantInternal,mu as pinParticipant,ja as pinParticipantInternal,Kp as processPush,Va as processPushInternal,Vu as promoteParticipant,bu as recordSetRole,Bu as removeHistoryRecords,Iu as removeJoinLink,Mu as removeMovie,tu as removeParticipant,Ga as removeParticipantInternal,xa as setApi,Lu as setAudioStream,ou as setLocalResolution,Gp as setLogger,hu as setMediaModifiers,La as setSignalingFactory,wu as setStatisticsInterval,Hp as setVideoEffects,au as setVideoStream,Tu as setVolume,vu as startConversation,yu as startStream,Pu as stopStream,su as toggleLocalAudio,nu as toggleLocalVideo,lu as updateDisplayLayout,Du as updateMovie};
|
|
7
|
+
var da=Object.defineProperty;var pr=Object.getOwnPropertySymbols;var pa=Object.prototype.hasOwnProperty,la=Object.prototype.propertyIsEnumerable;var lr=Math.pow,ur=(a,e,t)=>e in a?da(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,hr=(a,e)=>{for(var t in e||(e={}))pa.call(e,t)&&ur(a,t,e[t]);if(pr)for(var t of pr(e))la.call(e,t)&&ur(a,t,e[t]);return a};var o=(a,e,t)=>new Promise((i,r)=>{var n=l=>{try{d(t.next(l))}catch(_){r(_)}},s=l=>{try{d(t.throw(l))}catch(_){r(_)}},d=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,s);d((t=t.apply(a,e)).next())});import oa from"webrtc-adapter";var gt=class{createJoinLink(e){return o(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return o(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return o(this,null,function*(){return""})}log(e){}prepareUserIds(e){return o(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return o(this,null,function*(){})}cleanup(){}getTokenForAnonym(e,t){return o(this,null,function*(){return""})}call(i){return o(this,arguments,function*(e,t={}){return null})}};var ft=class{log(e,t,i=!1){}destroy(){}};var Z=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var St=class extends Z{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var ni;(function(i){i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING"})(ni||(ni={}));var Ge=ni;var si;(function(i){i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT"})(si||(si={}));var Ue=si;var oi;(function(t){t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP"})(oi||(oi={}));var ci=oi;var di;(function(t){t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD"})(di||(di={}));var mr=di;var pi;(function(i){i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL"})(pi||(pi={}));var li=pi;function _r(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function gr(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 ui;(function(y){y.CAMERA_PERMISSION="camera",y.MIC_PERMISSION="mic",y.CAMERA_ACCESS="cameralock",y.MIC_ACCESS="miclock",y.MIC_NOT_FOUND="nomic",y.SCREEN_PERMISSION="screenpermission",y.SCREEN_ACCESS="screenlock",y.CONNECTION="connection",y.NETWORK="network",y.UNKNOWN="unknown",y.UNSUPPORTED="unsupported",y.SIGNALING_FAILED="signalingfailed",y.API="api",y.AUTH="auth"})(ui||(ui={}));var re=ui;var hi;(function(O){O.CANCELED="CANCELED",O.REJECTED="REJECTED",O.REMOVED="REMOVED",O.HUNGUP="HUNGUP",O.MISSED="MISSED",O.BUSY="BUSY",O.FAILED="FAILED",O.NETWORK_ERROR="NETWORK_ERROR",O.KILLED="KILLED",O.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",O.NOT_FRIENDS="NOT_FRIENDS",O.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",O.UNKNOWN_ERROR="UNKNOWN_ERROR",O.UNSUPPORTED="UNSUPPORTED",O.OLD_VERSION="OLD_VERSION",O.SERVICE_DISABLED="SERVICE_DISABLED",O.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",O.SOCKET_CLOSED="SOCKET_CLOSED",O.ENDED="ENDED"})(hi||(hi={}));var A=hi;var mi;(function(i){i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING"})(mi||(mi={}));var ce=mi;var _i;(function(i){i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT"})(_i||(_i={}));var He=_i;var gi;(function(r){r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP"})(gi||(gi={}));var H=gi;var fi;(function(r){r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry"})(fi||(fi={}));var Be=fi;var Si;(function(i){i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT"})(Si||(Si={}));var ge=Si;var vi;(function(v){v.TRANSMITTED_DATA="transmitted-data",v.ACCEPTED_CALL="accepted-call",v.HUNGUP="hungup",v.PARTICIPANT_ADDED="participant-added",v.PARTICIPANT_JOINED="participant-joined",v.CLOSED_CONVERSATION="closed-conversation",v.MEDIA_SETTINGS_CHANGED="media-settings-changed",v.PARTICIPANT_STATE_CHANGED="participant-state-changed",v.RATE_CALL_DATA="rate-call-data",v.FEATURE_SET_CHANGED="feature-set-changed",v.TOPOLOGY_CHANGED="topology-changed",v.PRODUCER_UPDATED="producer-updated",v.CONSUMER_ANSWERED="consumer-answered",v.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",v.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",v.SETTINGS_UPDATE="settings-update",v.VIDEO_QUALITY_UPDATE="video-quality-update",v.REGISTERED_PEER="registered-peer",v.SWITCH_MICRO="switch-micro",v.RECORD_STARTED="record-started",v.RECORD_STOPPED="record-stopped",v.REALLOC_CON="realloc-con",v.AUDIO_ACTIVITY="audio-activity",v.SPEAKER_CHANGED="speaker-changed",v.STALLED_ACTIVITY="stalled-activity",v.CHAT_MESSAGE="chat-message",v.CUSTOM_DATA="custom-data",v.ROLES_CHANGED="roles-changed",v.MUTE_PARTICIPANT="mute-participant",v.PIN_PARTICIPANT="pin-participant",v.OPTIONS_CHANGED="options-changed",v.NETWORK_STATUS="network-status",v.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",v.PROMOTE_PARTICIPANT="promote-participant",v.CHAT_ROOM_UPDATED="chat-room-updated",v.PROMOTION_APPROVED="promotion-approved",v.JOIN_LINK_CHANGED="join-link-changed"})(vi||(vi={}));var x=vi;var Ei;(function(u){u.ERROR="callError",u.DEVICES="callDevices",u.CALL_SPEC_ERROR="callSpecError",u.ICE_CONNECTION_STATE="callIceConnectionState",u.ICE_CONNECTION_TYPE="callIceConnectionType",u.ICE_RESTART="callIceRestart",u.PUSH="callPush",u.OUTGOING_CALL="callStart",u.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",u.JOIN_CONVERSATION="callJoinConversation",u.ACCEPTED_OUTGOING="callAcceptedOutgoing",u.ACCEPT_INCOMING="callAcceptIncoming",u.DECLINE_INCOMING="callDeclineIncoming",u.ACCEPT_CONCURRENT="callAcceptConcurrent",u.HANGUP="callHangup",u.MEDIA_STATUS="callMediaStatus",u.DEVICE_CHANGED="callDeviceChanged",u.SOCKET_ACTION="callSocketAction",u.ADD_PARTICIPANT="callAddParticipant",u.REMOVE_PARTICIPANT="callRemoveParticipant",u.POOR_CONNECTION="callPoorConnection",u.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",u.RELAY_POLICY="callForceRelay",u.PAT_ALLOCATED="patAllocate",u.PAT_DEALLOCATED="patDeallocate",u.PAT_ERROR="patError",u.PAT_WAITING_TIME_ERROR="patWaitingTimeError",u.PAT_OUTDATED_RESPONSE="patOutdatedResponse"})(Ei||(Ei={}));var f=Ei;var Ii;(function(t){t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat"})(Ii||(Ii={}));var Me=Ii;var vt;(function(t){t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error"})(vt||(vt={}));var fr=vt;function Sr(a){switch(a){case 1:return vt.NO_AVAILABLE_TRACKS;default:return vt.UNKNOWN_ERROR}}var Ti;(function(t){t.CREATOR="CREATOR",t.ADMIN="ADMIN"})(Ti||(Ti={}));var et=Ti;function Et(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var Ci;(function(t){t.USER="USER",t.GROUP="GROUP"})(Ci||(Ci={}));var ee=Ci;var Ri=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 vr=2*1024*1024,ua=512*1024,It=100*1024,ha=5,Pi="_okcls_logs_session_",ma=3e4,Er=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=vr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(Pi)!==0)continue;let i=e.getItem(t);if(!i){Cr(t);continue}let r=Tr(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(It)}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(Pi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Cr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>vr||this.length>ha-1||this.size+e>this.available);)this.deleteOldestItem()}};function Ir(){return`${Pi}${Date.now()}`}function Tr(a){return new Blob([a]).size}function Cr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function yi(){let a=$e.toString();if(!ve.available||!a)return;let e=Tr(a);ve.cleanup(e);try{window.localStorage.setItem(Nt,a)}catch(t){if(console.warn("Failed to write log to storage",t),ve.storageSize=ve.size+e,ve.cleanup(It+e),ve.available>=It+e){yi();return}if(e>It){$e.bisect(),yi();return}ve.storageSize=0;return}e>ua&&(ve.add(Nt,e),Nt=Ir(),$e.clear(),ve.cleanup(It))}function bi(){!ve.available||!$e.length||yi()}function _a(a=!1){let e=[];try{let r=window.localStorage;for(let s of ve.items){let d=r.getItem(s.key);e.push(d)}let n=$e.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 ga(t,i),i}function ga(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 Rr(a,e){!ve.available||($e.push({t:Date.now(),l:a,d:e}),Ai||(Ai=window.setTimeout(()=>{Ai=null,bi()},ma)))}function Mi(){ve||(ve=new Er,$e=new Ri,Nt=Ir(),window.addEventListener("beforeunload",bi))}var ve,$e,Nt,Ai=null;window.__VKCallsSDKLogs__=(a=!1)=>(ve||Mi(),bi(),_a(a));import yr from"@vkontakte/libvpx";var Pr;(function(t){t.VP9="vp09.00.50.08",t.VP8="vp8"})(Pr||(Pr={}));var ue;(function(s){s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error"})(ue||(ue={}));var h=class extends ft{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){h._instance||(h._instance=new h(e,t))}static log(e,t,i=!1){h._instance&&h._instance.log(e,t,i)}static destroy(){h._instance&&h._instance.destroy(),h._instance=null}};var ke=class{constructor(){this._worker=null}_createWorker(s,d){return o(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((l,_)=>{let M=i.join(","),k=new Blob([e,`exports.default(${M});`],{type:"application/javascript; charset=utf-8"}),q=window.URL.createObjectURL(k);this._worker=new Worker(q),this._worker.onmessage=j=>{switch(j.data.type){case ue.READY:l();break;case ue.ERROR:_(j.data.error);break;case ue.FRAME:t(j.data);break;case ue.DEBUG:c.debug(j.data.message);break;case ue.LOG_ERROR:h.log(f.ERROR,j.data.message);break}},this._sendToWorker(ue.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 tt=class extends ke{init(e){return o(this,null,function*(){c.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var R=Object.defineProperty;var V=o=>R(o,"__esModule",{value:!0});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)c.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)},[yr,yr.getUrl])})}decodeFrame(e,t,i,r){let n="ImageBitmap"in window;this._sendToWorker(ue.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:n,debug:c.enabled()},[t.buffer])}destroy(){this._removeWorker(),c.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var qe=class extends ke{init(e){return o(this,null,function*(){c.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var l=Object.defineProperty;var f=t=>l(t,"__esModule",{value:!0});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?c.warn("WebCodecsDecoder",t.error):e(t.data)})})}decodeFrame(e,t,i,r=!1){this._sendToWorker(ue.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),c.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window&&"ImageBitmap"in window&&"createImageBitmap"in window}};var Di="_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 fa(a){let e=it?it.getItem(Di+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function Sa(a,e){try{it&&it.setItem(Di+a,JSON.stringify(e))}catch(t){}}function va(a){it&&it.removeItem(Di+a)}var Oi;(function(i){function a(r){return fa(r)||null}i.get=a;function e(r,n){Sa(r,n)}i.set=e;function t(r){va(r)}i.remove=t})(Oi||(Oi={}));var We=Oi;import Tt from"big-integer";function br(a,e){if(a.isAudioEnabled!==e.isAudioEnabled||a.isVideoEnabled!==e.isVideoEnabled||a.isScreenSharingEnabled!==e.isScreenSharingEnabled||a.videoStreams.length!==e.videoStreams.length)return!1;for(let t of a.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function fe(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}var Mr=a=>a.stop(),Ar=a=>a.getTracks().forEach(Mr),ki=a=>a.getVideoTracks().forEach(Mr),Dr=a=>a.getVideoTracks()[0].clone();var N=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(A).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 ae;(function(i){i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS"})(ae||(ae={}));var $;(function(i){i.audio="audio",i.video="video",i.screen="screen"})($||($={}));var wi=class extends Z{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=fe();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return o(this,arguments,function*(e=[ce.AUDIO]){if(this._stream)return;let t=e.includes(ce.VIDEO),i=e.includes(ce.AUDIO);if(!b.isBrowserSupported())throw new N(re.UNSUPPORTED);try{this._stream=yield b.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 o(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return o(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=I.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);navigator.mediaDevices.addEventListener("devicechange",()=>o(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),s=n&&n.groupId,d=this._stream.getVideoTracks()[0],l=d&&d.enabled&&d.getSettings(),_=l&&l.groupId;if(!s&&!_)return;let M=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!M.find(k=>k.groupId===s)),!t&&_&&(t=!M.find(k=>k.groupId===_)),i()}))}_changeVideoInput(e=null){return o(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield b.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{p.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),n=yield this._videoEffect(this._effect,r);this._stopLocalTrack($.video),h.log(f.DEVICE_CHANGED,t),c.log("Video stream changed"),yield this._replaceLocalTrack(n),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent(ae.SOURCE_CHANGED,{kind:$.video,mediaSettings:this._mediaSettings})}}catch(t){throw h.log(f.ERROR,"change_video"),c.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=Dr(e)),t=this._trackVideoStreamBackup.clone(),ki(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),ki(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return o(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return o(this,null,function*(){try{if(e=e||(yield b.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack($.audio),h.log(f.DEVICE_CHANGED,"audio"),c.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent(ae.SOURCE_CHANGED,{kind:$.audio,mediaSettings:this._mediaSettings})}}catch(t){throw h.log(f.ERROR,"change_audio"),c.error("Microphone change failed",t),t}})}_changeScreen(e){return o(this,null,function*(){try{if(e=e||(yield b.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=p.consumerScreenTrack?t:yield this._videoEffect(null,t);h.log(f.DEVICE_CHANGED,"screen"),c.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,p.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack($.video),this._sendVideoTrack=p.consumerScreenDataChannel?b.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent(ae.SCREEN_STATUS,{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent(ae.SOURCE_CHANGED,{kind:$.screen,mediaSettings:this._mediaSettings})}}catch(t){throw h.log(f.ERROR,"screen"),c.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(ae.SCREEN_STATUS,{mediaSettings:this._mediaSettings}),this._triggerEvent(ae.SOURCE_CHANGED,{kind:$.screen,mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return o(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(ae.TRACK_REPLACED,e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return o(this,null,function*(){if(!p.videoEffects)return t;try{return h.log(f.DEVICE_CHANGED,`effect_${e}`),p.videoEffects.setEffect(e,t)}catch(i){return c.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){p.videoEffects&&(this._effect=null,p.videoEffects.destroy()),this._stream&&(Ar(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return o(this,null,function*(){return e?this._changeScreen():p.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return o(this,null,function*(){if(!this._stream)return;p.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield b.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=b.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack($.video),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent(ae.SOURCE_CHANGED,{kind:$.video,mediaSettings:this._mediaSettings})})}toggleAudio(e){return o(this,null,function*(){if(!this._stream)return;let t;e?t=(yield b.getUserAudio()).getAudioTracks()[0]:t=b.getSilentMediaTrack(),this._stopLocalTrack($.audio),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent(ae.SOURCE_CHANGED,{kind:$.audio,mediaSettings:this._mediaSettings})})}setResolution(e,t){return o(this,null,function*(){if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return o(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:p.noiseSuppression})})}videoEffect(e){return o(this,null,function*(){if(!p.videoEffects)throw new Error("Video Effects library is not set");if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var rt=":",Lt="d",xi;(function(ii){function a(u,R,D,V,S=!1){let z=/[\r\n]+/,m=`\r
|
|
8
|
+
`;if(!R&&!D&&!V)return S?K(u.split(z)).join(m):u;function K(Q){let Oe=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],le="a=rtcp-fb:111",g=Q.findIndex(P=>P.startsWith(le));return~g&&(Q[g]=Q[g]+m+Oe.join(m)),Q}function se(Q,Oe,le){let g=Q.split(" "),P=g.slice(0,3),F;for(F=3;F<g.length;F++)le.includes(g[F])&&P.push(g[F]);for(F=3;F<g.length;F++)!le.includes(g[F])&&!Oe.includes(g[F])&&P.push(g[F]);return P.join(" ")}function v(Q,Oe){let le=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),g,P=[];for(g=0;g<Q.length;++g){let F=Q[g].match(le);F&&F.length===3&&F[2]===Oe&&P.push(F[1])}return P}function Ee(Q,Oe,le,g){let P,F="m="+Oe;for(P=0;P<Q.length;++P)if(Q[P].startsWith(F)){Q[P]=se(Q[P],le,g);break}}let Fe=[],oe=u.split(z);(D||R)&&(Fe=v(oe,"H264"));let Le=[];if(V&&(Le=v(oe,"VP9")),D){let Q=Fe.slice(0),Oe=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),le;for(le=0;le<oe.length;++le){let P=oe[le].match(Oe);P&&P.length===3&&Q.includes(P[2])&&Q.push(P[1])}let g=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(le=oe.length;le--;){let P=oe[le].match(g);P&&P.length===3&&Q.includes(P[2])&&oe.splice(le,1)}Ee(oe,"video",Q,[])}else R&&Ee(oe,"video",[],Fe);return V&&Ee(oe,"video",[],Le),S&&K(oe),oe.join(m)}ii.patchSDP=a;function e(u){return u?`${u.type||"WEB_SOCKET"}_${u.id}`:"_"}ii.getPeerIdString=e;function t(u,R){return u&&u.id===R.id&&(u.type||"WEB_SOCKET")===(R.type||"WEB_SOCKET")}ii.comparePeerId=t;function i(u){return o(this,null,function*(){return!u||!u.getStats?Promise.resolve(null):u.getStats(null).then(R=>{let D=null,V=null;if(R.forEach(S=>{S.type==="transport"&&S.selectedCandidatePairId?V=R.get(S.selectedCandidatePairId):S.type==="candidate-pair"&&S.state==="succeeded"&&!V&&(!S.hasOwnProperty("selected")||S.selected)&&(V=S)}),V&&V.localCandidateId){let S=R.get(V.localCandidateId);S&&(D={type:S.candidateType,ip:S.ip||S.ipAddress,port:S.port||S.portNumber})}return D}).catch(()=>null)})}ii.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function s(u,R){let D=String(u);return n.test(D)?(c.warn(`Already composite id [${u}] type supplied [${R}]`),D):R===ee.GROUP?"g"+D:R===ee.USER?"u"+D:(c.warn(`Unknown type [${R}] for id [${u}]`),D.match(r)?"u"+D:D)}ii.composeUserId=s;function d(u,R,D){let V=s(u,R);return l(V,D)}ii.composeParticipantId=d;function l(u,R){return R?u+rt+Lt+R:u}ii.compose=l;function _(u){return d(u.id,u.idType||ee.USER,u.deviceIdx||0)}ii.composeId=_;function M(u){return u.participant?_(u.participant):d(u.participantId,u.participantType||ee.USER,u.deviceIdx||0)}ii.composeMessageId=M;function k(u){let R=String(u),D=R.match(n);return D?{id:Number(D[2]),type:D[1]==="g"?ee.GROUP:ee.USER}:(c.warn(`Unsupported compositeId [${u}]`),{id:Number(R),type:ee.USER})}ii.decomposeId=k;function q(u){let R=u.split(rt+Lt);return{compositeUserId:R[0],deviceIdx:R.length>1?parseInt(R[1],10):0}}ii.decomposeParticipantId=q;function j(){let u="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),R=new Array(36),D=0,V,S;for(S=0;S<36;S++)S===8||S===13||S===18||S===23?R[S]="-":S===14?R[S]="4":(D<=2&&(D=33554432+Math.random()*16777216|0),V=D&15,D=D>>4,R[S]=u[S===19?V&3|8:V]);return R.join("")}ii.uuid=j;function y(u,R){let D;function V(){let S=this,z=arguments;D&&window.clearTimeout(D),D=window.setTimeout(()=>{u.apply(S,z)},R)}return V}ii.throttle=y;function _e(u){let R="",D=u.split(`
|
|
9
|
+
`);for(let m of D)if(m.startsWith("a=fingerprint")){let K=m.split(" ");if(K.length===2){R=K[1];break}}if(!R)return Tt.minusOne;let V=R.split(":"),S=Tt.zero;for(let m=Math.min(7,V.length-1);m>=0;m--){let K=Tt(V[m],16);S=S.shiftLeft(8).or(K)}return((m,K)=>{let se=K.value;if(typeof se=="bigint")return Tt(BigInt.asIntN(m,se));let v=Tt.one.shiftLeft(m),Ee=K.and(v.subtract(1));return Ee.greaterOrEquals(v.subtract(Ee))?Ee.subtract(v):Ee})(64,S)}ii.sdpFingerprint=_e;function De(u){return o(this,null,function*(){return new Promise(R=>window.setTimeout(R,u))})}ii.delay=De;function pe(u,R,D){let V=[];return u.getSenders().forEach(S=>Ke(R,S,S.track,D,V)),V}ii.applySettings=pe;function Ke(u,R,D,V,S){if(u&&D&&D.kind===$.video){let z=D.getSettings();if(z){let m=u.maxBitrateK?u.maxBitrateK*1024:null,K=z.width,se=z.height,v=K&&se&&u.maxDimension?Math.max(1,Math.max(K,se)/u.maxDimension):null,Ee=u.maxFramerate?u.maxFramerate:null,Fe=u.degradationPreference?u.degradationPreference:"balanced",oe=V[D.id];if(oe&&oe.bitrate===m&&oe.scaleResolutionDownBy===v&&oe.maxFramerate===Ee&&oe.degradationPreference===Fe){S[D.id]=oe;return}S[D.id]={bitrate:m,scaleResolutionDownBy:v,maxFramerate:Ee,degradationPreference:Fe};let Le=R.getParameters();Le.encodings||(Le.encodings=[{}]),Le.encodings.forEach(Q=>{m?Q.maxBitrate=m:delete Q.maxBitrate,v?Q.scaleResolutionDownBy=v:delete Q.scaleResolutionDownBy,Ee?Q.maxFramerate=Ee:delete Q.maxFramerate}),Le.degradationPreference=Fe,R.setParameters(Le)}}}ii.applyVideoTrackSettings=Ke;function O(u,R){Array.isArray(R)||(R=[R]);for(let D of R)if(u.includes(D))return!0;return!1}ii.includesOneOf=O;function ye(u){var R;return Object.entries(((R=u.participantState)==null?void 0:R.state)||{}).reduce((D,[V,S])=>(u.participantState&&(D[V]={ts:u.participantState.stateUpdateTs[V],state:S}),D),{})}ii.mapParticipantState=ye;function be(u){return Object.entries(u).reduce((R,[D,{state:V}])=>(R[D]=V,R),{})}ii.mapLegacyParticipantState=be;function mt(u){return u.map(R=>{let D={uid:R.externalId,mediaSettings:R.mediaSettings,status:R.status,muteStates:R.muteStates,unmuteOptions:R.unmuteOptions};return p.participantStateMapped&&(D.participantState=R.participantState),D})}ii.mapSharedParticipants=mt;function sr(u,R){let D=Object.keys(u),V=Object.keys(R);if(D.length!==V.length)return!1;for(let S of D)if(!V.hasOwnProperty(S)||u[S].state!==R[S].state||u[S].ts!==R[S].ts)return!1;return!0}ii.isEqualParticipantState=sr;function or(u,R){let D=Object.keys(u),V=Object.keys(R);if(D.length!==V.length)return!1;for(let S of D)if(!R.hasOwnProperty(S)||u[S]!==R[S])return!1;return!0}ii.isObjectsEquals=or;function cr(u,R){if(u.length!==R.length)return!1;for(let D of u)if(R.indexOf(D)<0)return!1;return!0}ii.isArraysEquals=cr;function dr(u){return!Object.keys(u).length}ii.isEmptyObject=dr})(xi||(xi={}));var I=xi;var Je=null,Ni=null,Ut=[],Bt=[],Li=[],Ct=null,Rt=null,Ui=null,Bi=!1,Vi=!1,Vt,at,Ft,Or=!1,kr=!1,Fi=null,Gi="",Gt=[],Hi=null,wr=navigator.appVersion,Ea=navigator.appName,Te=navigator.userAgent,Wi;(function(r){r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right"})(Wi||(Wi={}));var Pt=class{constructor(e,t=!1,i=p.videoMaxWidth,r=p.videoMaxHeight){let n=!1;if(e){n={noiseSuppression:p.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let d;Rt&&(d=Rt.deviceId),typeof e=="string"&&(d=e),d&&(n.deviceId={exact:d})}let s=!1;if(t){s={width:{min:p.videoMinWidth,max:i,ideal:i},height:{min:p.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:p.videoAspectRatio},frameRate:{ideal:p.videoFrameRate}};let d;Ct&&(d=Ct.deviceId),typeof t=="string"&&(d=t),d&&(s.deviceId={exact:d}),p.videoFacingMode&&(s.facingMode={exact:p.videoFacingMode})}this.audio=n,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},xr=class extends Pt{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=p.screenFrameRate}};function Ia(){return o(this,null,function*(){Je=null,yield Ht()})}function Ta(){Je=null,Ht().then(()=>T.onDeviceChange())}function Ht(){return o(this,null,function*(){return Je||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Ni&&navigator.mediaDevices.addEventListener&&(Ni=I.throttle(Ta,1e3),navigator.mediaDevices.addEventListener("devicechange",Ni)),Je=navigator.mediaDevices.enumerateDevices().then(a=>{Ut=a.filter(r=>r.kind==="videoinput"?(r.label&&(Bi=!0),!0):!1),Bt=a.filter(r=>r.kind==="audioinput"?(r.label?Vi=!0:Ye.isMobile()&&Ye.browserName()==="Firefox"&&(Vi=Bi),!0):!1),Li=a.filter(r=>r.kind==="audiooutput");let e=We.get("videoinput"),t=We.get("audioinput"),i=We.get("audiooutput");return Ct=Ut.find(r=>r.deviceId===e)||null,Rt=Bt.find(r=>r.deviceId===t)||null,Ui=Li.find(r=>r.deviceId===i)||null,Je=Promise.resolve(a),a}).catch(()=>(Je=null,[]))))})}function Ca(){return o(this,null,function*(){return Ye.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(Or=!0),/^a=mid:0$/m.test(t.sdp)&&(kr=!0),a()}).catch(a)}):Promise.resolve()})}function Wt(a,e){return o(this,null,function*(){c.debug("Try to get media",a.getNative());let t=Ye.hasPermissions(a.isVideo());!t&&!e&&T.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield Ia()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?re.CAMERA_PERMISSION:re.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?re.CAMERA_ACCESS:re.MIC_ACCESS;break}if(a.canSimplify())return Wt(a.simplify(),e);let r=e||re.UNKNOWN;throw T.onPermissionsError(r),r}})}function Ra(a){return o(this,null,function*(){c.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&&(c.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw re.SCREEN_PERMISSION;default:throw re.SCREEN_ACCESS}}})}function ji(){return Gt.length||(Gt=(()=>{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]:Ea,a&&a[1]||i[2]||wr,e,t]})()),Gt}var Ye;(function(V){function a(){return o(this,null,function*(){return yield Ca(),Ht()})}V.init=a;function e(){return Ut}V.getCameras=e;function t(){return Bt}V.getMicrophones=t;function i(){return Li}V.getOutput=i;function r(){return Ut.length>0}V.hasCamera=r;function n(){return Bt.length>0}V.hasMicrophone=n;function s(){return Ct}V.getSavedCamera=s;function d(){return Rt}V.getSavedMicrophone=d;function l(){return Ui}V.getSavedOutput=l;function _(){return Bi}V.hasCameraPermission=_;function M(){return Vi}V.hasMicrophonePermission=M;function k(S=!1){return M()?r()&&S?_():!0:!1}V.hasPermissions=k;function q(S=!1,z=!0){return o(this,null,function*(){let m=n()&&z,K=r()&&S,se;if(!m&&!K)se=new MediaStream;else try{se=yield Wt(new Pt(m,K))}catch(v){se=new MediaStream}return se.getVideoTracks().length||se.addTrack(Ke()),se.getAudioTracks().length||se.addTrack(pe()),se})}V.getUserMedia=q;function j(){return o(this,null,function*(){return Ra(new xr(window.screen.width,window.screen.height))})}V.getScreenMedia=j;function y(S,z=!1){return o(this,null,function*(){let m=z?p.videoEffectMaxWidth:p.videoMaxWidth,K=z?p.videoEffectMaxHeight:p.videoMaxHeight;return Wt(new Pt(!1,S||!0,m,K))})}V.getUserVideo=y;function _e(S){return o(this,null,function*(){return Wt(new Pt(S||!0,!1))})}V.getUserAudio=_e;function De(S,z){return o(this,null,function*(){let K=(yield Ht()).find(se=>se.kind===S&&se.deviceId===z);return K?(S==="videoinput"?Ct=K:S==="audioinput"?Rt=K:S==="audiooutput"&&(Ui=K),We.set(S,z),K):null})}V.saveDeviceId=De;function pe(){if(!Ft||Ft.readyState==="ended"){let S=D(),z=S.createMediaStreamDestination(),m=S.createGain();m.gain.value=1e-5,m.connect(z),m.connect(S.destination);let K=S.createOscillator();K.type="sine",K.frequency.value=0,K.connect(m),K.start(),Ft=z.stream.getAudioTracks()[0]}return Object.assign(Ft.clone(),{enabled:!1})}V.getSilentMediaTrack=pe;function Ke(S=p.videoMinWidth,z=p.videoMinHeight){return at||(at=document.createElement("canvas"),at.getContext("2d")),at.width=S,at.height=z,(!Vt||Vt.readyState==="ended")&&(Vt=at.captureStream(p.videoFrameRate).getVideoTracks()[0]),Object.assign(Vt.clone(),{enabled:!1})}V.getBlackMediaTrack=Ke;function O(){if(ii()==="Edge"&&u()<70)return!1;try{let S=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&S.RTCPeerConnection&&S.RTCIceCandidate&&S.RTCSessionDescription&&S.HTMLCanvasElement&&S.HTMLCanvasElement.prototype.captureStream&&S.RTCRtpSender&&S.RTCRtpSender.prototype.replaceTrack&&S.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(S){return!1}}V.isBrowserSupported=O;function ye(){return!!navigator.mediaDevices.getDisplayMedia}V.isScreenCapturingSupported=ye;function be(){return Or}V.canVP8=be;function mt(){return kr}V.isUnifiedPlan=mt;function sr(){return V.browserName()==="Opera"&&V.os()==="Windows"}V.isBrokenH264=sr;function or(){return!(V.baseChromeVersion()&&V.isMobile())}V.canPreferH264=or;function cr(){return Gi||(Gi=(()=>{let S={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let z in S)if(S.hasOwnProperty(z)&&S[z].test(Te))return z;return"Unknown"})()),Gi}V.os=cr;function dr(){return Fi===null&&(Fi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(wr)),Fi}V.isMobile=dr;function ii(){return ji()[0]}V.browserName=ii;function u(){return ji()[1]}V.browserVersion=u;function R(){return ji()[3]}V.baseChromeVersion=R;function D(){return Hi||(Hi=new(window.AudioContext||window.webkitAudioContext)),Hi}V.getAudioContext=D})(Ye||(Ye={}));var b=Ye;import{BitStream as Pa}from"bit-buffer";var ya=65536,ze=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(c.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%ya!==e.sequence){c.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:n}=ze.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:n})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((n,s)=>n+s.data.byteLength,0),i=new Uint8Array(t),r=0;for(let n of e)i.set(new Uint8Array(n.data),r),r+=n.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new Pa(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),s=i.readBits(1)<<1|r;return s===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,s>=2&&i.index++,i.readBits(3)!==7?(i.index++,(s===1||s===3)&&(i.index+=3)):(s===1||s===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var yt=class extends ze{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;c.debug(`StreamBuilder started for participant [${e}]`),this._useImageBitmap="ImageBitmap"in window,qe.isBrowserSupported()?this._decoder=new qe:this._decoder=new tt,this._decoder.init(i=>this._drawImage(i)).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}_drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._removeStream(),c.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(b.browserName()==="Safari"&&b.browserVersion()>=15)}};var jt=1,ba=1,Nr=0,Lr=11,Ur=1,Br=2,Vr=4,Fr=8;function Gr(a,e,t,i,r,n,s){let d=0;e&&(d|=Ur),t&&(d|=Br),i&&(d|=Vr),s||(d|=Fr);let l=new ArrayBuffer(Lr),_=new DataView(l);if(_.setUint8(0,jt),_.setUint16(1,r),_.setUint32(3,a),_.setUint8(7,n?1:0),_.setUint16(8,Nr),_.setUint8(10,d),!s)return l;let M=new Uint8Array(l.byteLength+s.byteLength);return M.set(new Uint8Array(l),0),M.set(new Uint8Array(s),l.byteLength),M.buffer}function Hr(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,s=e.getUint16(8),d=e.getUint8(10),l=!!(d&Ur),_=!!(d&Br),M=!!(d&Vr),k=!!(d&Fr);if(t!==jt)throw new Error(`Unexpected protocol version. Got ${t}, expected ${jt}`);return{timestamp:r,start:l,end:_,keyframe:M,sequence:i,isVP9:n,ssrc:s,eos:k,data:a.slice(Lr)}}function Wr(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==jt||e.getUint8(1)!==ba||e.getUint16(2)!==Nr)}import{ID as X,build as jr,bytes as $r,element as te,number as Se,string as $t,unknownSizeElement as Kr,vintEncodedNumber as Oa}from"simple-ebml-builder";var Ma=lr(2,15)-1,Ki=1,Aa=5,Da=5,nt;(function(t){t.VP8="vp8",t.VP9="vp9"})(nt||(nt={}));var Kt=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),c.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=Kt._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return jr(e[0])}else return new Uint8Array;let t=e.reduce((n,s)=>n+s.countSize(),0),i=new Uint8Array(t),r=0;for(let n of e){let s=jr(n);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var n;let e=(n=this._sourceBuffer)==null?void 0:n.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-Aa);r-i>Da&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},Ae=class extends ze{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;c.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return te(X.EBML,[te(X.EBMLVersion,Se(1)),te(X.EBMLReadVersion,Se(1)),te(X.EBMLMaxIDLength,Se(4)),te(X.EBMLMaxSizeLength,Se(8)),te(X.DocType,$t("webm")),te(X.DocTypeVersion,Se(2)),te(X.DocTypeReadVersion,Se(2))])}static _genSegmentHeader(e,t,i){let r=te(X.Info,[te(X.TimecodeScale,Se(1e6)),te(X.MuxingApp,$t("vk-webm-builder")),te(X.WritingApp,$t("vk-webm-builder"))]),n=[te(X.PixelWidth,Se(e)),te(X.PixelHeight,Se(t))],s=te(X.Tracks,te(X.TrackEntry,[te(X.TrackNumber,Se(Ki)),te(X.TrackUID,Se(Ki)),te(X.TrackType,Se(1)),te(X.FlagLacing,Se(0)),te(X.DefaultDuration,Se(1e9)),te(X.CodecID,$t(`V_${i.toUpperCase()}`)),te(X.Video,n)]));return Kr(X.Segment,[r,s])}static _genClusterHeader(e){return Kr(X.Cluster,[te(X.Timecode,Se(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new Kt(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){c.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>c.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?nt.VP9:nt.VP8;this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,c.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,c.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=Ae._genWebmHeader();this._mediaBuffer.append(s);let d=Ae._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(d),this._mediaBuffer.cleanup()}let r=Math.round(i-this._clusterStartTime);if(r>Ma&&(this._clusterStartTime=i,r=0),r===0){c.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=Ae._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let n=te(X.SimpleBlock,[Oa(Ki),$r(Ae._intToU16BE(r)),Se((e.keyframe?1:0)<<7),$r(e.frameData)]);this._mediaBuffer.append(n,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),c.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported(`video/webm; codecs="${nt.VP8}"`))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported(`video/webm; codecs="${nt.VP9}"`))}};var st=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};c.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=n=>this._onDataChannelMessage(n.data)}_onDataChannelMessage(e){var n,s;let t=Hr(e),i=(s=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){c.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];if(!r){let d=l=>this._onStream(i,l);p.screenShareWebmBuilder&&Ae.isBrowserSupported()?r=new Ae(i,d):r=new yt(i,d),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,c.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(qe.isBrowserSupported()||tt.isBrowserSupported())&&(yt.isBrowserSupported()||Ae.isBrowserSupported())}};import qr from"@vkontakte/libvpx";var ka=1e3,bt=class extends ke{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 o(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=d=>t(),r.onerror=()=>i(new Error("Video element error"));let n=r.play(),s=()=>i(new Error("Autoplay is disabled"));n?n.catch(s):s()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return o(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 o(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;c.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 x=(o,s)=>{b(o);for(var t in s)u(o,t,{get:s[t],enumerable:!0})};var V={};x(V,{default:()=>g});var m;(function(t){t.VP9="vp09.00.50.08",t.VP8="vp8"})(m||(m={}));var r;(function(e){e.INIT="init",e.READY="ready",e.FRAME="frame",e.ERROR="error",e.DEBUG="debug",e.LOG_ERROR="log_error"})(r||(r={}));var g=(o,s)=>{let t;function E(a,e){return o({locateFile:s}).then(n=>{if(t=new n.VpxEncoder,t.debug(e),!t.init(a?n.VpxType.VP9:n.VpxType.VP8))throw self.postMessage({type:r.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");t.setMaxQuantizer(10),t.setTargetBitrate(1024)})}function R(a,e,n,i){let f=t.allocateImage(a,e);if(!f){self.postMessage({type:r.FRAME,error:"No buffer data"});return}f.set(new Uint8Array(n));let c=Math.round(performance.now()),l=150;if(!t.encode(c,l,i)){self.postMessage({type:r.FRAME,error:"Encode failed"});return}let d=t.readFrame();if(!d){self.postMessage({type:r.FRAME,error:"No encoded data"});return}t.readFrame()&&(self.postMessage({type:r.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:r.LOG_ERROR,message:"LibVPxEncoder-drop"}));let p=new Uint8Array(d.byteLength);p.set(d),self.postMessage({type:r.FRAME,frameType:i?"key":"delta",timestamp:c,duration:l,data:p.buffer},[p.buffer])}self.onmessage=a=>{switch(a.data.type){case r.INIT:E(a.data.isVP9,a.data.debug).then(()=>self.postMessage({type:r.READY})).catch(e=>self.postMessage({type:r.ERROR,error:String(e)}));break;case r.FRAME:R(a.data.width,a.data.height,a.data.imageData,a.data.keyFrame);break}}};return V;})();
|
|
10
|
+
`,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength})},[qr,qr.getUrl],{isVP9:this.isVP9(),debug:c.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(ue.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)},ka),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(),c.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var ot=class extends ke{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return o(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;c.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var p=Object.defineProperty;var h=n=>p(n,"__esModule",{value:!0});var A=(n,l)=>{h(n);for(var r in l)p(n,r,{get:l[r],enumerable:!0})};var y={};A(y,{default:()=>P});var i;(function(r){r.VP9="vp09.00.50.08",r.VP8="vp8"})(i||(i={}));var a;(function(t){t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error"})(a||(a={}));var P=()=>{let n=1e3,l,r,c,m,u,t,d=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?i.VP9:i.VP8,width:c,height:m,latencyMode:"realtime"}),self.postMessage({type:a.READY})}function F(e){E=self.setTimeout(()=>{d&&V(d,e)},n),!R&&(R=!0,r.read().finally(()=>{R=!1,self.clearTimeout(E)}).then(({done:o,value:s})=>{if(d==null||d.close(),d=null,!(o||!s)){if(!f){r.releaseLock(),l.cancel();return}d=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?i.VP9:i.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:a.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:a.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case a.INIT:b(e.data);break;case a.FRAME:F(e.data.keyFrame);break}}};return y;})();
|
|
11
|
+
`,r=>{var n;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(n=r.data)==null?void 0:n.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:p.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(ue.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),c.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var wa=16*1024,xa=11,Jr=wa-xa,Na=65536,$i=0,ct=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;c.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,n)=>{if(!this._destroyed){if(!r){c.warn("requestFrame failed, keyFrame: "+this._needKeyframe,n),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{c.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};ot.isBrowserSupported()?this._encoder=new ot(e,i):this._encoder=new bt(e,i),this._datachannel.onmessage=r=>{Wr(r.data)&&(c.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>c.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,n){let s=Gr(e,t,i,r,$i,this._encoder.isVP9(),n);return $i=($i+1)%Na,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return o(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+Jr),s=e.data.byteLength<=t+n.byteLength,d=this._wrapHeader(e.timestamp,!t,s,e.type==="key",n);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(d)}catch(l){c.warn("Error send data to DataChannel",l),r();return}s||window.setTimeout(()=>this._sendChunk(e,t+Jr,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(),c.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return ot.isBrowserSupported()||bt.isBrowserSupported()}};var ie=class{static get sessionKey(){return ie._sessionKey}static set sessionKey(e){ie._sessionKey=e}static get sessionSecretKey(){return ie._sessionSecretKey}static set sessionSecretKey(e){ie._sessionSecretKey=e}static get accessToken(){return ie._accessToken}static set accessToken(e){ie._accessToken=e}static isEmpty(){return!ie._sessionKey||!ie._sessionSecretKey}};var C=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(C._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(C._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(C._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(ie.accessToken=e.apiAuth.accessToken,ie.sessionKey=e.apiAuth.sessionKey,ie.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(C._params,e)}static get(e){return C._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.4.4-dev.717e1c2.0"}static get debug(){return!1}static get protocolVersion(){return C._params.joinFromMultipleDevices?6:5}static get platform(){return C._params.platform}static set platform(e){C._params.platform=e}static get clientType(){return C._params.clientType}static set clientType(e){C._params.clientType=e}static get device(){return C._params.device}static get apiAppId(){return 42}static get apiKey(){return C._params.apiKey}static get apiEnv(){switch(C._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 C._params.authToken}static set authToken(e){C._params.authToken=e}static get anonymToken(){return C._params.anonymToken}static set anonymToken(e){C._params.anonymToken=e}static get domain(){return C._params.domain}static get iceServers(){return C._params.iceServers}static set iceServers(e){C._params.iceServers=e}static get wssBase(){return C._params.wssBase}static set wssBase(e){C._params.wssBase=e}static get wssToken(){return C._params.wssToken}static set wssToken(e){C._params.wssToken=e}static get signalingReconnectDelay(){return C._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return C._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return C._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return C._params.waitConnectionDelay}static get waitResponseDelay(){return C._params.waitResponseDelay}static get waitMessageDelay(){return C._params.waitMessageDelay}static get debugLog(){return C._params.debugLog}static get forceRelayPolicy(){return C._params.forceRelayPolicy}static set forceRelayPolicy(e){C._params.forceRelayPolicy=e}static get videoMinWidth(){return C._params.videoMinWidth}static get videoMaxWidth(){return C._params.videoMaxWidth}static set videoMaxWidth(e){C._params.videoMaxWidth=e}static get videoMinHeight(){return C._params.videoMinHeight}static get videoMaxHeight(){return C._params.videoMaxHeight}static set videoMaxHeight(e){C._params.videoMaxHeight=e}static get videoAspectRatio(){return C._params.videoAspectRatio}static get videoFrameRate(){return C._params.videoFrameRate}static get videoFacingMode(){return C._params.videoFacingMode}static get screenFrameRate(){return C._params.screenFrameRate}static get videoEffects(){return C._params.videoEffects}static set videoEffects(e){C._params.videoEffects=e}static get videoEffectMaxWidth(){return C._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){C._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return C._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){C._params.videoEffectMaxHeight=e}static get voiceParams(){return C._params.voiceParams}static get specListenerParams(){return C._params.specListenerParams}static get iceRestartWaitTime(){return C._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return C._params.transportConnectionWaitTime}static get statisticsInterval(){return C._params.statisticsInterval}static set statisticsInterval(e){C._params.statisticsInterval=e}static get networkStatisticsInterval(){return C._params.networkStatisticsInterval}static get perfStatReportEnabled(){return C._params.perfStatReportEnabled}static get producerNotificationDataChannel(){return C._params.producerNotificationDataChannel&&st.isBrowserSupported()}static get producerCommandDataChannel(){return C._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return C._params.consumerScreenDataChannel&&ct.isBrowserSupported()}static get producerScreenDataChannel(){return C._params.producerScreenDataChannel&&C.producerNotificationDataChannel}static get screenShareWebmBuilder(){return C._params.screenShareWebmBuilder}static get noiseSuppression(){return C._params.noiseSuppression}static set noiseSuppression(e){C._params.noiseSuppression=e}static get preferH264(){return C._params.preferH264}static get preferVP9(){return C._params.preferVP9}static get audioNack(){return C._params.audioNack}static get consumerScreenTrack(){return C._params.consumerScreenTrack&&C.consumerScreenDataChannel}static get producerScreenTrack(){return C._params.producerScreenTrack&&C.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=C._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get videoTracksCount(){return C.producerNotificationDataChannel?C._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return C._params.breakVideoPayloadTypes}static get filteredMessages(){return C._params.filteredMessages}static get batchParticipantsOnStart(){return C._params.batchParticipantsOnStart}static get participantStateMapped(){return C._params.participantStateMapped}},p=C;p._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"PROD",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!1,producerScreenTrack:!1,videoTracksCount:0,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!1,joinFromMultipleDevices:!0};var J;(function(l){l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS"})(J||(J={}));function U(a,...e){let t=p.get(a);t&&setTimeout(t,0,...e)}function we(a){return Object.assign({},a)}function dt(a){return a.slice()}var qi;(function(le){function a(g,P){U("onLocalStream",g,we(P))}le.onLocalStream=a;function e(g,P){U("onScreenStream",g,we(P))}le.onScreenStream=e;function t(g,P){U("onLocalStreamUpdate",we(g),P)}le.onLocalStreamUpdate=t;function i(g){U("onLocalStatus",g)}le.onLocalStatus=i;function r(g,P){U("onRemoteStream",g,P)}le.onRemoteStream=r;function n(g,P,F){U("onRemoteLive",g,P,F)}le.onRemoteLive=n;function s(g,P){U("onRemoteScreenStream",g,P)}le.onRemoteScreenStream=s;function d(g,P,F,_t){U("onConversation",g,we(P),we(F),_t)}le.onConversation=d;function l(g,P){U("onRemoteMediaSettings",g,we(P))}le.onRemoteMediaSettings=l;function _(g,P){U("onRemoteParticipantState",g,we(P))}le.onRemoteParticipantState=_;function M(g,P,F=null){U("onRemoteStatus",g,P,F)}le.onRemoteStatus=M;function k(g,P,F=null){U("onParticipantStatus",g,P,F)}le.onParticipantStatus=k;function q(){U("onPermissionsRequested")}le.onPermissionsRequested=q;function j(g){U("onPermissionsError",g)}le.onPermissionsError=j;function y(g){U("onRemoteRemoved",g)}le.onRemoteRemoved=y;function _e(g,P,F){U("onCallState",g,P,we(F))}le.onCallState=_e;function De(g,P){U("onDeviceSwitched",g,P)}le.onDeviceSwitched=De;function pe(g,P,F,_t=!1,ri=!1,ai=null,ca=null){U("onMuteStates",we(g),dt(P),dt(F),_t,ri,ai,ca)}le.onMuteStates=pe;function Ke(g,P){U("onRolesChanged",g,dt(P))}le.onRolesChanged=Ke;function O(g){U("onLocalRolesChanged",dt(g))}le.onLocalRolesChanged=O;function ye(g,P){U("onPinnedParticipant",g,P)}le.onPinnedParticipant=ye;function be(g){U("onLocalPin",g)}le.onLocalPin=be;function mt(g){U("onOptionsChanged",dt(g))}le.onOptionsChanged=mt;function sr(){U("onCallAccepted")}le.onCallAccepted=sr;function or(){U("onRateNeeded")}le.onRateNeeded=or;function cr(g){U("onSpeakerChanged",g)}le.onSpeakerChanged=cr;function dr(g){U("onVolumesDetected",dt(g))}le.onVolumesDetected=dr;function ii(g,P){U("onLocalVolume",g,P)}le.onLocalVolume=ii;function u(g,P){U("onJoinStatus",g,P)}le.onJoinStatus=u;function R(g,P){U("onHangup",g,P)}le.onHangup=R;function D(g){U("onMultipartyChatCreated",we(g))}le.onMultipartyChatCreated=D;function V(){U("onDeviceChange")}le.onDeviceChange=V;function S(g){U("onFingerprintChange",g)}le.onFingerprintChange=S;function z(){U("onTokenExpired")}le.onTokenExpired=z;function m(g,P,F=!1){U("onChatMessage",g,P,F)}le.onChatMessage=m;function K(g,P,F=!1){U("onCustomData",g,P,F)}le.onCustomData=K;function se(g,P,F,_t,ri,ai){U("onRecordStarted",g,P,F,_t,ri,ai)}le.onRecordStarted=se;function v(){U("onRecordStopped")}le.onRecordStopped=v;function Ee(g){U("onLocalNetworkStatusChanged",g)}le.onLocalNetworkStatusChanged=Ee;function Fe(g){U("onNetworkStatusChanged",g)}le.onNetworkStatusChanged=Fe;function oe(g,...P){U("onDebugMessage",g,...P)}le.onDebugMessage=oe;function Le(g,P){let F=Object.assign({},g,{memory:P});U("onStatistics",F)}le.onStatistics=Le;function Q(){U("onAutoplayError")}le.onAutoplayError=Q;function Oe(g,P,F){U("onChatRoomUpdated",g,P,F)}le.onChatRoomUpdated=Oe})(qi||(qi={}));var T=qi;var de;(function(r){r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR"})(de||(de={}));var Ji;(function(O){let a="📞",e=(ye,...be)=>{T.onDebugMessage(ye,...be)},t=!1,i=(ye,be)=>(...mt)=>{ye(...mt),Rr(be,mt)},r=console.debug.bind(console,a),n=console.log.bind(console,a),s=console.warn.bind(console,a),d=console.error.bind(console,a),l=e.bind(null,de.DEBUG),_=e.bind(null,de.LOG),M=e.bind(null,de.WARN),k=e.bind(null,de.ERROR);O.debug=l,O.log=_,O.warn=M,O.error=k;function De(){return t}O.enabled=De;function pe(ye){t=ye,p.debugLog&&Mi(),ye?(O.debug=p.debugLog?i(r,de.DEBUG):r,O.log=p.debugLog?i(n,de.LOG):n,O.warn=p.debugLog?i(s,de.WARN):s,O.error=p.debugLog?i(d,de.ERROR):d):(O.debug=p.debugLog?i(l,de.DEBUG):l,O.log=p.debugLog?i(_,de.LOG):_,O.warn=p.debugLog?i(M,de.WARN):M,O.error=p.debugLog?i(k,de.ERROR):k)}O.toggle=pe;function Ke(ye,...be){switch(ye){case de.DEBUG:O.debug(...be);break;case de.LOG:O.log(...be);break;case de.WARN:O.warn(...be);break;case de.ERROR:O.error(...be);break}}O.send=Ke})(Ji||(Ji={}));var c=Ji;var Ce;(function(i){i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP"})(Ce||(Ce={}));var he;(function(d){function a(l){return l.length?typeof l[0]=="object"?l:l.map(_=>e(_)):[]}d.fromIds=a;function e(l,_=Ce.USER){return{id:l,type:_}}d.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?Ce.ANONYM:Ce.USER}}d.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}d.toString=i;function r(l,_=Ce.USER){return i(e(l,_))}d.fromIdToString=r;function n(l){try{return JSON.parse(l)}catch(_){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}d.fromString=n;function s(l,_){return l.id===_.id&&l.type===_.type}d.compare=s})(he||(he={}));var me;(function(r){function a(n,s=Ce.USER,d=0){return{id:n,type:s,deviceIdx:d}}r.fromId=a;function e(n){return`{"id":"${n.id}","type":"${n.type}","deviceIdx":"${n.deviceIdx}"}`}r.toString=e;function t(n,s){return Object.assign({deviceIdx:s},he.fromSignaling(n))}r.fromSignaling=t;function i(n){return n&&typeof n=="object"?n.deviceIdx:0}r.getDeviceIdx=i})(me||(me={}));var Ie;(function(r){r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE"})(Ie||(Ie={}));var Yr="s",zr="m";function Qe(a){return a.participantId+(a.mediaType?rt+Yr+a.mediaType:"")+(a.streamName?rt+zr+a.streamName:"")}function Mt(a){let e=a.split(rt),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i=null,r,n=0;for(let d of e)switch(d.charAt(0)){case Yr:i=La(d.slice(1));break;case zr:r=d.slice(1);break;case Lt:n=Number.parseInt(d.slice(1),10);break;default:throw new Error("Unexpected parameter type "+d.charAt(0)+" in stream description "+a)}return{participantId:I.compose(t,n),mediaType:i,streamName:r}}function La(a){for(let e of Object.keys(Ie))if(e===a)return Ie[e];return null}function Yi(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 qt(a,e){return!(!Yi(a.camera,e.camera)||!Yi(a.screenSharing,e.screenSharing))}function zi(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function Qr(a){return{camera:Object.assign({},a.camera),screenSharing:Object.assign({},a.screenSharing)}}function Xr(a){try{return btoa(JSON.stringify(a))}catch(e){c.warn("WaitingParticipant: failed convert to string",a,e)}return null}function Zr(a){try{return JSON.parse(atob(a))}catch(e){c.warn("WaitingParticipant: failed convert from string",a,e)}return null}var At=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,h.log(f.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,h.log(f.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?(c.log("Failed to fix RV"),h.log(f.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),h.log(f.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,c.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===$.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Jt=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(!((s=this._output)==null?void 0:s.audioTrack))return;let e=b.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{c.warn("Error on play audio"),T.onAutoplayError()},r=d=>{t.srcObject=new MediaStream([d]),t.load();let l=t.play();l?l.catch(i):i()},n=()=>{var l;c.debug("Recover audio playback");let d=(l=this._output)==null?void 0:l.audioTrack;d?r(d):c.warn("Broken audio track")};t.onpause=n,t.onstalled=n,t.onerror=n,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return o(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=b.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw h.log(f.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var Ua=90,Ba=3,Yt=class extends Z{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),T.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>Ua?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Ba)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var Va=44100,Dt=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=b.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=Va/this._fftBins.length,t=Math.ceil(p.voiceParams.minFreq/e),i=Math.floor(p.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((n,s)=>n+s,0)/e.length/255,r=this._lastSmoothedLevel*p.voiceParams.smoothing+i*(1-p.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 zt=class extends Z{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&T.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,p.voiceParams.interval)};this._interval=window.setTimeout(t,p.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,ae.SOURCE_CHANGED,r=>{r.kind===$.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new Dt("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 Fa=1e3;function xe(a,e,t=0){return e in a&&a[e]?a[e]:t}function ea(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function je(a,e){return t=>t[a]===e}function Ga(a){return(e,t)=>e[a]-t[a]}function Qt(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function Ha(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Wa(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Qi(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=Wa(t[1])?Qi(t[1]):t[1],e),{})}function ja(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function Ka(a){return o(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(ja).then(Ha)})}function $a(a){let e=a.filter(je("type","candidate-pair")).sort(Ga("priority")).find(ea(je("nominated",!0),je("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=a.find(je("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=a.find(je("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),Qi(t)}function qa(a,e){let t=Qt("id",a),i=a.filter(ea(je("type","inbound-rtp"),je("type","outbound-rtp")));b.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,s)=>{if(!n[s.ssrc])n[s.ssrc]=s;else{let d=Object.assign({},n[s.ssrc],s),l=n[s.ssrc].isRemote?s:n[s.ssrc];d.id=l.id,d.type=l.type,delete d.isRemote,delete d.remoteId,n[d.ssrc]=d}return n},{})));let r={};if(b.browserName()==="Safari"){let n=a.filter(je("type","track"));r=Qt("trackIdentifier",n)}return i.map(n=>{let s=Number(n.ssrc),d=n.mediaType||n.kind,l=n.trackId,_=n.type,M=n.codecId;if(b.browserName()==="Safari"){let q=/^.+_([\d]+)$/.exec(n.id);if(q&&(s=parseInt(q[1],10)),d=n.id.indexOf("Audio")>0?"audio":"video",e[s]){let j=d+"-"+e[s];r[j]&&(l=r[j].id)}}if(!_||!s||!d)return null;let k={ssrc:s,type:_,kind:d,bytesReceived:xe(n,"bytesReceived"),bytesSent:xe(n,"bytesSent"),jitter:xe(n,"jitter"),packetsLost:xe(n,"packetsLost"),packetsReceived:xe(n,"packetsReceived"),packetsSent:xe(n,"packetsSent"),fractionLost:xe(n,"fractionLost"),pliCount:xe(n,"pliCount"),firCount:xe(n,"firCount"),nackCount:xe(n,"nackCount"),userId:e[s]};if(M&&t[M]){let q=t[M];k.clockRate=q.clockRate,k.mimeType=q.mimeType}if(l&&t[l]){let q=t[l];k.frameHeight=q.frameHeight,k.frameWidth=q.frameWidth,k.framesDecoded=q.framesDecoded,k.framesReceived=q.framesReceived,k.framesDropped=q.framesDropped}return Qi(k)}).filter(n=>!!n)}function Ja(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=Qt("ssrc",a.rtps),i=Qt("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let s=t[n],d=i[n];if(!(!s||!d)){if(s.bytesReceived&&s.bytesReceived>d.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-d.bytesReceived)/r)),s.bytesSent&&s.bytesSent>d.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-d.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>d.packetsReceived||s.packetsLost>d.packetsLost){let l=s.packetsLost-d.packetsLost,_=s.packetsReceived-d.packetsReceived;s.packetLoss=parseFloat((100*l/(l+_)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&d.framesDropped&&s.framesDropped>d.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-d.framesDropped)/r).toFixed(0)))}}),a}function Ot(i,r){return o(this,arguments,function*(a,e,t={}){let n=yield Ka(a),s={timestamp:Date.now(),transport:$a(n),rtps:qa(n,t)};return e?Ja(s,e):(yield I.delay(Fa),Ot(a,s,t))})}var Xt=.8,Xe=class extends Z{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=w.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,ge.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ae.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ae.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:p.iceServers,iceTransportPolicy:p.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(s){h.log(f.ERROR,"addTrack-direct"),c.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===w.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==w.IDLE&&e!==w.CLOSED&&e!==w.FAILED&&this._startStatInterval()}open(e=null){return o(this,null,function*(){if(this._isOpen){c.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(c.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){h.log(f.ERROR,"addTrack-direct"),c.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(w.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(E.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){qt(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(E.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?(c.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(w.FAILED)):(c.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(w.CLOSED)),this._triggerEvent(E.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(E.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case x.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case x.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 x.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((n=e.data.sdk)==null?void 0:n.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=I.getPeerIdString(e.peerId);I.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){c.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw h.log(f.ERROR,"addIceCandidate-direct"),c.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else c.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return o(this,null,function*(){if(!this._remoteCandidates[e]){c.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 o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){c.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 h.log(f.ERROR,"setRemoteDescription-direct"),c.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){c.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(E.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(E.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return o(this,null,function*(){e.candidate&&this._signaling.ready&&(c.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(c.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=>o(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(c.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===w.IDLE||e===w.OPENED?this._setState(w.CONNECTING):this._setState(w.RECONNECTING);break}}_onConnectionStateChange(){switch(c.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),h.log(f.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(w.CONNECTED),this._stopReconnection(),I.getPeerConnectionHostInfo(this._pc).then(e=>{e&&h.log(f.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(w.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(c.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},p.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(c.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(W.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(h.log(f.ICE_RESTART),c.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):c.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,c.error("Ice restart failed",{participantId:this._participantId}),h.log(f.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},p.iceRestartWaitTime)}_createOffer(e){return o(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return c.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw c.error("Unable to create offer",i,{participantId:this._participantId}),h.log(f.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=Xe._patchDescription(i),c.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw c.error("Unable to set local description",i,{participantId:this._participantId}),h.log(f.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return o(this,null,function*(){return c.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw c.error("Unable to create answer",e,{participantId:this._participantId}),h.log(f.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=Xe._patchDescription(e),c.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw c.error("Unable to set local description",e,{participantId:this._participantId}),h.log(f.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!b.baseChromeVersion();return e.sdp=I.patchSDP(e.sdp,p.preferH264&&b.canPreferH264(),b.isBrokenH264(),p.preferVP9,t&&p.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=>{c.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),h.log(f.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Ot(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:W.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:W.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(E.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,p.statisticsInterval)})};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=pe=>pe.rtt<=this._networkLimits.goodNet.rtt&&pe.loss<=this._networkLimits.goodNet.loss,i=pe=>pe.rtt>=this._networkLimits.badNet.rtt||pe.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((pe,Ke)=>Math.max(pe,Ke.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-Xt)+r*Xt,loss:this._lastNetworkStat.loss*(1-Xt)+n*Xt},d=i(s),l=t(s),_=i(this._remoteNetworkStat),M=t(this._remoteNetworkStat),k=i(this._lastNetworkStat),q=t(this._lastNetworkStat),_e=d||_?.2:l&&M?1:0,De=Date.now();if((k!==d||q!==l||De-this._lastNetworkStat.date>p.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(pe=>{c.warn("Unable to send [bad-net]",pe)})),_e){let pe={};pe[this._participantId]=pe[""]=_e,this._triggerEvent(E.NETWORK_STATUS,pe)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=I.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(T.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=I.applySettings(this._pc,e,this._prevConsumerSettings))}};var Xi;(function(r){r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare"})(Xi||(Xi={}));var kt=Xi;import{decode as pt}from"messagepack";var Zi=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var n,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let d=pt(r);return Object.entries(d).forEach(([y,_e])=>{let De=Mt(y);this.streamDescriptionByCompactId.set(_e,De)}),null;case 2:case 4:let l=pt(r),_=[];for(let y of l){let _e=this.getStreamDescription(y);_e&&_.push(_e.participantId)}return i===2?{type:"notification",notification:x.AUDIO_ACTIVITY,activeParticipants:_}:{type:"notification",notification:x.STALLED_ACTIVITY,stalledParticipants:_};case 3:let M=pt(r);return{type:"notification",notification:x.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(M))==null?void 0:n.participantId};case 5:let k=pt(r);return{type:"notification",notification:x.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:k[0],maxDimension:k[1]}};case 6:let q=pt(r),j={};for(let[y,_e]of Object.entries(q)){let De=(s=this.getStreamDescription(Number(y)))==null?void 0:s.participantId;De&&(j[De]=_e/100)}return{type:"notification",notification:x.NETWORK_STATUS,statuses:j};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=pt(e),i=[];for(let[r,n]of Object.entries(t)){let s=n[0],d=n[1],l=n[2],_;if(s!==null){if(_=this.getStreamDescription(s),!_){c.error(`could not uncompress participant ID ${s}`);continue}}else _=null;if(l===null){c.error("unexpected null sequenceNumber",r,n);continue}let M=Me.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,k=d?d>>>0:null;i.push({participantStreamDescription:_,streamId:M,rtpTimestamp:k,sequenceNumber:l})}return{type:"notification",notification:x.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var ta="videochat-epi",wt=class extends Z{constructor(e,t){super();this._previousTimestamp=0;this._signaling=t,this.subscribe(e,E.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(ta)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return o(this,null,function*(){if(!p.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(ta,r.estimatedPerformanceIndex)}catch(r){}this._previousTimestamp=i}})}};var Ya=90,za=4294967295,Re=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=w.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,ge.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ae.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ae.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,ae.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new wt(this,e),this._serverSettings=i,c.debug("ServerTransport: Created")}getState(){return this._state||w.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==w.IDLE&&e!==w.CLOSED&&e!==w.FAILED&&this._startStatInterval()}open(){if(this._isOpen){c.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(c.error("ServerTransport: Closed",e),this._setState(w.FAILED)):(c.debug("ServerTransport: Closed"),this._setState(w.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){qt(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,Re._closeDataChannel(this._producerNotification),Re._closeDataChannel(this._producerCommand),Re._closeDataChannel(this._producerScreen),Re._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(E.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{c.debug(`[${t}] data channel opened`),r.onerror=n=>{c.error(`[${t}] data channel error`,n)},i(r)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection");let t={};b.baseChromeVersion()&&(t.sdpSemantics=Re._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=I.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Re._onSignalingStateChange.bind(this,this._pc),p.producerNotificationDataChannel&&this._createDataChannel(this._pc,kt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Zi,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),p.producerCommandDataChannel&&this._createDataChannel(this._pc,kt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),p.producerScreenDataChannel&&this._createDataChannel(this._pc,kt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){c.error("ServerTransport: Unable to add media source tracks",i),h.log(f.ERROR,"addTrack-single"),this.close(i);return}p.consumerScreenDataChannel&&this._createDataChannel(this._pc,kt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(w.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==w.OPENED&&(this._setState(w.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(E.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(E.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(E.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(E.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
|
|
12
|
+
`).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||!p.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new ct(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!p.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new st(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(E.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(E.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!p.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==$.video)return;let r=!this._disabledSenders.has(i),n=e.maxDimension!==0;if(r&&!n){c.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(b.getBlackMediaTrack()).catch(d=>{c.error("Could not disable video upload",d)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&n&&s){c.log("Enabling video upload"),this._disabledSenders.delete(i);let d=i.track;d.enabled=s.enabled,i.replaceTrack(s).then(()=>d.stop()).catch(l=>{c.error("Could not enable video upload",l)})}I.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(E.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,p.statisticsInterval)};this._statInterval=window.setTimeout(e,p.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 o(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Ot(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(E.REMOTE_DATA_STATS,{inbound:{topology:W.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:W.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=Me.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(E.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:wt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:p.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:p.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:p.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:p.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:Re._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:p.videoTracksCount};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return o(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,c.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(c.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw c.error("[single] unable to set remote offer",i),h.log(f.ERROR,"setRemoteDescription-single"),i}).then(()=>o(this,null,function*(){if(c.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw c.error("[single] unable to create answer",i),h.log(f.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=I.patchSDP(i.sdp,!1,b.isBrokenH264(),!1),i)).then(i=>o(this,null,function*(){if(c.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw c.error("[single] unable to set local answer",i),h.log(f.ERROR,"setLocalDescription-single"),i}).then(i=>o(this,null,function*(){c.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),c.debug("[single] remote offer has been processed")})).catch(i=>{c.warn("[single] unable to send local answer",i),h.log(f.ERROR,"acceptProducer")}).then(()=>o(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){c.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 o(this,null,function*(){if(!!this._isOpen)switch(e.notification){case x.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case x.REALLOC_CON:this._reconnect();break;case x.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case x.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case x.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case x.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return o(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),p.breakVideoPayloadTypes&&(c.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){c.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent(E.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(E.REMOTE_TRACK_ADDED,i.id,i,t.track)):c.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){c.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(c.debug("[single] connection state changed",{state:e.connectionState},t),h.log(f.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===w.IDLE||i===w.OPENED?this._setState(w.CONNECTING):e.iceConnectionState==="checking"&&this._setState(w.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(w.RECONNECTING);break;case"connected":this._setState(w.CONNECTED),I.getPeerConnectionHostInfo(e).then(r=>{r&&h.log(f.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(p.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=>{c.error("ServerTransport: Unable to replace track",r),h.log(f.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=b.baseChromeVersion();return e?p.isUnifiedPlanSupported("Chrome",e):p.isUnifiedPlanSupported(b.browserName(),b.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return h.log(f.PAT_WAITING_TIME_ERROR,"noConnection"),c.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return h.log(f.PAT_WAITING_TIME_ERROR,"noReceiver"),c.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return c.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return h.log(f.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),c.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let d=t-s&za,l=Math.ceil(d/Ya);return Math.min(100,Math.max(0,l))}};var E;(function(y){y.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",y.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",y.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",y.REMOTE_ALL_STALL="REMOTE_ALL_STALL",y.REMOTE_DATA_STATS="REMOTE_DATA_STATS",y.STATE_CHANGED="STATE_CHANGED",y.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",y.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",y.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",y.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",y.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",y.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",y.NETWORK_STATUS="NETWORK_STATUS",y.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED"})(E||(E={}));var w;(function(d){d.IDLE="IDLE",d.OPENED="OPENED",d.CONNECTING="CONNECTING",d.RECONNECTING="RECONNECTING",d.CONNECTED="CONNECTED",d.CLOSED="CLOSED",d.FAILED="FAILED"})(w||(w={}));var W;(function(t){t.DIRECT="DIRECT",t.SERVER="SERVER"})(W||(W={}));var er=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=w.IDLE;this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,ge.NOTIFICATION,this._onSignalingNotification.bind(this)),e===W.SERVER&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){c.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology===W.DIRECT&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology===W.SERVER&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){c.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){c.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology===W.DIRECT&&this._directTransport&&this._directTransport.open(t),this._topology===W.SERVER&&this._serverTransport&&(this._serverTransport.open(),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),c.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&c.warn(`The participant [${e}] transport has already deallocated`),this._topology===W.DIRECT&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology===W.SERVER&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,w.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(E.STATE_CHANGED,i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent(E.STATE_CHANGED,[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent(E.LOCAL_STATE_CHANGED,e))}_onSignalingNotification(e){if(e.notification===x.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===x.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),h.log(f.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology===W.SERVER&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology===W.DIRECT){let i=e.offerTo||[],r=e.offerToTypes||[],n=e.offerToDeviceIdxs||[],s=i.length&&r.length?I.composeParticipantId(i[0],r[0],n[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){c.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&c.warn("Topology changed to DIRECT, but the allocated participants count more then one");let d=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=s===d;this._directTransport=this._createDirectTransport(d,l)}this._opened.indexOf(d)>=0&&this._directTransport.open()}this._triggerEvent(E.TOPOLOGY_CHANGED,this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new Xe(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),this._dtListeners&&this._dtListeners.length>0&&c.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener(E.REMOTE_TRACK_ADDED,this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener(E.REMOTE_TRACK_REMOVED,this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener(E.REMOTE_DATA_STATS,this._onDirectRemoteDataStats.bind(this)),i.addEventListener(E.STATE_CHANGED,this._onDirectTransportChanged.bind(this,e)),i.addEventListener(E.NETWORK_STATUS,this._onTransportNetworkStatus.bind(this)),i.addEventListener(E.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this,W.DIRECT))),i}_createServerTransport(){let e=new Re(this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!1),this._stListeners&&this._stListeners.length>0&&c.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener(E.REMOTE_TRACK_ADDED,this._onServerRemoteTrackAdded.bind(this)),e.addEventListener(E.REMOTE_TRACK_REMOVED,this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener(E.REMOTE_ALL_STALL,this._onServerRemoteAllStall.bind(this)),e.addEventListener(E.REMOTE_DATA_STATS,this._onServerRemoteDataStats.bind(this)),e.addEventListener(E.STATE_CHANGED,this._onServerTransportChanged.bind(this)),e.addEventListener(E.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener(E.SIGNALLED_ACTIVE_PARTICIPANTS,this._onTransportActiveParticipants.bind(this)),e.addEventListener(E.SIGNALLED_SPEAKER_CHANGED,this._onTransportSpeakerChanged.bind(this)),e.addEventListener(E.SIGNALLED_STALLED_PARTICIPANTS,this._onTransportStalledParticipants.bind(this)),e.addEventListener(E.NETWORK_STATUS,this._onTransportNetworkStatus.bind(this)),e.addEventListener(E.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),e.addEventListener(E.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this,W.SERVER))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;p.noiseSuppression!==e&&(p.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t===w.CONNECTED&&this._topology===W.DIRECT&&this._releaseServerTransport(!0),(t===w.CLOSED||t===w.FAILED)&&(this._releaseDirectTransport(!1),this._topology===W.DIRECT)){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology===W.DIRECT&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e===w.CONNECTED&&this._topology===W.SERVER&&this._releaseDirectTransport(!0),(e===w.CLOSED||e===w.FAILED)&&(this._releaseServerTransport(!1),this._topology===W.SERVER&&(this._allocated=[],this._opened=[])),this._topology===W.SERVER&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent(E.ACTIVE_PARTICIPANTS_NO_SIGNAL)}_onTransportActiveParticipants(e){this._topology===W.SERVER&&this._triggerEvent(E.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_onTransportStalledParticipants(e){this._topology===W.SERVER&&this._triggerEvent(E.SIGNALLED_STALLED_PARTICIPANTS,e)}_onTransportSpeakerChanged(e){this._topology===W.SERVER&&this._triggerEvent(E.SIGNALLED_SPEAKER_CHANGED,e)}_onTransportNetworkStatus(e){this._triggerEvent(E.NETWORK_STATUS,e)}_onRemoteStreamSecond(e,t){this._triggerEvent(E.REMOTE_STREAM_SECOND,e,t)}_onPeerConnectionClosed(e){this._triggerEvent(E.PEER_CONNECTION_CLOSED,e)}_onServerRemoteAllStall(e){this._topology===W.SERVER&&this._triggerEvent(E.REMOTE_ALL_STALL,e)}_onServerRemoteDataStats(e){this._triggerEvent(E.REMOTE_DATA_STATS,e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent(E.REMOTE_TRACK_ADDED,e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent(E.REMOTE_TRACK_REMOVED,e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent(E.REMOTE_DATA_STATS,e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent(E.REMOTE_TRACK_ADDED,e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent(E.REMOTE_TRACK_REMOVED,e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!==W.SERVER?(h.log(f.PAT_WAITING_TIME_ERROR,"wrongTopology"),c.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(h.log(f.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Ve;(function(e){e.VOLUMES_DETECTED="VOLUMES_DETECTED"})(Ve||(Ve={}));var tr=class extends Z{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,E.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,E.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,E.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,E.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===$.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Dt(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,p.voiceParams.interval)};this._interval=window.setTimeout(n,p.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===$.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(Ve.VOLUMES_DETECTED,e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var lt;(function(e){e.SPEAKER_CHANGED="SPEAKER_CHANGED"})(lt||(lt={}));var ir=class extends Z{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,Ve.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,E.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,E.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,E.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>p.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*p.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent(lt.SPEAKER_CHANGED,i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent(lt.SPEAKER_CHANGED,e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var Zt=class extends 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,E.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,Ve.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===w.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),p.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),p.specListenerParams.volumeTimeout))),t===w.FAILED&&this._connectionTimeout&&(c.warn("Transport failed, send callSpecError"),h.log(f.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!==w.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(c.warn("There is not connected transport, send callSpecError"),h.log(f.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),h.log(f.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&c.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Qa=1e3,Xa=1e4,Y;(function(r){r.IDLE="IDLE",r.PROCESSING="PROCESSING",r.ACTIVE="ACTIVE",r.CLOSE="CLOSE"})(Y||(Y={}));var Za=15,B=class extends Z{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state=Y.IDLE;this._participantState=H.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._signalingServerSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;h.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),h.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new Jt,p.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Qa))}static current(){return B._current}static hangupAfterInit(){B._activationMutex&&!B._current&&(B._delayedHangup=!0)}static id(){var e,t;return((t=(e=B._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,s=!1){return o(this,null,function*(){if(B._activationMutex)throw h.log(f.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new N(A.FAILED);B._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let d=this._mediaSource.getMediaSettings();t===Ue.CHAT||e.length>1?this._logWithMediaSettings(f.OUTGOING_MULTIPARTY_CALL,d):this._logWithMediaSettings(f.OUTGOING_CALL,d);let l=yield this._startConversation(e,t,Ge.OUTGOING,i,r,n,s);if(!this._conversation)throw new N(A.UNKNOWN_ERROR);if(this._participantState=H.ACCEPTED,this._signaling.changeMediaSettings(d),yield this._registerParticipants(l.conversation.participants),this._processConnectionData(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new N(A.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let _=Object.values(this._participants),M;return p.batchParticipantsOnStart&&(M=I.mapSharedParticipants(_)),T.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,M),T.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),B._current=this,this._conversation.concurrent?yield this._acceptConcurrent():p.batchParticipantsOnStart||this._setParticipantsStatus(_,J.WAITING),this._conversation}catch(d){throw this._close(d,"Unable to start conversation"),d}finally{B._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){if(B._activationMutex)throw h.log(f.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new N(A.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(f.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new N(A.UNKNOWN_ERROR);return T.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(c.log("In waiting hall"),B._current=this,B._activationMutex=!1,this._signaling.readyToSend(),T.onLocalStatus(J.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw B._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return o(this,null,function*(){c.debug("Join conversation part 2"),B._activationMutex=!0;try{if(this._participantState=H.ACCEPTED,!this._conversation||!this._mediaSource)throw new N(A.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(A.CANCELED);let t=Object.values(this._participants),i;return p.batchParticipantsOnStart&&(i=I.mapSharedParticipants(t)),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),T.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state=Y.ACTIVE,this._changeFeatureSet(),B._current=this,p.batchParticipantsOnStart||this._setParticipantsStatus(t,J.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 o(this,arguments,function*(e,t=ee.USER,i){if(B._activationMutex)throw c.warn("Conversation: there is already running activation"),new N(A.REJECTED);B._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new N(A.UNKNOWN_ERROR);if(!n.conversation.participants.find(d=>{var l;return d.state===H.CALLED&&d.id===((l=this._conversation)==null?void 0:l.userId)}))throw c.log("Push rejected (there is an active call)"),h.log(f.PUSH,"rejected"),new N(A.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),h.log(f.PUSH,"accepted"),B._current=this,B._delayedHangup)throw new N(A.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(li.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>I.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return o(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new N(A.UNKNOWN_ERROR);this._state=Y.PROCESSING;let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(f.ACCEPT_CONCURRENT,e),c.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),T.onCallAccepted(),this._state=Y.ACTIVE,this._participantState=H.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return o(this,null,function*(){if(this._state!==Y.IDLE)throw h.log(f.ERROR,"acceptIncoming"),c.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(A.UNKNOWN_ERROR);this._state=Y.PROCESSING,c.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(f.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=H.ACCEPTED;let i=Object.values(this._participants),r;p.batchParticipantsOnStart&&(r=I.mapSharedParticipants(i)),T.onCallAccepted(),T.onLocalStream(this._mediaSource.getStream(),t),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),T.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(He.MUTE)||n.includes(He.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state=Y.ACTIVE,this._changeFeatureSet(),p.batchParticipantsOnStart||this._setParticipantsStatus(i,J.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return o(this,null,function*(){var e;if(this._state!==Y.IDLE)throw h.log(f.ERROR,"declineIncoming"),c.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state=Y.PROCESSING,c.debug("Decline incoming call"),this._logWithMediaSettings(f.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=H.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(A.REJECTED)),this._close(new N(A.REJECTED))})}hangup(){return o(this,null,function*(){c.debug("Hangup");let e=this._state===Y.ACTIVE?A.HUNGUP:A.CANCELED;h.log(f.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new N(e))):T.onHangup(new N(A.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new N(A.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=A.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(I.composeId(n),n,r)})}removeParticipant(e,t=!1){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){if(!this._transport)return;let i=[];for(let r of e)(r.state===H.CALLED||r.state===H.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===H.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&c.error(t,e),c.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(A.FAILED):h.log(f.ERROR,e.hangup),B._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([A.CANCELED,A.NOT_FRIENDS,A.CALLEE_IS_OFFLINE,A.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===A.REJECTED&&!e.remote){T.onHangup(e,i),this.destroy();return}if(e.hangup===A.HUNGUP&&(!e.remote||this._participantState===H.CALLED)){T.onHangup(e,i),this.destroy();return}if(e.hangup===A.MISSED&&!e.remote){T.onHangup(e,i),this.destroy();return}if(e.hangup===A.SOCKET_CLOSED&&B._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===A.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state=Y.CLOSE,this._participantState=H.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),h.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,T.onHangup(e||new N(A.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;c.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),h.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return o(this,null,function*(){let t=yield this._api.getConversationParams(e);c.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let s=r.urls.filter((d,l,_)=>_.indexOf(d)===l);s.forEach(d=>s.push(`${d}?transport=tcp`)),i.push({urls:s,username:r.username,credential:r.credential})}return p.iceServers=i,p.wssBase=t.endpoint,p.wssToken=t.token,t.client_type&&(p.clientType=t.client_type),t})}_startConversation(e,t,i,r,n="",s=!1,d=!1){return o(this,null,function*(){let l=I.uuid();c.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let _=r.includes(ce.VIDEO),M=yield this._api.startConversation(l,e,t,_,n,s,d);c.debug("Api.startConversation",M),yield this._getConversationParams(M.id);let k=yield this._connectSignaling(Be.START,M);return yield this._setConversation(M,k,i),k})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n}=e;c.debug("Conversation: join",{conversationId:t,joinLink:n});let s=i.includes(ce.VIDEO),d;if(t)d=yield this._api.joinConversation(t,s,r);else if(n)d=yield this._api.joinConversationByLink(n,s);else throw new N(A.UNKNOWN_ERROR);c.debug("Api.joinConversation",d),yield this._getConversationParams(d.id);let l=yield this._connectSignaling(Be.JOIN,d);return yield this._setConversation(d,l,Ge.JOINING),l})}_prepareConversation(r){return o(this,arguments,function*(e,t=ee.USER,i){c.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let n=this._api.getUserId();if(!n)throw new N(A.UNKNOWN_ERROR);let s=yield this._getConversationParams(e);c.error("got params",s);let d=s.device_idx||0,l={id:e,peerId:i,endpoint:`${p.wssBase}?userId=${n}&entityType=${t}&deviceIdx=${d}&conversationId=${e}&token=${p.wssToken}`,is_concurrent:!1,p2p_forbidden:!1,device_idx:d},_=yield this._connectSignaling(Be.ACCEPT,l);return B._current&&(B._current._participantState===H.ACCEPTED||B._current._participantState===H.CALLED)?(c.log("Push rejected (busy)"),h.log(f.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(A.BUSY),Promise.reject({hangup:A.BUSY})):(B._current&&(B._current.destroy(),B._current=null),yield this._setConversation(l,_,Ge.INCOMING,t),_)})}_createParticipant(e){return o(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:fe(),participantState:{},state:H.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);if(e.externalId){let i=I.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(i,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return t})}_getParticipantId(e){return o(this,null,function*(){try{let t=I.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new N(A.NETWORK_ERROR),t),t}})}_setConversation(n,s,d){return o(this,arguments,function*(e,t,i,r=ee.USER){let l=t.conversation.participants.map(j=>j.id);yield this._api.prepareUserIds(l);let _=this._api.getUserId(),M=e.device_idx||0;if(!_){let j=(t.conversation.participants||[]).find(y=>I.comparePeerId(y.peerId,t.peerId));if(!j)throw new N(A.UNKNOWN_ERROR);_=Number(j.id),j.idType&&(r=j.idType),j.deviceIdx&&(M=j.deviceIdx),this._api.setUserId(_)}let k=I.composeParticipantId(_,r,M),q=yield this._getParticipantId(k);this._conversation={userId:_,compositeUserId:k,externalId:q,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||W.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(p.forceRelayPolicy=e.p2p_forbidden),h.log(f.RELAY_POLICY,p.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new N(A.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||W.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new wi;return this.subscribe(e,ae.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,ae.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new At(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,ge.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,ge.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,ge.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return o(this,null,function*(){if(!!this._conversation)for(let t of e){let i=I.composeId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(c.debug(`Local roles changed: ${t.roles}`),T.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===H.HUNGUP||t.state===H.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],A.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&me.fromSignaling(t.externalId,t.deviceIdx),mediaSettings:fe(t.mediaSettings),participantState:I.mapParticipantState(t),state:t.state,roles:t.roles||[],status:p.batchParticipantsOnStart?J.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(c.debug(`Roles for participant [${i}] changed: ${t.roles}`),T.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){I.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(ci.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new er(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new Yt,this.subscribe(this._transport,E.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,E.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,E.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,E.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,E.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,E.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,E.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,E.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,E.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,E.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,E.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,E.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Ge.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===H.ACCEPTED||t.state===H.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new tr(this._transport),this.subscribe(this._volumesDetector,Ve.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new ir(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,lt.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new zt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Zt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=b.getCameras().length,t=b.getMicrophones().length;c.debug("Cameras: "+e+(b.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(b.hasMicrophonePermission()?"✔":"✖")),h.log(f.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){h.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===H.CALLED||e.state===H.ACCEPTED||this._state===Y.CLOSE||!this._participants[e.id]||(t===A.HUNGUP?this._setParticipantsStatus([e],J.HANGUP):this._setParticipantsStatus([e],J.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Ie.CAMERA,stopStream:!0}]),delete this._participants[e.id],T.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){c.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 o(this,null,function*(){c.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===H.ACCEPTED||r.state===H.CALLED)){c.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&me.fromSignaling(t.externalId,t.deviceIdx),mediaSettings:fe(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],J.WAITING),i?(r.state=H.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=H.CALLED,this._transport.allocate(r.id,!0),h.log(f.ADD_PARTICIPANT))})}_onRemoveParticipant(e){c.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=Za;i++){let r=I.compose(e,i),n=this._participants[r];n&&t.push(n)}if(!t.length){c.warn(`Participant [${e}] isn't in conversation`);return}if(this._transport)for(let i of t)this._transport.close(i.id);h.log(f.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new At(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(re.UNKNOWN)})}toggleScreenCapturing(e){return o(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(re.UNKNOWN)})}setVideoStream(e,t=!1){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return o(this,null,function*(){if(this._mediaSource)return h.log(f.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return h.log(f.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return o(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let n=typeof r.uid=="object"?r.uid:me.fromId(r.uid),s=me.toString(n);i[s]=r.priority}for(let r of Object.values(this._participants)){let n=me.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return o(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 o(this,null,function*(){if(e.length<1||!this._signaling.ready)return;c.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:me.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(n);if(!s){let M=me.toString(n);c.log(`Unknown participant external ID ${M}`);continue}let d=I.compose(s,n.deviceIdx),l=Qe({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),_=this._participants[d];_&&(_.lastRequestedLayouts[l]=r),B._isStopStreaming(r)?this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now()):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&p.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=B._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>p.videoTracksCount;){let r=i.next();if(r.done){c.error("Cannot accommodate all streaming requests: tracks available "+p.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)&&(c.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Mt(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Ie.STREAM||i.mediaType===Ie.SCREEN)?T.onRemoteLive(r.externalId,i.streamName,null):T.onRemoteStream(r.externalId,null),h.log(f.PAT_DEALLOCATED)):c.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return o(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,n]of Object.entries(t.errorCodeByParticipantId||{})){let s=Mt(r),d=this._participants[s.participantId];if(d){let l;typeof n!="number"?(c.warn(`Unexpected error code ${n} received for participant ${s.participantId}`),l=fr.UNKNOWN_ERROR):l=Sr(n),i.push({externalId:d.externalId,errorReason:l})}}if(i&&i.length)throw new ei("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]+Xa>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=B._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(B._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),e.keyFrame&&(t!==""&&(t+=":"),t+="kf"),t}_onParticipantSourcesUpdate(e){if(this._conversation){c.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){c.log("Promoted in waiting hall",!e.demote),e.demote?(c.log("Kicked from waiting hall"),this._close(new N(A.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return o(this,arguments,function*(e,t=0,i=[]){c.log(`Chat room updated: ${e}`);let n=[],s=[];i.length&&(i.forEach(d=>{if(d.externalId){let l=he.fromSignaling(d.externalId);n.push(l),this._api.cacheExternalId(d.id.id,l)}else s.push(I.decomposeId(d.id.id).id)}),s.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(s))),T.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var d,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||p.producerScreenTrack&&t.mediaType===Ie.SCREEN)return;let i=Qe(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){c.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),h.log(f.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let _=t.participantId,M=this._participants[_];if(!M){h.log(f.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${_}`);return}let k=this._streamByStreamId.get(n);if(!k){h.log(f.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${n}`);return}h.log(f.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let q=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(q===Ie.STREAM||q===Ie.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&T.onRemoteLive(M.externalId,e.participantStreamDescription.streamName,k);else{let j=(p.producerScreenTrack?null:M.secondStream)||k;T.onRemoteStream(M.externalId,j)}}else{c.debug(`Waiting for ${s} until stream ${n} for ${i} is switched`);let _=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,_)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Qe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Qe(i)))return i}else{let i={participantId:t,mediaType:Ie.CAMERA};if(this._streamIdByStreamDescription.has(Qe(i)))return i;let r={participantId:t,mediaType:Ie.SCREEN};if(this._streamIdByStreamDescription.has(Qe(r)))return r}return c.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?I.includesOneOf(this._conversation.roles,[et.ADMIN,et.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!I.includesOneOf(this._conversation.roles,[et.ADMIN,et.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return o(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return o(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return o(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=gr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return o(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Zr(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let s=n.participants||[],d=[],l=[],_=null;return s.length&&(s.forEach(M=>{if(M.externalId){let k=he.fromSignaling(M.externalId);d.push(k),this._api.cacheExternalId(M.id.id,k)}else l.push(I.decomposeId(M.id.id).id)}),l.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(l)),n.hasMore&&(_=Xr(s[s.length-1].id))),{participants:d,pageMarker:_,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return o(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return o(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 o(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return o(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 o(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 o(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return o(this,null,function*(){var d;let n={movieId:e,participantId:(d=this._conversation)==null?void 0:d.compositeUserId};(t||t===0)&&(n.gain=t),i&&(n.offset=i),typeof r!==void 0&&(n.pause=r);let s=yield this._signaling.updateMovie(n);if(s.error)throw new Error(s.error)})}removeMovie(e){return o(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 o(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},d=yield this._signaling.startStream(s);return d.error?Promise.reject(d.message):d})}stopStream(){return o(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return o(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return o(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return o(this,null,function*(){var r;if(e<p.videoMinWidth||t<p.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<p.videoMinWidth||i.effect.height<p.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");p.videoEffectMaxHeight=i.effect.height,p.videoEffectMaxWidth=i.effect.width}return p.videoMaxWidth=e,p.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return o(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t;!this._conversation||(c.debug("Local media stream changed",e.mediaSettings),T.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 o(this,null,function*(){var t;if(c.log("Screen sharing changed",e.track,e.mediaSettings),p.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;T.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){c.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state===Y.ACTIVE&&T.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){c.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state===Y.ACTIVE&&(p.participantStateMapped?T.onRemoteParticipantState(i.externalId,i.participantState):T.onRemoteParticipantState(i.externalId,I.mapLegacyParticipantState(i.participantState))))}_onSignalingNotification(e){switch(e.notification){case x.ACCEPTED_CALL:return this._onAcceptedCall(e);case x.HUNGUP:return this._onHungup(e);case x.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case x.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case x.CLOSED_CONVERSATION:return this._onClosedConversation(e);case x.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case x.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case x.RATE_CALL_DATA:return this._onNeedRate();case x.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case x.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case x.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case x.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case x.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case x.REGISTERED_PEER:return this._onPeerRegistered(e);case x.SWITCH_MICRO:return this._onMicSwitched(e);case x.CHAT_MESSAGE:return this._onChatMessage(e);case x.CUSTOM_DATA:return this._onCustomData(e);case x.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case x.RECORD_STOPPED:return this._onRecordInfo(null);case x.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case x.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case x.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case x.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case x.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case x.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case x.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return o(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let s=I.composeId(n),d=n.roles||[];if(s===this._conversation.compositeUserId){t=fe(n.mediaSettings),Et(this._conversation.roles,d)||this._onRolesChanged(s,d);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let _=fe(n.mediaSettings);br(_,l.mediaSettings)||this._changeRemoteMediaSettings(s,_);let M=I.mapParticipantState(n),k=l.participantState;I.isEqualParticipantState(M,k)||this._changeRemoteParticipantState(s,M),Et(d,l.roles)||this._onRolesChanged(l.id,d)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],A.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){c.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return o(this,null,function*(){let t=I.composeMessageId(e),i=I.getPeerIdString(e.peerId);if(c.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new N(A.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:fe(e.mediaSettings)}),r=this._participants[t]),r.state=H.ACCEPTED,r.mediaSettings=fe(e.mediaSettings),this._logWithMediaSettings(f.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Ge.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){c.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=I.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new N(e.reason));return}let i=this._participants[t];if(!i){c.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===A.REJECTED?H.REJECTED:H.HUNGUP,this._state!==Y.CLOSE&&this._removeParticipant(i,A.HUNGUP)}_onAddedParticipant(e){return o(this,null,function*(){var r,n;c.debug(`Participant added [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state!==H.HUNGUP&&i.state!==H.REJECTED){c.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&me.fromSignaling(e.participant.externalId,e.participant.deviceIdx),mediaSettings:fe(e.participant.mediaSettings),state:e.participant.state,participantState:I.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=H.CALLED,i.mediaSettings=fe((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=I.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],J.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 o(this,null,function*(){var r;c.debug(`Participant joined [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state===H.ACCEPTED){c.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&me.fromSignaling(e.participant.externalId,e.participant.deviceIdx),mediaSettings:fe(e.participant.mediaSettings),state:e.participant.state,participantState:I.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Ge.OUTGOING&&(this._state===Y.IDLE||this._state===Y.PROCESSING)&&(this._state=Y.ACTIVE,this._changeFeatureSet()),i.state=H.ACCEPTED,i.mediaSettings=fe(e.mediaSettings),i.participantState=I.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],J.CONNECTED):this._setParticipantsStatus([i],J.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=I.composeMessageId(e);this._changeRemoteMediaSettings(t,fe(e.mediaSettings))}_onParticipantStateChanged(e){let t=I.composeMessageId(e);this._changeRemoteParticipantState(t,I.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),T.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=fe(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),p.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=zi(this._serverSettings,t),this._signalingServerSettings=Qr(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),s={camera:Object.assign({},t,{maxBitrateK:r,maxDimension:n}),screenSharing:null};this._serverSettings=zi(this._serverSettings,s),c.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=I.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return o(this,null,function*(){T.onDeviceSwitched(ce.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return o(this,null,function*(){let t=I.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),T.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return o(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=I.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),T.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return o(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getParticipantId(e.initiator);T.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else T.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!Et(this._conversation.roles,t)){c.debug(`Local roles changed: ${t}`),this._conversation.roles=t,T.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!Et(i.roles,t)&&(c.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,T.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){c.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let d=this._participants[e.participantId];d&&(c.debug(`Mute states for participant [${e.participantId}] changed`,i),T.onMuteStates(i,r,n,e.muteAll,e.unmute,d.externalId,s==null?void 0:s.externalId));return}I.isObjectsEquals(this._conversation.muteStates,i)&&I.isArraysEquals(this._conversation.unmuteOptions,r)&&!n.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(n,e.muteAll,e.unmute,t,s)))})}_processMuteState(){return o(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==H.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),d=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),_=Object.entries(s);for(let[M,k]of _)if(!(k!==He.MUTE&&k!==He.MUTE_PERMANENT)&&(this._isCallAdmin()&&k===He.MUTE_PERMANENT&&(s[M]=He.MUTE),!(!e.includes(M)||i)))switch(M){case ce.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(T.onDeviceSwitched(ce.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case ce.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(T.onDeviceSwitched(ce.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case ce.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(T.onDeviceSwitched(ce.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}T.onMuteStates(s,d,e,t,i,null,n==null?void 0:n.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?T.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&T.onLocalPin(!0)),this._participants[e]?T.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&T.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!_r(this._conversation.options,e)&&(this._conversation.options=e,T.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let n;if(i===this._conversation.compositeUserId||i==="")n=this._conversation.networkRating;else if(this._participants[i])n=this._participants[i].networkRating;else continue;if(n!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,T.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;c.log("Received network status update: ",e),T.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(p.producerScreenTrack){T.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,p.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){c.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)){c.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(n);if(!s){h.log(f.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${n}`);return}T.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&T.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===W.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state===Y.ACTIVE,t=this._conversation.features.includes(mr.ADD_PARTICIPANT);T.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&T.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}T.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(T.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){c.debug(`Transport state has changed: ${t}`,e);let i;if(t===w.CONNECTED?i=J.CONNECTED:t===w.CONNECTING||t===w.OPENED?i=J.CONNECTING:t===w.RECONNECTING&&(i=J.RECONNECT),!i)return;let r=e.reduce((n,s)=>{if(s in this._participants){let d=this._participants[s];n.push(d),t===w.CONNECTED&&(d.remoteStream||(d.mediaSettings&&this._changeRemoteMediaSettings(s,d.mediaSettings),this._changeRemoteParticipantState(s,d.participantState)),this._updateDisplayLayoutFromCache(s))}else c.warn(`Participant [${s}] isn't in conversation`);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){c.debug(`Local transport state has changed: ${e}`),e===w.CONNECTED&&T.onLocalStatus(J.CONNECTED),e===w.CONNECTING&&T.onLocalStatus(J.CONNECTING),e===w.RECONNECTING&&T.onLocalStatus(J.RECONNECT),e===w.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(A.FAILED)),this._close(new N(A.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(Me.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(Me.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))c.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{c.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(c.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],J.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(T.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===$.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;T.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),p.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(c.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case $.audio:this._removeAudioTrack(e,t,i);break;case $.video:case $.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,J.RECONNECT),i.length&&this._setParticipantsStatus(i,J.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let s=this._participants[n];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let s=this._participants[n];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,J.RECONNECT),r.length&&this._setParticipantsStatus(r,J.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!b.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&&(c.debug("Toggle join availability",{available:t,chatId:e}),T.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==W.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,s)=>(s.status!==t&&(s.status=t,p.batchParticipantsOnStart?n.push(s.externalId):T.onParticipantStatus(s.externalId,t,i)),n),[]);!r.length||p.batchParticipantsOnStart&&T.onRemoteStatus(r,t,i)}},L=B;L._delayedHangup=!1;var ei=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,ei.prototype),this.participantErrors=t}};function ia(){if(!p.apiAppId||!p.apiKey)throw new N(re.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function rr(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=aa(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${p.apiEnv.api}fb.do`,r)}function ra(i){return o(this,arguments,function*(a,e={},t=!1){let r=aa(a,e,t);return en(r)})}function en(a){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${p.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 aa(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=p.apiKey),t||(ie.sessionKey?e.session_key=ie.sessionKey:ie.accessToken&&(e.access_token=ie.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 Ze;(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"})(Ze||(Ze={}));var ut;(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"})(ut||(ut={}));var tn=10,rn=700,an=3e3,ti=class extends gt{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return o(this,arguments,function*(e,t={},i=!1){let n=s=>o(this,null,function*(){try{return yield ra(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<tn))return yield I.delay(Math.min(s*rn,an)),n(s);throw c.warn(e,"error",d),d}});return n(0)})}_call(r){return o(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){c.warn("Api call error",n);let s=re.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=A.SERVICE_DISABLED;break;case 1102:s=A.CALLEE_IS_OFFLINE;break;case 1103:s=A.NOT_FRIENDS;break;case 1104:case 1106:s=A.EXTERNAL_API_ERROR;break}throw new N(s,{message:n.error_msg,code:n.error_code})}})}userId(e){return o(this,null,function*(){let t=I.decomposeId(e).id;return ie.isEmpty()?he.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),he.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return o(this,null,function*(){ie.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return o(this,null,function*(){if(!this._uuid){let t=We.get("uuid");t||(t=I.uuid(),We.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:p.appVersion,client_type:"SDK_JS"}};return p.authToken&&(e.session_data.auth_token=p.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),ie.sessionKey=t.session_key,ie.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&T.onTokenExpired(),new N(re.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${p.appName}:${p.sdkVersion}`,platform:p.platform,items:e})};rr("log.externalLog",t)}init(){ia()}joinConversation(e,t=!1,i){return o(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:p.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return o(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1};return t&&(r.payload=t),p.domain&&(r.domainId=p.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,n="",s=!1,d=!1){return o(this,null,function*(){let l={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case Ue.USER:l.uids=t.join(",");break;case Ue.GROUP:l.gid=t[0];break;case Ue.CHAT:l.chatId=t[0];break}return s&&(l.createJoinLink=!0),n&&(l.payload=n),p.domain&&(l.domainId=p.domain),d&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return o(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return o(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return o(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return o(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 o(this,null,function*(){let i={joinLink:e,isVideo:t,protocolVersion:p.protocolVersion};return p.anonymToken&&(i.anonymToken=p.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=he.fromIds(e),i=[],r={methods:[]},n=[],s=Object.keys(this._externalUidsCache),d=Object.values(this._externalUidsCache);for(let _ of t){let M=he.toString(_),k=d.indexOf(M);k>-1?i.push(Number(s[k])):(n.push(M),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:_.id,anonym:_.type===Ce.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((_,M)=>{if(_.ok){let k=Number(_.ok.ok_id);this._externalUidsCache[k]=n[M],i.push(k)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(he.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(he.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=he.toString(e),n=i.indexOf(r);return n>-1?I.composeUserId(t[n],ee.USER):null}cacheExternalId(e,t){let i=I.decomposeId(e).id;this._externalUidsCache[i]=he.toString(t)}getConversationParams(e){return o(this,null,function*(){let t={};return p.anonymToken&&(t.anonymToken=p.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:A.HUNGUP};p.anonymToken&&(t.anonymToken=p.anonymToken),rr("vchat.hangupConversation",t)}removeHistoryRecords(e){return o(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return o(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]=he.fromIdToString(n,Ce.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=he.fromIdToString(n,Ce.ANONYM);return t}catch(i){return t}})}getTokenForAnonym(e,t){return o(this,null,function*(){let i={id:e};return t&&(i.application_key=t),(yield this._callUnsafe("auth.getTokenForAnonym",i,!0)).token})}call(i){return o(this,arguments,function*(e,t={}){return this._call(e,t)})}};var ar;(function(m){m.RECOVER="recover",m.ACCEPT_CALL="accept-call",m.ADD_PARTICIPANT="add-participant",m.REMOVE_PARTICIPANT="remove-participant",m.HANGUP="hangup",m.TRANSMIT_DATA="transmit-data",m.ACCEPT_PRODUCER="accept-producer",m.ALLOCATE_CONSUMER="allocate-consumer",m.CHANGE_MEDIA_SETTINGS="change-media-settings",m.CHANGE_PARTICIPANT_STATE="change-participant-state",m.CHANGE_STREAM_PRIORITIES="change-streams-priorities",m.UPDATE_DISPLAY_LAYOUT="update-display-layout",m.REPORT_PERF_STAT="report-perf-stat",m.RECORD_START="record-start",m.RECORD_STOP="record-stop",m.RECORD_SET_ROLE="record-set-role",m.RECORD_GET_STATUS="record-get-status",m.SWITCH_MICRO="switch-micro",m.SWITCH_TOPOLOGY="switch-topology",m.REQUEST_REALLOC="request-realloc",m.CHAT_MESSAGE="chat-message",m.CHAT_HISTORY="chat-history",m.CUSTOM_DATA="custom-data",m.GRANT_ROLES="grant-roles",m.MUTE_PARTICIPANT="mute-participant",m.PIN_PARTICIPANT="pin-participant",m.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",m.CHANGE_OPTIONS="change-options",m.GET_WAITING_HALL="get-waiting-hall",m.PROMOTE_PARTICIPANT="promote-participant",m.REQUEST_TEST_MODE="request-test-mode",m.ADD_MOVIE="add-movie",m.UPDATE_MOVIE="update-movie",m.REMOVE_MOVIE="remove-movie"})(ar||(ar={}));var G=ar;var na="open",sa=[()=>p.producerScreenTrack,()=>p.videoTracksCount>0,()=>!0,()=>p.filteredMessages,()=>p.consumerScreenTrack,()=>!0],nn=10,Pe=class extends St{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="+p.platform+"&appVersion="+p.appVersion+"&version="+p.protocolVersion+"&device="+p.device+"&capabilities="+Pe._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null}static _getCapabilityFlags(){let e=0;for(let t=0;t<sa.length;t++)sa[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 o(this,null,function*(){return this.postfix+=`&clientType=${p.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){h.log(f.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 o(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=I.decomposeParticipantId(t.participantId),s=I.decomposeId(n.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),n.deviceIdx&&(t.deviceIdx=n.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return o(this,arguments,function*(e,t={},i=0){let n=s=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===na&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){h.log(f.SOCKET_ACTION,"not_opened"),c.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(h.log(f.SOCKET_ACTION,"invalid_state"),c.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,d)=>{let l=(M,k=!1)=>{!i||k?d(M):(c.debug("Resending a signaling message",e,_.sequence),i--,n(_))},_={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};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 o(this,null,function*(){return this._send(G.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return o(this,null,function*(){return this._send(G.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return o(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(G.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(G.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},nn)})}changeParticipantState(e){return o(this,null,function*(){return this._send(G.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(G.ADD_PARTICIPANT,hr({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(G.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return o(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(G.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(G.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(G.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(G.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return o(this,null,function*(){return this._send(G.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(G.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(G.REMOVE_MOVIE,e)})}startStream(e){return o(this,null,function*(){return this._send(G.RECORD_START,e)})}stopStream(){return o(this,null,function*(){return this._send(G.RECORD_STOP)})}recordSetRole(e,t){return o(this,null,function*(){return this._send(G.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return o(this,null,function*(){return this._send(G.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(G.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(G.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(G.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(G.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(G.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(G.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return o(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(G.GRANT_ROLES,r)})}muteParticipant(e,t,i){return o(this,null,function*(){return this._sendRaw(G.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return o(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(G.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(G.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(G.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return o(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 o(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===Be.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),c.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(){c.debug("Socket opened"),h.log(f.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){h.log(f.SOCKET_ACTION,"parse_error"),c.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(c.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(ge.RECONNECT,e),e.conversation.topology&&this._triggerEvent(ge.NOTIFICATION,{type:"notification",notification:x.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(ge.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(h.log(f.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(h.log(f.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new N(A.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(ge.NOTIFICATION,{notification:x.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new N(re.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(h.log(f.SOCKET_ACTION,"unknown_message"),c.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(ge.FAILED,e)}_onError(e){h.log(f.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){h.log(f.SOCKET_ACTION,"closed"),c.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Pe.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(Pe.RECONNECT_MAX_DELAY,Pe.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),h.log(f.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Be.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],h.log(f.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Pe.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),n=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==na){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}Pe._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Pe.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(n))}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Pe.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(n))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new N(re.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Pe.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{c.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Be.RETRY)},Pe.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Ne=Pe;Ne.RECONNECT_DELAY=p.signalingReconnectDelay,Ne.RECONNECT_MAX_DELAY=p.signalingReconnectMaxDelay,Ne.RECONNECT_MAX_COUNT=p.signalingReconnectMaxCount,Ne.WAIT_CONNECTION_DELAY=p.waitConnectionDelay,Ne.WAIT_RESPONSE_DELAY=p.waitResponseDelay,Ne.WAIT_MESSAGE_DELAY=p.waitMessageDelay;var nr;(function(t){t.KING="KING",t.PAWN="PAWN"})(nr||(nr={}));var sn=nr;var ht,ne,xt=null,Ou={getCameras:b.getCameras,getMicrophones:b.getMicrophones,getOutput:b.getOutput,hasCamera:b.hasCamera,hasMicrophone:b.hasMicrophone,getSavedCamera:b.getSavedCamera,getSavedMicrophone:b.getSavedMicrophone,getSavedOutput:b.getSavedOutput,hasCameraPermission:b.hasCameraPermission,hasMicrophonePermission:b.hasMicrophonePermission,hasPermissions:b.hasPermissions,getUserMedia:b.getUserMedia,getUserVideo:b.getUserVideo,getUserAudio:b.getUserAudio,saveDeviceId:b.saveDeviceId,isBrowserSupported:b.isBrowserSupported,isScreenCapturingSupported:b.isScreenCapturingSupported,os:b.os,isMobile:b.isMobile,browserName:b.browserName,browserVersion:b.browserVersion,baseChromeVersion:b.baseChromeVersion,getAudioContext:b.getAudioContext};function on(a){ne=a}function cn(a){ht=a}function ku(a){xt=a}function wu(a){p.videoEffects=a}function xu(a){return o(this,null,function*(){if(p.set(a),b.browserName()==="Sferum"&&(p.platform=`SFERUM:${b.browserVersion()}`),ne||on(new ti),ht||cn(()=>new Ne),p.debug&&(oa.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${p.sdkVersion}`,a),yield b.init(),!b.isBrowserSupported())throw new N(re.UNSUPPORTED);ne.init()})}function Nu(n){return o(this,arguments,function*(a,e=[ce.AUDIO],t="",i=!1,r=!1){let s=[],d=[];if(Array.isArray(a)?s=a.length?a:[]:a&&(s=[a]),s.length&&(d=yield ne.getOkIdsByExternalIds(s),!d.length))throw new N(A.CALLEE_IS_OFFLINE);return dn(d,Ue.USER,e,t,i,r)})}function dn(s){return o(this,arguments,function*(a,e=Ue.USER,t,i="",r=!1,n=!1){if(L.current())throw c.error("There is already active call"),new N(A.FAILED);return new L(ne,ht(),xt).onStart(a,e,t,i,r,n)})}function Lu(a){return o(this,null,function*(){return pn(a)})}function pn(i){return o(this,arguments,function*(a,e=ee.USER,t){if(a===L.id())throw new Error("Push has already been processed");return new L(ne,ht(),xt).onPush(a,e,t)})}function Uu(a,e){return o(this,null,function*(){return ne.getTokenForAnonym(a,e)})}function Bu(t){return o(this,arguments,function*(a,e={}){return ne.call(a,e)})}function Vu(a){return o(this,null,function*(){return a&&(p.authToken=a),ne.authorize()})}function Fu(){return o(this,arguments,function*(a=[ce.AUDIO]){let e=L.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function Gu(){return o(this,null,function*(){let a=L.current();if(a)return a.decline()})}function Hu(t){return o(this,arguments,function*(a,e=[ce.AUDIO]){return ln(a,e)})}function ln(a,e,t){return o(this,null,function*(){if(L.current())throw c.error("There is already active call"),new N(A.FAILED);return new L(ne,ht(),xt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function Wu(i){return o(this,arguments,function*(a,e=[ce.AUDIO],t){if(L.current())throw c.error("There is already active call"),new N(A.FAILED);return t&&(p.anonymToken=t),new L(ne,ht(),xt).onJoin({joinLink:a,mediaOptions:e})})}function ju(){return o(this,null,function*(){let a=L.current();if(a)return a.hangup();L.hangupAfterInit()})}function Ku(a,e){return o(this,null,function*(){let t=yield ne.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return un(t[0],e)})}function un(a,e){return o(this,null,function*(){let t=L.current();t&&(yield t.addParticipant(I.composeUserId(a,ee.USER),e))})}function $u(a,e=!1){return o(this,null,function*(){let t=yield ne.getOkIdsByExternalIds([a]);return hn(t[0],e)})}function hn(a,e=!1){return o(this,null,function*(){let t=L.current();t&&(yield t.removeParticipant(I.composeUserId(a,ee.USER),e))})}function qu(a,e){return o(this,null,function*(){let t=yield b.saveDeviceId(a,e),i=L.current();return t&&i?i.changeDevice(a):Promise.reject()})}function Ju(a){return o(this,null,function*(){let e=L.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function Yu(a,e=!1){return o(this,null,function*(){let t=L.current();t&&(yield t.setVideoStream(a,e))})}function zu(a){return o(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalVideo(a))})}function Qu(a){return o(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalAudio(a))})}function Xu(a,e,t){return o(this,null,function*(){let i=L.current();if(i)return i.setLocalResolution(a,e,t)})}function Zu(a){return o(this,null,function*(){let e=L.current();e&&(yield e.changePriorities(a))})}function eh(a){return o(this,null,function*(){let e=L.current();e&&(yield e.changeParticipantState(a))})}function th(a){return o(this,null,function*(){let e=L.current();e&&(yield e.updateDisplayLayout(a))})}function ih(a,e,t=!1){return o(this,null,function*(){let i=yield ne.getOkIdsByExternalIds([a]);return mn(i[0],e,t)})}function mn(a,e,t=!1){return o(this,null,function*(){let i=L.current();i&&(yield i.grantRoles(I.composeUserId(a,ee.USER),e,t))})}function rh(){return o(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield ne.getOkIdsByExternalIds([a]))[0]),_n(i,e,t,me.getDeviceIdx(a))})}function _n(){return o(this,arguments,function*(a=null,e,t=[],i=0){let r=L.current();if(r){let n=a?I.composeParticipantId(a,ee.USER,i):null;yield r.muteParticipant(n,e,t)}})}function ah(a,e=!1){return o(this,null,function*(){let t=yield ne.getOkIdsByExternalIds([a]);return gn(t[0],e,me.getDeviceIdx(a))})}function gn(a,e=!1,t=0){return o(this,null,function*(){let i=L.current();i&&(yield i.pinParticipant(I.composeParticipantId(a,ee.USER,t),e))})}function nh(a){return o(this,null,function*(){let e=L.current();e&&(yield e.updateMediaModifiers(a))})}function sh(a){return o(this,null,function*(){let e=L.current();e&&(yield e.changeOptions(a))})}function oh(a,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield ne.getOkIdsByExternalIds([e]))[0]),fn(a,t)})}function fn(a,e=null){return o(this,null,function*(){let t=L.current();if(t){let i=e?I.composeUserId(e,ee.USER):null;yield t.chatMessage(a,i)}})}function ch(a=10){return o(this,null,function*(){let e=L.current();if(e)return e.chatHistory(a)})}function dh(a,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield ne.getOkIdsByExternalIds([e]))[0]),Sn(a,t,me.getDeviceIdx(e))})}function Sn(a,e=null,t=0){return o(this,null,function*(){let i=L.current();if(i){let r=e?I.composeParticipantId(e,ee.USER,t):null;yield i.customData(a,r)}})}function ph(a="",e=!1){return o(this,null,function*(){return(yield ne.createConversation(I.uuid(),a,e)).join_link})}function lh(){return o(this,null,function*(){let a=L.current();return a?a.createJoinLink():Promise.reject()})}function uh(){return o(this,null,function*(){let a=L.current();return a?a.removeJoinLink():Promise.reject()})}function hh(a,e){return o(this,null,function*(){return ne.getAnonymTokenByLink(a,e)})}function mh(a){let e=L.current();e&&e.setVolume(a)}function _h(a){p.forceRelayPolicy=a}function gh(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return o(this,null,function*(){let n=L.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function fh(){return o(this,null,function*(){let a=L.current();return a?a.stopStream():Promise.reject()})}function Sh(a,e){return o(this,null,function*(){let t=L.current();if(t){let i=yield ne.getOkIdsByExternalIds([a]),r=me.getDeviceIdx(a);return t.recordSetRole(I.composeParticipantId(i[0],ee.USER,r),e)}return Promise.reject()})}function vh(){return o(this,null,function*(){let a=L.current();return a?a.getStreamInfo():Promise.reject()})}function Eh(a){return o(this,null,function*(){let e=L.current();return e?e.addMovie(a):Promise.reject()})}function Ih(a,e,t,i){return o(this,null,function*(){let r=L.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function Th(a){return o(this,null,function*(){let e=L.current();return e?e.removeMovie(a):Promise.reject()})}function Ch(a){p.statisticsInterval=a;let e=L.current();if(e)return e.updateStatisticsInterval()}function Rh(a){oa.disableLog(!a),c.toggle(a)}function Ph(a,...e){!p.debugLog||c.send(a,"[external]",...e)}function yh(a){return o(this,null,function*(){let e=L.current();if(e)return e.videoEffect(a)})}function bh(a){return o(this,null,function*(){let e=L.current();e&&(yield e.setAudioStream(a))})}function Mh(a=null,e,t=!1){return o(this,null,function*(){let i=L.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(a,e,t)})}function Ah(a,e=!1){return o(this,null,function*(){let t=L.current();if(!t)throw new Error("Conversation not found");let i=yield ne.getOkIdsByExternalIds([a]);return t.promoteParticipant(I.composeUserId(i[0],ee.USER),e)})}function Dh(a){return o(this,null,function*(){yield ne.removeHistoryRecords(a)})}export{ti as Api,gt as BaseApi,ft as BaseLogger,St as BaseSignaling,Ge as CallDirection,Ue as CallType,ci as ChatRoomEventType,li as ConversationOption,de as DebugMessageType,Ce as ExternalIdType,Wi as FacingMode,re as FatalError,N as HangupReason,A as HangupType,ce as MediaOption,$ as MediaTrackKind,Ie as MediaType,He as MuteState,H as ParticipantState,J as ParticipantStatus,sn as RecordRole,Ne as Signaling,G as SignalingCommandType,Be as SignalingConnectionType,x as SignalingNotification,et as UserRole,ee as UserType,I as Utils,Fu as acceptCall,Eh as addMovie,Ku as addParticipant,un as addParticipantInternal,Bu as apiCall,Vu as authorize,Ou as browser,dn as callInternal,Nu as callTo,Ju as captureScreen,sh as changeConversationOptions,qu as changeDevice,eh as changeParticipantState,Zu as changePriorities,yh as changeVideoEffect,ch as chatHistory,oh as chatMessage,fn as chatMessageInternal,lh as createJoinLink,dh as customData,Sn as customDataInternal,Rh as debug,Ph as debugMessage,Gu as declineCall,_h as forceRelayPolicy,hh as getAnonymTokenByLink,vh as getStreamInfo,Uu as getTokenForAnonym,Mh as getWaitingHall,ih as grantRoles,mn as grantRolesInternal,ju as hangup,xu as init,Hu as joinCall,Wu as joinCallByLink,ln as joinCallInternal,rh as muteParticipant,_n as muteParticipantInternal,ah as pinParticipant,gn as pinParticipantInternal,Lu as processPush,pn as processPushInternal,Ah as promoteParticipant,Sh as recordSetRole,Dh as removeHistoryRecords,uh as removeJoinLink,Th as removeMovie,$u as removeParticipant,hn as removeParticipantInternal,on as setApi,bh as setAudioStream,Xu as setLocalResolution,ku as setLogger,nh as setMediaModifiers,cn as setSignalingFactory,Ch as setStatisticsInterval,wu as setVideoEffects,Yu as setVideoStream,mh as setVolume,ph as startConversation,gh as startStream,fh as stopStream,Qu as toggleLocalAudio,zu as toggleLocalVideo,th as updateDisplayLayout,Ih as updateMovie};
|