@vkontakte/calls-sdk 2.7.2-beta.8 → 2.7.2-dev.d37e896.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/calls-sdk.cjs.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
- * @vkontakte/calls-sdk v2.7.2-beta.8
3
- * Mon, 03 Apr 2023 17:32:45 GMT
2
+ * @vkontakte/calls-sdk v2.7.2-dev.d37e896.0
3
+ * Mon, 03 Apr 2023 20:05:43 GMT
4
4
  * https://st.mycdn.me/static/callssdk/2-7-2/doc/
5
5
  */
6
6
 
7
- "use strict";var nn=Object.create;var jt=Object.defineProperty,sn=Object.defineProperties,on=Object.getOwnPropertyDescriptor,cn=Object.getOwnPropertyDescriptors,dn=Object.getOwnPropertyNames,kr=Object.getOwnPropertySymbols,ln=Object.getPrototypeOf,wr=Object.prototype.hasOwnProperty,pn=Object.prototype.propertyIsEnumerable;var xr=Math.pow,Or=(n,r,e)=>r in n?jt(n,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[r]=e,Re=(n,r)=>{for(var e in r||(r={}))wr.call(r,e)&&Or(n,e,r[e]);if(kr)for(var e of kr(r))pn.call(r,e)&&Or(n,e,r[e]);return n},ze=(n,r)=>sn(n,cn(r));var un=(n,r)=>{for(var e in r)jt(n,e,{get:r[e],enumerable:!0})},Lr=(n,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of dn(r))!wr.call(n,i)&&i!==e&&jt(n,i,{get:()=>r[i],enumerable:!(t=on(r,i))||t.enumerable});return n};var si=(n,r,e)=>(e=n!=null?nn(ln(n)):{},Lr(r||!n||!n.__esModule?jt(e,"default",{value:n,enumerable:!0}):e,n)),mn=n=>Lr(jt({},"__esModule",{value:!0}),n);var c=(n,r,e)=>new Promise((t,i)=>{var a=l=>{try{o(e.next(l))}catch(u){i(u)}},s=l=>{try{o(e.throw(l))}catch(u){i(u)}},o=l=>l.done?t(l.value):Promise.resolve(l.value).then(a,s);o((e=e.apply(n,r)).next())});var Wo={};un(Wo,{Api:()=>Ut,ArrayDequeue:()=>Hi,BaseApi:()=>st,BaseLogger:()=>ot,BaseSignaling:()=>ct,CallDirection:()=>Ke,CallType:()=>Be,ChatRoomEventType:()=>oi,ConversationFeature:()=>ci,ConversationOption:()=>di,DebugMessageType:()=>vr,ExternalIdType:()=>Ai,FacingMode:()=>qe,FatalError:()=>re,HangupReason:()=>F,HangupType:()=>w,MediaOption:()=>oe,MediaTrackKind:()=>xe,MediaType:()=>Dt,MuteState:()=>Pe,ParticipantState:()=>K,ParticipantStatus:()=>Mi,RecordRole:()=>Ha,RoomsEventType:()=>Et,Signaling:()=>Ae,SignalingCommandType:()=>L,SignalingConnectionType:()=>Fe,SignalingNotification:()=>x,TransportTopology:()=>rt,UserRole:()=>$e,UserType:()=>z,acceptCall:()=>Bs,activateRooms:()=>Co,addMovie:()=>Eo,addParticipant:()=>Gs,addParticipantInternal:()=>Ja,authorize:()=>Us,browser:()=>As,callInternal:()=>Ka,callTo:()=>Ls,captureScreen:()=>$s,captureVmoji:()=>qs,changeConversationOptions:()=>no,changeDevice:()=>Ks,changeParticipantState:()=>Zs,changePriorities:()=>Xs,changeVideoEffect:()=>Do,chatHistory:()=>oo,chatMessage:()=>so,chatMessageInternal:()=>Za,createJoinLink:()=>po,customData:()=>co,customDataInternal:()=>en,debug:()=>Mo,debugMessage:()=>Ao,declineCall:()=>Fs,enableFeatureForRoles:()=>Bo,feedback:()=>Uo,forceRelayPolicy:()=>_o,getAnonymTokenByLink:()=>mo,getParticipantListChunk:()=>Lo,getParticipants:()=>No,getStreamInfo:()=>vo,getWaitingHall:()=>wo,grantRoles:()=>to,grantRolesInternal:()=>Ya,hangup:()=>Hs,init:()=>xs,joinCall:()=>Vs,joinCallByLink:()=>js,joinCallInternal:()=>qa,muteParticipant:()=>io,muteParticipantInternal:()=>Qa,pinParticipant:()=>ro,pinParticipantInternal:()=>Xa,processPush:()=>Ns,processPushInternal:()=>$a,promoteParticipant:()=>xo,recordSetRole:()=>So,removeHistoryRecords:()=>Fo,removeJoinLink:()=>uo,removeMovie:()=>To,removeParticipant:()=>Ws,removeParticipantInternal:()=>za,removeRooms:()=>yo,requestAsr:()=>Ho,setApi:()=>Ga,setAudioStream:()=>ko,setLocalResolution:()=>Qs,setLogger:()=>ks,setMediaModifiers:()=>ao,setSignalingFactory:()=>Wa,setStatisticsInterval:()=>bo,setVideoEffects:()=>Os,setVideoStream:()=>Js,setVmoji:()=>ws,setVmojiSvg:()=>Oo,setVolume:()=>ho,startAsr:()=>Vo,startConversation:()=>lo,startStream:()=>go,stopAsr:()=>jo,stopStream:()=>fo,switchRoom:()=>Po,toggleLocalAudio:()=>Ys,toggleLocalVideo:()=>zs,updateDisplayLayout:()=>eo,updateMovie:()=>Io,updateRooms:()=>Ro,utils:()=>Ds,version:()=>Go});module.exports=mn(Wo);var Pr=si(require("webrtc-adapter"));var st=class{createJoinLink(r){return c(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(r){return c(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(r,e){return c(this,null,function*(){return""})}log(r){}prepareUserIds(r){return c(this,null,function*(){})}getCachedOkIdByExternalId(r){return null}cacheExternalId(r,e){}hangupConversation(r){}removeHistoryRecords(r){return c(this,null,function*(){})}cleanup(){}};var ot=class{log(r,e,t=!1){}destroy(){}};var ie=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(r,...e){if(this._handlers.hasOwnProperty(r))for(let t of this._handlers[r])t.apply(this,e)}addEventListener(r,e){if(typeof e!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(r)||(this._handlers[r]=[]),this._handlers[r].push(e),{dispose:this.removeEventListener.bind(this,r,e)}}removeEventListener(r,e){if(!this._handlers.hasOwnProperty(r))return;e||delete this._handlers[r];let t=this._handlers[r].indexOf(e);t>=0&&this._handlers[r].splice(t,1)}subscribe(r,e,t){let i=r.addEventListener(e,t);this._listeners.push(i)}unsubscribe(){this._listeners.forEach(r=>{r.dispose()})}};var ct=class extends ie{get ready(){return!0}setParticipantIdRegistry(r){}requestRealloc(){}setEndpoint(r){}setConversationId(r){}readyToSend(){}cleanup(){}requestTestMode(r,e){}getNextCommandSequenceNumber(){return 0}};var Nr=(t=>(t.INCOMING="INCOMING",t.OUTGOING="OUTGOING",t.JOINING="JOINING",t))(Nr||{}),Ke=Nr;var Ur=(t=>(t.USER="USER",t.GROUP="GROUP",t.CHAT="CHAT",t))(Ur||{}),Be=Ur;var Br=(e=>(e.ATTENDEE="ATTENDEE",e.HAND_UP="HAND_UP",e))(Br||{}),oi=Br;var Fr=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t.MOVIE_SHARE="MOVIE_SHARE",t))(Fr||{}),ci=Fr;var Vr=(a=>(a.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",a.AUDIENCE_MODE="AUDIENCE_MODE",a.WAITING_HALL="WAITING_HALL",a.ASR="ASR",a.FEEDBACK="FEEDBACK",a))(Vr||{}),di=Vr;function jr(n,r){if(n.length!==r.length)return!1;for(let e of n)if(!r.includes(e))return!1;return!0}function Hr(n,r){let e=new Set(n);for(let[t,i]of Object.entries(r))i?e.add(t):e.delete(t);return Array.from(e)}var Gr=(A=>(A.CAMERA_PERMISSION="camera",A.MIC_PERMISSION="mic",A.CAMERA_ACCESS="cameralock",A.MIC_ACCESS="miclock",A.MIC_NOT_FOUND="nomic",A.SCREEN_PERMISSION="screenpermission",A.SCREEN_ACCESS="screenlock",A.CONNECTION="connection",A.NETWORK="network",A.UNKNOWN="unknown",A.UNSUPPORTED="unsupported",A.SIGNALING_FAILED="signalingfailed",A.API="api",A.AUTH="auth",A))(Gr||{}),re=Gr;var Wr=(Q=>(Q.CANCELED="CANCELED",Q.REJECTED="REJECTED",Q.REMOVED="REMOVED",Q.HUNGUP="HUNGUP",Q.MISSED="MISSED",Q.BUSY="BUSY",Q.FAILED="FAILED",Q.NETWORK_ERROR="NETWORK_ERROR",Q.KILLED="KILLED",Q.BANNED="BANNED",Q.HAS_ACTIVE_CALL="HAS_ACTIVE_CALL",Q.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",Q.NOT_FRIENDS="NOT_FRIENDS",Q.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",Q.CALLER_IS_REJECTED="CALLER_IS_REJECTED",Q.UNKNOWN_ERROR="UNKNOWN_ERROR",Q.UNSUPPORTED="UNSUPPORTED",Q.OLD_VERSION="OLD_VERSION",Q.SERVICE_DISABLED="SERVICE_DISABLED",Q.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",Q.SOCKET_CLOSED="SOCKET_CLOSED",Q.ENDED="ENDED",Q.KILLED_WITHOUT_DELETE="KILLED_WITHOUT_DELETE",Q.ANOTHER_DEVICE="ANOTHER_DEVICE",Q))(Wr||{}),w=Wr;var Kr=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SCREEN_SHARING="SCREEN_SHARING",s.MOVIE_SHARING="MOVIE_SHARING",s.AUDIO_SHARING="AUDIO_SHARING",s.ANIMOJI="ANIMOJI",s))(Kr||{}),oe=Kr;var $r=(t=>(t.UNMUTE="UNMUTE",t.MUTE="MUTE",t.MUTE_PERMANENT="MUTE_PERMANENT",t))($r||{}),Pe=$r;var qr=(i=>(i.CALLED="CALLED",i.ACCEPTED="ACCEPTED",i.REJECTED="REJECTED",i.HUNGUP="HUNGUP",i))(qr||{}),K=qr;var Jr=(t=>(t.UPDATE="UPDATE",t.REMOVE="REMOVE",t.ACTIVATE="ACTIVATE",t))(Jr||{}),Et=Jr;var zr=(i=>(i.START="start",i.ACCEPT="accept",i.JOIN="join",i.RETRY="retry",i))(zr||{}),Fe=zr;var Yr=(t=>(t.NOTIFICATION="NOTIFICATION",t.FAILED="FAILED",t.RECONNECT="RECONNECT",t))(Yr||{}),Ee=Yr;var Qr=(B=>(B.TRANSMITTED_DATA="transmitted-data",B.ACCEPTED_CALL="accepted-call",B.HUNGUP="hungup",B.PARTICIPANT_ADDED="participant-added",B.PARTICIPANT_JOINED="participant-joined",B.CLOSED_CONVERSATION="closed-conversation",B.MEDIA_SETTINGS_CHANGED="media-settings-changed",B.PARTICIPANT_STATE_CHANGED="participant-state-changed",B.RATE_CALL_DATA="rate-call-data",B.FEATURE_SET_CHANGED="feature-set-changed",B.TOPOLOGY_CHANGED="topology-changed",B.PRODUCER_UPDATED="producer-updated",B.CONSUMER_ANSWERED="consumer-answered",B.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",B.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",B.SETTINGS_UPDATE="settings-update",B.VIDEO_QUALITY_UPDATE="video-quality-update",B.REGISTERED_PEER="registered-peer",B.SWITCH_MICRO="switch-micro",B.RECORD_STARTED="record-started",B.RECORD_STOPPED="record-stopped",B.REALLOC_CON="realloc-con",B.AUDIO_ACTIVITY="audio-activity",B.SPEAKER_CHANGED="speaker-changed",B.STALLED_ACTIVITY="stalled-activity",B.CHAT_MESSAGE="chat-message",B.CUSTOM_DATA="custom-data",B.ROLES_CHANGED="roles-changed",B.MUTE_PARTICIPANT="mute-participant",B.PIN_PARTICIPANT="pin-participant",B.OPTIONS_CHANGED="options-changed",B.NETWORK_STATUS="network-status",B.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",B.PROMOTE_PARTICIPANT="promote-participant",B.CHAT_ROOM_UPDATED="chat-room-updated",B.PROMOTION_APPROVED="promotion-approved",B.JOIN_LINK_CHANGED="join-link-changed",B.FEEDBACK="feedback",B.MOVIE_UPDATE_NOTIFICATION="movie-update-notification",B.MOVIE_SHARE_INFO="movie-share-info",B.MOVIE_SHARE_STARTED="movie-share-started",B.MOVIE_SHARE_STOPPED="movie-share-stopped",B.ROOM_UPDATED="room-updated",B.ROOMS_UPDATED="rooms-updated",B.ROOM_PARTICIPANTS_UPDATED="room-participants-updated",B.FEATURES_PER_ROLE_CHANGED="features-per-role-changed",B.PARTICIPANT_ANIMOJI_CHANGED="participant-animoji-changed",B.ASR_STARTED="asr-started",B.ASR_STOPPED="asr-stopped",B))(Qr||{}),x=Qr;var Xr=(m=>(m.ERROR="callError",m.DEVICES="callDevices",m.CALL_SPEC_ERROR="callSpecError",m.ICE_CONNECTION_STATE="callIceConnectionState",m.ICE_CONNECTION_TYPE="callIceConnectionType",m.ICE_RESTART="callIceRestart",m.PUSH="callPush",m.OUTGOING_CALL="callStart",m.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",m.JOIN_CONVERSATION="callJoinConversation",m.ACCEPTED_OUTGOING="callAcceptedOutgoing",m.ACCEPT_INCOMING="callAcceptIncoming",m.DECLINE_INCOMING="callDeclineIncoming",m.ACCEPT_CONCURRENT="callAcceptConcurrent",m.HANGUP="callHangup",m.MEDIA_STATUS="callMediaStatus",m.DEVICE_CHANGED="callDeviceChanged",m.SOCKET_ACTION="callSocketAction",m.ADD_PARTICIPANT="callAddParticipant",m.REMOVE_PARTICIPANT="callRemoveParticipant",m.POOR_CONNECTION="callPoorConnection",m.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",m.RELAY_POLICY="callForceRelay",m.PAT_ALLOCATED="patAllocate",m.PAT_DEALLOCATED="patDeallocate",m.PAT_ERROR="patError",m.PAT_WAITING_TIME_ERROR="patWaitingTimeError",m.PAT_OUTDATED_RESPONSE="patOutdatedResponse",m.SIGNALING_CONNECTED="callSignalingConnected",m.FIRST_DATA_RECEIVED_P2P="callFirstDataReceivedP2P",m.FIRST_AUDIO_MIX_DATA_RECEIVED="callFirstAudioMixDataReceived",m.RECONNECT="callReconnect",m.SCREENSHARE_FIRST_FRAME="callScreenshareFirstFrame",m.SCREENSHARE_FIRST_FRAME_SMALL="callScreenshareFirstFrameSmall",m.SCREENSHARE_FIRST_FRAME_MEDIUM="callScreenshareFirstFrameMedium",m.SCREENSHARE_FIRST_FRAME_LARGE="callScreenshareFirstFrameLarge",m))(Xr||{}),v=Xr;var Zr=(e=>(e.AUDIO_MIX="audio-mix",e.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",e))(Zr||{}),we=Zr;var ea=(e=>(e.NO_AVAILABLE_TRACKS="no-available-tracks",e.UNKNOWN_ERROR="unknown-error",e))(ea||{}),ta=ea;function ia(n){switch(n){case 1:return"no-available-tracks";default:return"unknown-error"}}var ra=(e=>(e.CREATOR="CREATOR",e.ADMIN="ADMIN",e))(ra||{}),$e=ra;function Ht(n,r){if(n.length!==r.length)return!1;for(let e of n)if(!r.includes(e))return!1;return!0}var aa=(e=>(e.USER="USER",e.GROUP="GROUP",e))(aa||{}),z=aa;var li=class{constructor(){this._items=[]}get length(){return this._items.length}push(r){this._items.push(r)}shift(){return this._items.shift()||null}bisect(){let r=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(r)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(r,e)=>e instanceof Error?String(e):e):""}};var na=2*1024*1024,hn=512*1024,Gt=100*1024,_n=5,zi="_okcls_logs_session_",gn=3e4,Yi=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=na;try{let r=window.localStorage;for(let e of Object.keys(r)){if(e.indexOf(zi)!==0)continue;let t=r.getItem(e);if(!t){sa(e);continue}let i=ca(t);this.add(e,i)}}catch(r){console.error("Storage is blocked",r),this._storageSize=0}this._items.sort((r,e)=>r.date-e.date),this.cleanup(Gt)}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(r){this._storageSize=r}add(r,e){let t=parseInt(r.replace(zi,""),10);this._itemsSize+=e,this._items.push({key:r,size:e,date:t})}deleteOldestItem(){let r=this._items.shift();r&&(sa(r.key),this._itemsSize-=r.size)}cleanup(r){for(;this.length&&(this.size>na||this.length>_n-1||this.size+r>this.available);)this.deleteOldestItem()}};function oa(){return`${zi}${Date.now()}`}function ca(n){return new Blob([n]).size}function sa(n){try{window.localStorage.removeItem(n)}catch(r){console.error("Failed to remove log from storage",r)}}function Qi(){let n=dt.toString();if(!Te.available||!n)return;let r=ca(n);Te.cleanup(r);try{window.localStorage.setItem(pi,n)}catch(e){if(console.warn("Failed to write log to storage",e),Te.storageSize=Te.size+r,Te.cleanup(Gt+r),Te.available>=Gt+r){Qi();return}if(r>Gt){dt.bisect(),Qi();return}Te.storageSize=0;return}r>hn&&(Te.add(pi,r),pi=oa(),dt.clear(),Te.cleanup(Gt))}function Xi(){!Te.available||!dt.length||Qi()}function fn(n=!1){let r=[];try{let i=window.localStorage;for(let s of Te.items){let o=i.getItem(s.key);r.push(o)}let a=dt.toString();a&&r.push(a)}catch(i){console.error("Storage is blocked",i)}let e=`[${r.join(",")}]`;if(n)return e;let t=`logs_${Date.now()}.json`;return Sn(e,t),t}function Sn(n,r){let e=document.createElement("a"),t=new Blob([n],{type:"text/json"});e.href=URL.createObjectURL(t),e.download=r,e.click()}function da(n,r){if(!Te.available)return;let e=new Date;dt.push({t:e.getTime(),l:n,d:r,h:e.toLocaleString("ru-RU",{dateStyle:"short",timeStyle:"long"})}),Ji||(Ji=window.setTimeout(()=>{Ji=null,Xi()},gn))}function Zi(){Te||(Te=new Yi,dt=new li,pi=oa(),window.addEventListener("beforeunload",Xi))}var Te,dt,pi,Ji=null;window.__VKCallsSDKLogs__=(n=!1)=>(Te||Zi(),Xi(),fn(n));var mr=si(require("@vkontakte/libvpx"));var la=n=>n.stop(),Wt=n=>n.getTracks().forEach(la),pa=n=>n.getVideoTracks().forEach(la);function It(n,{width:r,height:e}){return n.applyConstraints({width:{max:r,ideal:r},height:{max:e,ideal:e}})}var tr="_okcls_",Tt=(()=>{try{let n=Date.now().toString(),r=window.localStorage,e=!1;return r.setItem(n,n),e=r.getItem(n)===n,r.removeItem(n),e?r:null}catch(n){return null}})();function En(n){let r=Tt?Tt.getItem(tr+n):null;if(r===null)return null;try{return JSON.parse(r)}catch(e){return null}}function In(n,r){try{Tt&&Tt.setItem(tr+n,JSON.stringify(r))}catch(e){}}function Tn(n){Tt&&Tt.removeItem(tr+n)}var er;(t=>{function n(i){return En(i)||null}t.get=n;function r(i,a){In(i,a)}t.set=r;function e(i){Tn(i)}t.remove=e})(er||(er={}));var Ye=er;var Ct=null,ir=null,fi=[],Si=[],gi=[],Qe=null,Xe=null,sr=null,ua=null,or=!1,vi=!1,ui,Rt,mi,rr=null,ar="",hi=[],nr=null,ma=navigator.appVersion,Rn=navigator.appName,Ce=navigator.userAgent,qe=(e=>(e.USER="user",e.ENVIRONMENT="environment",e))(qe||{});(r=>{function n(e){return Object.values(r).includes(e)}r.contains=n})(qe||(qe={}));var lt=class{constructor(r,e=!1,t=p.videoMaxWidth,i=p.videoMaxHeight){let a=!1;if(r){a={noiseSuppression:p.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let o;Xe&&(o=Xe.deviceId),typeof r=="string"&&(o=r),o&&(a.deviceId={exact:o})}let s=!1;if(e){s={width:{min:p.videoMinWidth,max:t,ideal:t},height:{min:p.videoMinHeight,max:i,ideal:i},aspectRatio:{ideal:p.videoAspectRatio},frameRate:{ideal:p.videoFrameRate}};let o;Qe&&(o=Qe.deviceId),typeof e=="string"&&(o=e),o&&(s.deviceId={exact:o}),p.videoFacingMode&&(s.facingMode={ideal:p.videoFacingMode},delete s.deviceId)}this.audio=a,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let r=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||r)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},cr=class extends lt{constructor(e,t,i,a){super(!1,!0);this.captureController="CaptureController"in window?new CaptureController:null,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=i,this.video.displaySurface=p.displaySurface,Ve.browserName()==="Safari"&&Number(Ve.browserVersion())===16&&(delete this.video.width,delete this.video.height),a&&(this.audio={noiseSuppression:!1,echoCancellation:!1,autoGainControl:!1})}getNative(){return Object.assign(super.getNative(),{systemAudio:"exclude",controller:this.captureController})}};function ha(){return c(this,null,function*(){vi=!1,Ct=null,yield dr(),f.onDeviceChange()})}function dr(){return c(this,null,function*(){return Ct||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!ir&&navigator.mediaDevices.addEventListener&&(ir=I.throttle(ha,1e3),navigator.mediaDevices.addEventListener("devicechange",ir)),Ct=navigator.mediaDevices.enumerateDevices().then(n=>{fi=n.filter(i=>i.kind==="videoinput"?(i.label&&(or=!0),!0):!1),Si=n.filter(i=>i.kind==="audioinput"?(i.label?vi=!0:Ve.isMobile()&&Ve.browserName()==="Firefox"&&(vi=or),!0):!1),gi=n.filter(i=>i.kind==="audiooutput");let r=Ye.get("videoinput"),e=Ye.get("audioinput"),t=Ye.get("audiooutput");return Qe=fi.find(i=>i.deviceId===r)||null,Xe=Si.find(i=>i.deviceId===e)||null,sr=gi.find(i=>i.deviceId===t)||gi[0]||null,Ct=Promise.resolve(n),n}).catch(()=>(Ct=null,[]))))})}function Cn(n){if(Qe&&Xe)return;let r=(e,t)=>{var a;let i=(a=t.getSettings())==null?void 0:a.deviceId;return e.find(s=>s.deviceId===i||s.label===t.label)||null};n==null||n.getTracks().forEach(e=>{var t;if(!Xe&&e.kind==="audio")Xe=r(Ve.getMicrophones(),e);else if(e.kind==="video"){Qe||(Qe=r(Ve.getCameras(),e));let i=(t=e.getSettings())==null?void 0:t.facingMode;qe.contains(i)&&(ua=i)}})}function Kt(n,r){return c(this,null,function*(){d.debug("Try to get media",JSON.parse(JSON.stringify(n.getNative())));let e=Ve.hasPermissions(n.isVideo());!e&&!r&&f.onPermissionsRequested();try{let t=yield navigator.mediaDevices.getUserMedia(n.getNative());return e||(yield ha()),Cn(t),t}catch(t){switch(d.error("getUserMedia error",t),t.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":r=n.isVideo()?re.CAMERA_PERMISSION:re.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":r=re.UNKNOWN;break;case"AbortError":case"NotReadableError":r=n.isVideo()?re.CAMERA_ACCESS:re.MIC_ACCESS;break}if(n.canSimplify())return Kt(n.simplify(),r);let i=r||re.UNKNOWN;throw f.onPermissionsError(i,t),i}})}function Pn(n){return c(this,null,function*(){var r;d.debug("Try to get screen",n.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(n.getNative()),t=e==null?void 0:e.getVideoTracks()[0];if(t&&(d.debug("Got display media track",t.id),t.contentHint="text",n.captureController)){let i=(r=t.getSettings())==null?void 0:r.displaySurface;(i==="browser"||i==="window")&&n.captureController.setFocusBehavior("no-focus-change")}return e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw re.SCREEN_PERMISSION;default:throw re.SCREEN_ACCESS}}})}function _i(){return hi.length||(hi=(()=>{let n,r=!1,e=0,t="0",i=Ce.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return n=/\brv[ :]+(\d+)/g.exec(Ce),["IE",n&&n[1]||"Unknown",r,e,t];if(i[1]==="Safari"){if(n=Ce.match(/\bEdge\/(\d+)/),n)return["Edge",n[1]||"Unknown",r,e,t];if(n=Ce.match(/\bCriOS\/(\d+)/),n)return["Chrome",n[1],!0,Number(n[1]),t];if(n=Ce.match(/\bFxiOS\/(\d+)/),n)return["Firefox",n[1],!1,e,t];if(n=Ce.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1],!1,e,t];if(n=Ce.match(/\bOPT\/(\d+)/),n)return["Opera",n[1],!1,e,t]}if(i[1]==="Chrome"){if(r=!0,e=Number(i[2]),n=Ce.match(/\bOPR\/(\d+)/),n)return["Opera",n[1]||"Unknown",r,e,t];if(n=Ce.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1]||"Unknown",r,e,t];if(n=Ce.match(/\bSferum\/((\d+)(?:\.\d+)*)/),n)return["Sferum",n[1]||"Unknown",r,e,t];if(n=Ce.match(/\bEdge?\/(\d+)/),n)return["Edge",n[1]||"Unknown",r,e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",r,e,t]}return n=Ce.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),n&&n[2]!==void 0&&(t=n[2]),[i[2]?i[1]:Rn,n&&n[1]||i[2]||ma,r,e,t]})()),hi}var Ve;(O=>{function n(){return c(this,null,function*(){let m=()=>{ue(),document.removeEventListener("click",m),document.removeEventListener("touchstart",m)};return document.addEventListener("click",m),document.addEventListener("touchstart",m),dr()})}O.init=n;function r(){return fi}O.getCameras=r;function e(){return Si}O.getMicrophones=e;function t(){return gi}O.getOutput=t;function i(){return fi.length>0}O.hasCamera=i;function a(){return Si.length>0}O.hasMicrophone=a;function s(){return Qe}O.getSavedCamera=s;function o(){return Xe}O.getSavedMicrophone=o;function l(){return sr}O.getSavedOutput=l;function u(){return ua||p.videoFacingMode||null}O.getVideoFacingMode=u;function g(){return or}O.hasCameraPermission=g;function T(){return vi}O.hasMicrophonePermission=T;function b(m=!1){return T()?i()&&m?g():!0:!1}O.hasPermissions=b;function D(m=!1,k=!0,G=!0){return c(this,null,function*(){let J=a()&&k,de=i()&&m,me;if(!J&&!de)me=new MediaStream;else try{me=yield Kt(new lt(J,de))}catch(Ne){me=new MediaStream}return!me.getVideoTracks().length&&G&&me.addTrack(Se()),!me.getAudioTracks().length&&G&&me.addTrack(ue()),me})}O.getUserMedia=D;function A(m,k){return c(this,null,function*(){let G=m?p.fastScreenShareWidth:window.screen.width,J=m?p.fastScreenShareHeight:window.screen.height,de=p.getScreenFrameRate(m);return Pn(new cr(G,J,de,k))})}O.getScreenMedia=A;function Y(m=!1){return c(this,null,function*(){let k=m?p.videoEffectMaxWidth:p.videoMaxWidth,G=m?p.videoEffectMaxHeight:p.videoMaxHeight;return Kt(new lt(!1,!0,k,G))})}O._getUserVideo=Y;function H(m,k){return c(this,null,function*(){let G=(k==null?void 0:k.width)||p.videoMaxWidth,J=(k==null?void 0:k.height)||p.videoMaxHeight;return Kt(new lt(!1,m||!0,G,J))})}O.getUserVideo=H;function ge(m){return c(this,null,function*(){return Kt(new lt(m||!0,!1))})}O.getUserAudio=ge;function W(m,k){return c(this,null,function*(){let[G]=m.getVideoTracks();if(!G)throw new Error("Video track not found in stream");return It(G,k)})}O.setResolution=W;function ee(m,k){return c(this,null,function*(){let J=(yield dr()).find(de=>de.kind===m&&de.deviceId===k);return J?(m==="videoinput"?Qe=J:m==="audioinput"?Xe=J:m==="audiooutput"&&(sr=J),Ye.set(m,k),J):null})}O.saveDeviceId=ee;function ue(){if(!mi||mi.readyState==="ended"){let m=E(),k=m.createMediaStreamDestination(),G=m.createGain();G.gain.value=1e-5,G.connect(k),G.connect(m.destination);let J=m.createOscillator();J.type="sine",J.frequency.value=0,J.connect(G),J.start(),mi=k.stream.getAudioTracks()[0]}return Object.assign(mi.clone(),{enabled:!1})}O.getSilentMediaTrack=ue;function Se(m=p.videoMinWidth,k=p.videoMinHeight){Rt||(Rt=document.createElement("canvas")),Rt.width=m,Rt.height=k;let G=Rt.getContext("2d");return G.rect(0,0,m,k),G.fillStyle="black",G.fill(),(!ui||ui.readyState==="ended")&&(ui=Rt.captureStream(p.videoFrameRate).getVideoTracks()[0]),Object.assign(ui.clone(),{enabled:!1})}O.getBlackMediaTrack=Se;function nt(){if(Gi()==="Edge"&&Number(Wi())<70)return!1;try{let m=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&m.RTCPeerConnection&&m.RTCIceCandidate&&m.RTCSessionDescription&&m.HTMLCanvasElement&&m.HTMLCanvasElement.prototype.captureStream&&m.RTCRtpSender&&m.RTCRtpSender.prototype.replaceTrack&&m.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(m){return!1}}O.isBrowserSupported=nt;function ni(){return!!navigator.mediaDevices.getDisplayMedia}O.isScreenCapturingSupported=ni;function Q(){let m=O.browserName()==="Safari"&&O.browserVersion()==="15"&&O.browserSubVersion()==="1",k=O.browserName()==="Opera"&&O.os()==="Windows";return m||k}O.isBrokenH264=Q;function yr(){return!(O.baseChromeVersion()&&O.isMobile())}O.canPreferH264=yr;function br(){var m;return((m=window.RTCRtpTransceiver)==null?void 0:m.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}O.canPreferRed=br;function Mr(){return ar||(ar=(()=>{let m={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 k in m)if(m.hasOwnProperty(k)&&m[k].test(Ce))return k;return"Unknown"})()),ar}O.os=Mr;function Ar(){return rr===null&&(rr=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(ma)),rr}O.isMobile=Ar;function Gi(){return _i()[0]}O.browserName=Gi;function Wi(){return _i()[1]}O.browserVersion=Wi;function Ki(){return _i()[3]}O.baseChromeVersion=Ki;function E(){return nr||(nr=new(window.AudioContext||window.webkitAudioContext)),nr}O.getAudioContext=E;function R(){return _i()[4]}O.browserSubVersion=R;function M(){return O.baseChromeVersion()>=105&&!O.isMobile()}O.isAudioShareSupported=M})(Ve||(Ve={}));var C=Ve;function _a(n,r){if(n.isAudioEnabled!==r.isAudioEnabled||n.isVideoEnabled!==r.isVideoEnabled||n.isScreenSharingEnabled!==r.isScreenSharingEnabled||n.isFastScreenSharingEnabled!==r.isFastScreenSharingEnabled||n.isAudioSharingEnabled!==r.isAudioSharingEnabled||n.isAnimojiEnabled!==r.isAnimojiEnabled||n.videoStreams.length!==r.videoStreams.length)return!1;for(let e of n.videoStreams)if(!r.videoStreams.find(t=>t.id===e.id&&t.source===e.source))return!1;return!0}function _e(n){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,isFastScreenSharingEnabled:!1,isAudioSharingEnabled:!1,isAnimojiEnabled:!1,videoStreams:[]},n||{})}var F=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(w).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,F)}};var xe=(i=>(i.audio="audio",i.video="video",i.screen="screen",i.audioshare="audioshare",i))(xe||{}),Ei=class extends ie{constructor(){super();this._stream=null;this._screenTrack=null;this._audioShareTrack=null;this._sendVideoTrack=null;this._cameraVideoTrack=null;this._mediaSettings=_e();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._sourceBusy=!1;this._animojiEnabled=!1;this._initDeviceChangeListener(),p.audioShare&&(this._audioShareTrack=this.getSilentAudioShareTrack())}request(){return c(this,arguments,function*(e=[oe.AUDIO],t=!0){var o;if(this._stream)return;let i=e.includes(oe.VIDEO),a=e.includes(oe.AUDIO),s=e.includes(oe.ANIMOJI);if(!C.isBrowserSupported())throw new F(re.UNSUPPORTED);try{this._stream=yield C.getUserMedia(i,a,t),(o=this._cameraVideoTrack)==null||o.stop(),this._cameraVideoTrack=this._stream.getVideoTracks()[0],this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(l=>l.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=a&&this._stream.getAudioTracks().filter(l=>l.enabled).length>0||!1,this._mediaSettings.isAnimojiEnabled=s&&!this._mediaSettings.isVideoEnabled||!1,this._animojiEnabled=s}catch(l){throw new F(l)}})}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}get isAnimojiRequested(){return this._animojiEnabled&&!this._mediaSettings.isVideoEnabled}addTrackToPeerConnection(e,t,i,a){let s=this.getStream(),o=this._getSendAudioTrack(),l=this.getSendVideoTrack(i);if(!s||!o&&!l&&!t)throw new Error("No local stream found");if(o&&!t){if(a){let{codecs:u}=RTCRtpSender.getCapabilities("audio"),g="audio/red",T=48e3,b=u.findIndex(D=>D.mimeType===g&&D.clockRate===T);if(b>=0){let D=[];D.push(u[b]);for(let A=0;A<u.length;A++)A!==b&&D.push(u[A]);e.getTransceivers().forEach(A=>A.setCodecPreferences(D))}}e.addTrack(o,s)}l&&!t&&e.addTrack(l,s)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return c(this,null,function*(){switch(e){case"videoinput":if(this._mediaSettings.isVideoEnabled)return this._changeVideoInput();break;case"audioinput":if(this._mediaSettings.isAudioEnabled)return this._changeAudioInput();break;default:return Promise.reject(re.UNKNOWN)}})}stopVideoTrack(){var e;this._mediaSettings.isVideoEnabled&&(this._stopEffect(),pa(this._stream),(e=this._cameraVideoTrack)==null||e.stop())}setVideoStream(e,t){return c(this,null,function*(){return t?this._changeScreen(!1,!1,e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=I.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);this._onDeviceChange=()=>c(this,null,function*(){if(!this._stream)return;let a=C.getSavedMicrophone(),s=C.getSavedCamera(),o=a==null?void 0:a.deviceId,l=s==null?void 0:s.deviceId;if(!o&&!l)return;let u=yield navigator.mediaDevices.enumerateDevices();!e&&o&&(e=!u.find(g=>g.deviceId===o)),!t&&l&&(t=!u.find(g=>g.deviceId===l)),i()}),navigator.mediaDevices.addEventListener("devicechange",this._onDeviceChange)}_destroyDeviceChangeListener(){this._onDeviceChange&&navigator.mediaDevices.removeEventListener("devicechange",this._onDeviceChange)}_changeVideoInput(e=null,t){return c(this,null,function*(){var i;this._busy();try{let a=e?"stream":"video",s=e||(yield C._getUserVideo(!!this._effect));if((i=this._cameraVideoTrack)==null||i.stop(),this._cameraVideoTrack=s.getVideoTracks()[0],!this._stream)Wt(s);else{p.consumerScreenTrack||(yield this._disableScreenCapture());let o=yield this._setEffect(this._effect,this._cameraVideoTrack);t&&(yield It(o,t)),_.log(v.DEVICE_CHANGED,a),d.log("Video stream changed"),yield this._replaceLocalTrack(o),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(a){throw _.log(v.ERROR,"change_video"),d.warn("Camera change failed",a),a}finally{this._free()}})}setAudioStream(e){return c(this,null,function*(){return this._changeAudioInput(e)})}_busy(){if(this._sourceBusy)throw _.log(v.ERROR,"change_device"),d.warn("Device change failed: MediaSource is busy"),new Error("MediaSource is busy");this._sourceBusy=!0}_free(){this._sourceBusy=!1}_changeAudioInput(e=null){return c(this,null,function*(){this._busy();try{if(e=e||(yield C.getUserAudio()),!this._stream)Wt(e);else{let t=e.getAudioTracks()[0];_.log(v.DEVICE_CHANGED,"audio"),d.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw _.log(v.ERROR,"change_audio"),d.error("Microphone change failed",t),t}finally{this._free()}})}_changeScreen(e,t,i){return c(this,null,function*(){this._busy();try{if(i=i||(yield C.getScreenMedia(e,t)),i.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.disableScreenCapturing()},!1),!this._stream)Wt(i);else{let a=i.getVideoTracks()[0];if(p.consumerScreenTrack||this._stopEffect(),_.log(v.DEVICE_CHANGED,"screen"),d.log("Screen capturing started"),this._screenTrack=a,this._mediaSettings.isScreenSharingEnabled=!0,this._mediaSettings.isFastScreenSharingEnabled=e,p.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._sendVideoTrack=p.consumerScreenDataChannel?C.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight):a,yield this._replaceLocalTrack(a,this._sendVideoTrack)),i.getAudioTracks().length>0){let s=i.getAudioTracks()[0];s.contentHint="music",this._audioShareTrack=s,yield this._replaceLocalTrack(s),this._mediaSettings.isAudioSharingEnabled=!0}t&&!this._mediaSettings.isAudioSharingEnabled&&d.debug("Audio share requested but not captured"),this._triggerEvent("SCREEN_STATUS",{track:a,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(a){throw _.log(v.ERROR,"screen"),d.warn("Screen capturing failed",a),a}finally{this._free()}})}_disableScreenCapture(){return c(this,null,function*(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),yield this.stopAudioShareTrack(),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._mediaSettings.isFastScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))})}disableAudioShare(){return c(this,null,function*(){yield this.stopAudioShareTrack(),this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"audioshare",mediaSettings:this._mediaSettings})})}stopAudioShareTrack(){return c(this,null,function*(){if(this._audioShareTrack){this._audioShareTrack.stop();let e=this.getSilentAudioShareTrack();yield this._replaceLocalTrack(e),this._mediaSettings.isAudioSharingEnabled=!1}})}getSilentAudioShareTrack(){let e=C.getSilentMediaTrack();return e.contentHint="music",e.stop(),e}_replaceLocalTrack(e,t){return c(this,null,function*(){if(!this._stream)return;let i=!1;this._stream.getTracks().forEach(a=>{var s,o;a.kind===e.kind&&a.contentHint===e.contentHint&&(a.stop(),(s=this._stream)==null||s.removeTrack(a),(o=this._stream)==null||o.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t),i=!0)}),i||(this._stream.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})}_setEffect(e,t){return c(this,null,function*(){if(!p.videoEffects)return t;try{return p.videoEffects.setEffect(e,t)}catch(i){return d.warn("Video effect failed",i),t}})}_stopEffect(){if(p.videoEffects)try{p.videoEffects.stopEffect()}catch(e){d.warn("Video effect failed",e)}}destroy(){var e;this._destroyDeviceChangeListener(),p.videoEffects&&(this._effect=null,p.videoEffects.destroy()),this._stream&&(Wt(this._stream),this._stream=null),(e=this._cameraVideoTrack)==null||e.stop(),this._disableScreenCapture()}toggleScreenCapturing(e){return c(this,null,function*(){if(e.captureScreen){yield this._changeScreen(e.fastScreenSharing,e.captureAudio);return}return p.consumerScreenTrack?this._disableScreenCapture():(e.captureAudio||(yield this.disableAudioShare()),this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1))})}disableScreenCapturing(){return c(this,null,function*(){return this.toggleScreenCapturing({captureScreen:!1,fastScreenSharing:!1,captureAudio:!1})})}toggleVideo(e){return c(this,null,function*(){var i;if(!this._stream)return;p.consumerScreenTrack||(yield this._disableScreenCapture()),(i=this._cameraVideoTrack)==null||i.stop();let t;if(e){let a=yield C._getUserVideo(!!this._effect);this._cameraVideoTrack=a.getVideoTracks()[0],t=yield this._setEffect(this._effect,this._cameraVideoTrack)}else t=C.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight),this._stopEffect();if(yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._animojiEnabled){this._triggerEvent("ANIMOJI_STATUS",!e);return}this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return c(this,null,function*(){if(!this._stream)return;let t;e?t=(yield C.getUserAudio()).getAudioTracks()[0]:t=C.getSilentMediaTrack(),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}toggleAnimojiCapturing(e){this._animojiEnabled=e,this._mediaSettings.isVideoEnabled||this._triggerEvent("ANIMOJI_STATUS",e)}onAnimojiSender(e){this._mediaSettings.isAnimojiEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}_setEffectResolution(e){return c(this,null,function*(){if(!p.videoEffects)return;let t=this._cameraVideoTrack;this._stopEffect(),yield It(t,e);let i=yield this._setEffect(this._effect,t);yield this._replaceLocalTrack(i)})}setResolution(i){return c(this,arguments,function*({video:e,effect:t}){if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let a=this._stream.getVideoTracks()[0];if(!a)throw new Error("Local video track not found");if(a.enabled){if(!this._effect)return It(a,e);if(t)return this._setEffectResolution(t)}})}updateNoiseSuppression(){return c(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks().find(t=>!t.contentHint);if(!e)throw new Error("Local audio track not found");if(e.enabled)return e.applyConstraints({noiseSuppression:p.noiseSuppression})})}videoEffect(e){return c(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(_.log(v.DEVICE_CHANGED,`effect_${(e==null?void 0:e.effect)||"none"}`),!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect){let t=this._effect;this._effect=e;try{let i=new MediaStream([this._cameraVideoTrack.clone()]);return e?this._changeVideoInput(i,{width:p.videoEffectMaxWidth,height:p.videoEffectMaxHeight}):this._changeVideoInput(i)}catch(i){throw this._effect=t,i}}})}getAudioShareTrack(){return this._audioShareTrack}};var ga=typeof Object.fromEntries=="function"?Object.fromEntries:function(n){if(!n||!n[Symbol.iterator])throw new Error("Object.fromEntries() requires a single iterable argument");let r={};for(let[e,t]of n)r[e]=t;return r};function fa(n){return c(this,null,function*(){return new Promise((r,e)=>{let t=new FileReader;t.onload=i=>{r(i.target.result)},t.onerror=e,t.readAsArrayBuffer(n)})})}var Pt=":",Ii="d",yn=533,lr="a=fmtp:",bn="sps-pps-idr-in-keyframe=1",pr;(Ki=>{function n(E,R,M,O,m,k=!1,G=!1){let J=/[\r\n]+/,de=`\r
8
- `;if(!R&&!M&&!O&&!G&&!k&&!m)return E;function me(q){let he=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],ve="a=rtcp-fb:111",te=q.findIndex(X=>X.startsWith(ve));return~te&&(q[te]=q[te]+de+he.join(de)),q}function Ne(q,he,ve){let te=q.split(" "),X=te.slice(0,3),se;for(se=3;se<te.length;se++)ve.includes(te[se])&&X.push(te[se]);for(se=3;se<te.length;se++)!ve.includes(te[se])&&!he.includes(te[se])&&X.push(te[se]);return X.join(" ")}function De(q,he){let ve=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),te,X=[];for(te=0;te<q.length;++te){let se=q[te].match(ve);se&&se.length===3&&se[2]===he&&X.push(se[1])}return X}function ke(q,he,ve,te){let X,se="m="+he;for(X=0;X<q.length;++X)if(q[X].startsWith(se)){q[X]=Ne(q[X],ve,te);break}}function Oe(q,he){let ve=new RegExp(lr+"(\\d+)");for(let te=0;te<q.length;++te){let X=q[te].match(ve);if(X&&X.length===2&&he.includes(X[1])){let se=q[te].trim()===lr+X[1]?" ":";";q[te]+=se+bn}}}function Ue(q){let he=De(q,"H264");if(M){let ve=he.slice(0),te=new RegExp(lr+"(\\d+) apt=(\\d+)"),X;for(X=0;X<q.length;++X){let Ge=q[X].match(te);Ge&&Ge.length===3&&ve.includes(Ge[2])&&ve.push(Ge[1])}let se=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(X=q.length;X--;){let Ge=q[X].match(se);Ge&&Ge.length===3&&ve.includes(Ge[2])&&q.splice(X,1)}ke(q,"video",ve,[])}else R&&ke(q,"video",[],he),m&&Oe(q,he)}function N(q){let he=De(q,"VP9");O&&ke(q,"video",[],he)}function Ft(q){let he=De(q,"red");he.length>0&&ke(q,"audio",[],he)}let B=E.split(J);return(M||R||m)&&Ue(B),O&&N(B),G&&Ft(B),k&&me(B),B.join(de)}Ki.patchLocalSDP=n;function r(E){return C.browserName()==="Firefox"&&Number(C.browserVersion())<60&&(E=E.replace("m=application 9 UDP/DTLS/SCTP webrtc-datachannel","m=application 9 DTLS/SCTP 5000").replace("a=sctp-port:5000","a=sctpmap:5000 webrtc-datachannel 256")),E}Ki.patchRemoteSDP=r;function e(E){return E?`${E.type||"WEB_SOCKET"}_${E.id}`:"_"}Ki.getPeerIdString=e;function t(E,R){return E&&E.id===R.id&&(E.type||"WEB_SOCKET")===(R.type||"WEB_SOCKET")}Ki.comparePeerId=t;function i(E){return c(this,null,function*(){return!E||!E.getStats?Promise.resolve(null):E.getStats(null).then(R=>{let M=null,O=null;if(R.forEach(m=>{m.type==="transport"&&m.selectedCandidatePairId?O=R.get(m.selectedCandidatePairId):m.type==="candidate-pair"&&m.state==="succeeded"&&!O&&(!m.hasOwnProperty("selected")||m.selected)&&(O=m)}),O&&O.localCandidateId){let m=R.get(O.localCandidateId);m&&(M={type:m.candidateType,ip:m.ip||m.ipAddress,port:m.port||m.portNumber})}return M}).catch(()=>null)})}Ki.getPeerConnectionHostInfo=i;let a=/^[0-9]+$/,s=/^([gu])([0-9]+)$/;function o(E,R){let M=String(E);return s.test(M)?(d.warn(`Already composite id [${E}] type supplied [${R}]`),M):R===z.GROUP?"g"+M:R===z.USER?"u"+M:(d.warn(`Unknown type [${R}] for id [${E}]`),M.match(a)?"u"+M:M)}Ki.composeUserId=o;function l(E,R,M){let O=o(E,R);return u(O,M)}Ki.composeParticipantId=l;function u(E,R){return R?E+Pt+Ii+R:E}Ki.compose=u;function g(E){return l(E.id,E.idType||z.USER,E.deviceIdx||0)}Ki.composeId=g;function T(E){return E.participant?g(E.participant):l(E.participantId,E.participantType||z.USER,E.deviceIdx||0)}Ki.composeMessageId=T;function b(E){let R=String(E),M=R.match(s);return M?{id:Number(M[2]),type:M[1]==="g"?z.GROUP:z.USER}:(d.warn(`Unsupported compositeId [${E}]`),{id:Number(R),type:z.USER})}Ki.decomposeId=b;function D(E){let R=E.split(Pt+Ii);return{compositeUserId:R[0],deviceIdx:R.length>1?parseInt(R[1],10):0}}Ki.decomposeParticipantId=D;function A(){var G,J;let E=(J=(G=window.crypto)==null?void 0:G.randomUUID)==null?void 0:J.call(G);if(E)return E;let R="0123456789abcdefghijklmnopqrstuvwxyz".split(""),M=new Array(36),O=0,m,k;for(k=0;k<36;k++)k===8||k===13||k===18||k===23?M[k]="-":k===14?M[k]="4":(O<=2&&(O=33554432+Math.random()*16777216|0),m=O&15,O=O>>4,M[k]=R[k===19?m&3|8:m]);return M.join("")}Ki.uuid=A;function Y(E,R){let M;function O(){let m=this,k=arguments;M&&window.clearTimeout(M),M=window.setTimeout(()=>{E.apply(m,k)},R)}return O}Ki.throttle=Y;function H(E){if(!window.BigInt)return null;let R="",M=E.split(`
9
- `);for(let k of M)if(k.startsWith("a=fingerprint")){let G=k.split(" ");if(G.length===2){R=G[1];break}}if(!R)return BigInt(-1);let O=R.split(":"),m=BigInt(0);for(let k=Math.min(7,O.length-1);k>=0;k--){let G=BigInt(parseInt(O[k],16));m<<=BigInt(8),m|=G}return BigInt.asIntN(64,m)}Ki.sdpFingerprint=H;function ge(E){return c(this,null,function*(){return new Promise(R=>window.setTimeout(R,E))})}Ki.delay=ge;function W(E,R,M){let O=[];return E.getSenders().forEach(m=>ee(R,m,m.track,M,O)),O}Ki.applySettings=W;function ee(E,R,M,O,m){var k;if(E&&M&&M.kind==="video"){let G=M.getSettings();if(G){let J=E.maxBitrateK?E.maxBitrateK*1024:null,de=G.width,me=G.height,Ne=de&&me&&E.maxDimension?Math.max(1,Math.max(de,me)/E.maxDimension):null,De=E.maxFramerate?E.maxFramerate:null;if(de&&me&&E.maxDimension&&E.maxDimension>Math.max(de,me)){let N=Math.round(de*me/256),Ft=(Math.round(N*yn/1e4)+1)*1e4;J=J===null?Ft:Math.min(Ft,J)}let ke=E.degradationPreference?E.degradationPreference:"balanced",Oe=O[M.id];if(Oe&&Oe.bitrate===J&&Oe.scaleResolutionDownBy===Ne&&Oe.maxFramerate===De&&Oe.degradationPreference===ke){m[M.id]=Oe;return}m[M.id]={bitrate:J,scaleResolutionDownBy:Ne,maxFramerate:De,degradationPreference:ke};let Ue=R.getParameters();Ue.encodings||(Ue.encodings=[{}]),Ue.encodings.forEach(N=>{J?N.maxBitrate=J:delete N.maxBitrate,Ne?N.scaleResolutionDownBy=Ne:delete N.scaleResolutionDownBy,De?N.maxFramerate=De:delete N.maxFramerate}),Ue.degradationPreference=ke,(k=R.setParameters)==null||k.call(R,Ue)}}}Ki.applyVideoTrackSettings=ee;function ue(E,R){Array.isArray(R)||(R=[R]);for(let M of R)if(E.includes(M))return!0;return!1}Ki.includesOneOf=ue;function Se(E){var R;return Object.entries(((R=E.participantState)==null?void 0:R.state)||{}).reduce((M,[O,m])=>(E.participantState&&(M[O]={ts:E.participantState.stateUpdateTs[O],state:m}),M),{})}Ki.mapParticipantState=Se;function nt(E){let R=E.map(M=>({uid:M.externalId,mediaSettings:M.mediaSettings,status:M.status,muteStates:M.muteStates,unmuteOptions:M.unmuteOptions,participantState:M.participantState,markers:M.markers,movieShareInfos:M.movieShareInfos}));return p.filterObservers?R.filter(M=>!M.uid.observer):R}Ki.mapSharedParticipants=nt;function ni(E,R){let M=Object.keys(E),O=Object.keys(R);if(M.length!==O.length)return!1;for(let m of M)if(!O.hasOwnProperty(m)||E[m].state!==R[m].state||E[m].ts!==R[m].ts)return!1;return!0}Ki.isEqualParticipantState=ni;function Q(E,R){let M=Object.keys(E),O=Object.keys(R);if(M.length!==O.length)return!1;for(let m of M)if(!R.hasOwnProperty(m)||E[m]!==R[m])return!1;return!0}Ki.isObjectsEquals=Q;function yr(E,R){if(E.length!==R.length)return!1;for(let M of E)if(R.indexOf(M)<0)return!1;return!0}Ki.isArraysEquals=yr;function br(E){return!Object.keys(E).length}Ki.isEmptyObject=br;function Mr(E,R){if(!E&&!R)return 0;if(!E||!R)return E?-1:1;return O(R.rank,E.rank)||O(E.ts,R.ts)||M(E,R);function M(m,k){let G={[z.USER]:0,[z.GROUP]:1},{compositeUserId:J,deviceIdx:de}=D(m.id),{compositeUserId:me,deviceIdx:Ne}=D(k.id),{id:De,type:ke}=b(J),{id:Oe,type:Ue}=b(me);return O(G[ke],G[Ue])||O(De,Oe)||O(de,Ne)}function O(m,k){return m<k?-1:m===k?0:1}}Ki.participantMarkerCompare=Mr;function Ar(E,R){let M=Object.entries(E).filter(([,O])=>Array.isArray(R)?!R.includes(O):O!==R);return ga(M)}Ki.objectFilterOutValues=Ar;function Gi(E,R,M){let O=M;for(let m in E)E.hasOwnProperty(m)&&(O=R(O,E[m],m));return O}Ki.objectReduce=Gi,Ki.setImmediate=(()=>{let E=1,R={},M=null;return typeof MessageChannel!="undefined"&&(M=new MessageChannel,M.port1.onmessage=O=>{let m=O.data;R[m]&&(R[m](),delete R[m])}),function(O){if(M&&document.visibilityState==="hidden"){let k=E;return E=E>=Number.MAX_SAFE_INTEGER?1:E+1,R[k]=O,M.port2.postMessage(k),()=>{R[k]&&delete R[k]}}let m=setTimeout(O,0);return()=>clearTimeout(m)}})()})(pr||(pr={}));var I=pr;var Mn=1e3;function le(n,r,e=0){return r in n&&n[r]?n[r]:e}function Sa(...n){return r=>{for(let e of n)if(e(r))return!0;return!1}}function Ze(n,r){return e=>e[n]===r}function An(n){return(r,e)=>r[n]-e[n]}function Ti(n,r){return r.reduce((e,t)=>(e[t[n]]=t,e),{})}function Dn(n){let r={},e=[];for(let t of n)r[t.id]||(r[t.id]=!0,e.push(t));return e}function kn(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ur(n){return Object.keys(n).filter(r=>n[r]!==void 0).map(r=>[r,n[r]]).reduce((r,e)=>(r[e[0]]=kn(e[1])?ur(e[1]):e[1],r),{})}function On(n){let r=[];for(let e of n)e.forEach(t=>r.push(t));return r}function wn(n){return c(this,null,function*(){let r=[];return RTCRtpReceiver.prototype.getStats?(r.push(...n.getReceivers().map(e=>e.getStats())),r.push(...n.getSenders().map(e=>e.getStats()))):r.push(n.getStats()),Promise.all(r).then(On).then(Dn)})}function xn(n){let r=n.filter(Ze("type","candidate-pair")).sort(An("priority")).find(Sa(Ze("nominated",!0),Ze("selected",!0)));if(!r)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let e={totalRoundTripTime:r.totalRoundTripTime||0,currentRoundTripTime:r.currentRoundTripTime||0,bytesSent:r.bytesSent,bytesReceived:r.bytesReceived},t=n.find(Ze("id",r.remoteCandidateId));t&&(e=Object.assign({},e,{remote:{type:t.candidateType,address:t.ip||t.address,port:t.port,protocol:t.protocol}}));let i=n.find(Ze("id",r.localCandidateId));return i&&(e=Object.assign({},e,{local:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol,relayProtocol:i.relayProtocol,networkType:i.networkType}})),ur(e)}function Ln(n,r){let e=Ti("id",n),t=n.filter(Sa(Ze("type","inbound-rtp"),Ze("type","outbound-rtp")));C.browserName()==="Firefox"&&(t=Object.values(t.reduce((a,s)=>{if(!a[s.ssrc])a[s.ssrc]=s;else{let o=Object.assign({},a[s.ssrc],s),l=a[s.ssrc].isRemote?s:a[s.ssrc];o.id=l.id,o.type=l.type,delete o.isRemote,delete o.remoteId,a[o.ssrc]=o}return a},{})));let i={};if(C.browserName()==="Safari"){let a=n.filter(Ze("type","track"));i=Ti("trackIdentifier",a)}return t.map(a=>{let s=Number(a.ssrc),o=a.mediaType||a.kind,l=a.trackId,u=a.type,g=a.codecId;if(C.browserName()==="Safari"){let b=/^.+_([\d]+)$/.exec(a.id);if(b&&(s=parseInt(b[1],10)),o=a.id.indexOf("Audio")>0?"audio":"video",r[s]){let D=o+"-"+r[s];i[D]&&(l=i[D].id)}}if(!u||!s||!o)return null;let T={ssrc:s,type:u,kind:o,bytesReceived:le(a,"bytesReceived"),bytesSent:le(a,"bytesSent"),jitter:le(a,"jitter"),packetsLost:le(a,"packetsLost"),packetsReceived:le(a,"packetsReceived"),packetsSent:le(a,"packetsSent"),fractionLost:le(a,"fractionLost"),pliCount:le(a,"pliCount"),firCount:le(a,"firCount"),nackCount:le(a,"nackCount"),userId:r[s]};if(o==="video"){let b=le(a,"framesDecoded"),D=le(a,"totalInterFrameDelay"),A=le(a,"totalSquaredInterFrameDelay");T.interframeDelayVariance=(A-D*D/b)/b}if(o==="audio"&&(T.totalSamplesReceived=le(a,"totalSamplesReceived"),T.concealedSamples=le(a,"concealedSamples"),T.insertedSamplesForDeceleration=le(a,"insertedSamplesForDeceleration"),T.removedSamplesForAcceleration=le(a,"removedSamplesForAcceleration"),T.silentConcealedSamples=le(a,"silentConcealedSamples"),T.concealmentEvents=le(a,"concealmentEvents"),T.totalAudioEnergy=le(a,"totalAudioEnergy")),g&&e[g]){let b=e[g];T.clockRate=b.clockRate,T.mimeType=b.mimeType}if(l&&e[l]){let b=e[l];T.frameHeight=b.frameHeight,T.frameWidth=b.frameWidth,T.framesDecoded=b.framesDecoded,T.framesReceived=b.framesReceived,T.framesDropped=b.framesDropped}return ur(T)}).filter(a=>!!a)}function Nn(n,r){if(!r||!r.rtps||!n.rtps)return n;let e=Ti("ssrc",n.rtps),t=Ti("ssrc",r.rtps),i=(n.timestamp-r.timestamp)/1e3;return!e||!t||Object.keys(e).forEach(a=>{let s=e[a],o=t[a];if(!(!s||!o)){if(s.bytesReceived&&s.bytesReceived>o.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-o.bytesReceived)/i)),s.bytesSent&&s.bytesSent>o.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-o.bytesSent)/i)),s.packetsReceived)if(s.packetsReceived>o.packetsReceived||s.packetsLost>o.packetsLost){let l=s.packetsLost-o.packetsLost,u=s.packetsReceived-o.packetsReceived;s.packetLoss=parseFloat((100*l/(l+u)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&o.framesDropped&&s.framesDropped>o.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-o.framesDropped)/i).toFixed(0)))}}),n}function $t(t,i){return c(this,arguments,function*(n,r,e={}){let a=yield wn(n),s={timestamp:Date.now(),transport:xn(a),rtps:Ln(a,e)};return r?Nn(s,r):(yield I.delay(Mn),$t(n,s,e))})}function pt(n){performance.clearMarks(n),performance.mark(n)}function Ri(n){let r=performance.getEntriesByName(n)[0];if(typeof r=="undefined")return null;let e=Math.round(performance.now()-r.startTime);return performance.clearMarks(n),e}function Ci(n){return`${v.SCREENSHARE_FIRST_FRAME}_${Un(n)}`}function Un(n){return typeof n=="string"?n:JSON.stringify(n)}var _=class extends ot{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 a={};typeof t!="undefined"&&(a.param=t),this._logInternal(e,a,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let a={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(a),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){_._instance||(_._instance=new _(e,t))}static log(e,t,i=!1){_._instance&&_._instance.log(e,t,i)}static logCustom(e,t,i=!1){_._instance&&_._instance.logCustom(e,t,i)}static logMeasure(e){let t=Ri(e);_._instance&&t!==null&&_._instance.logCustom(e,{param:t})}static destroy(){_._instance&&_._instance.destroy(),_._instance=null}};var Le=class{constructor(){this._worker=null}_createWorker(s,o){return c(this,arguments,function*(r,e,t=[],i={},a=[]){return new Promise((l,u)=>{let g=t.join(","),T=new Blob([r,`exports.default(${g});`],{type:"application/javascript; charset=utf-8"}),b=window.URL.createObjectURL(T);this._worker=new Worker(b),this._worker.onmessage=D=>{switch(D.data.type){case"ready":l();break;case"error":u(D.data.error);break;case"frame":e(D.data);break;case"debug":d.debug(D.data.message);break;case"log_error":_.log(v.ERROR,D.data.message);break}},this._sendToWorker("init",i,a)})})}_removeWorker(){var r;(r=this._worker)==null||r.terminate(),this._worker=null}_sendToWorker(r,e={},t=[]){var i;(i=this._worker)==null||i.postMessage(Object.assign({type:r},e),t)}static isBrowserSupported(){throw new Error("Not implemented")}};var ut=class extends Le{init(r){return c(this,null,function*(){d.debug("LibVPxDecoder started"),yield this._createWorker('"use strict";var exports=(()=>{var u=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var h=(a,t)=>{for(var e in t)u(a,e,{get:t[e],enumerable:!0})},D=(a,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of x(t))!M.call(a,s)&&s!==e&&u(a,s,{get:()=>t[s],enumerable:!(o=R(t,s))||o.enumerable});return a};var V=a=>D(u({},"__esModule",{value:!0}),a);var F={};h(F,{default:()=>A});var A=(a,t)=>{let e=null,o=null,s=!0;function m(){return a({locateFile:t}).then(r=>o=r)}function b(r,g,l,y,E){if(!o){self.postMessage({type:"log_error",message:"decoder-init-fail-libvpx"}),self.postMessage({type:"frame",error:"Fatal initialization error"});return}if(s!==l&&(s=l,e&&(e=null,self.postMessage({type:"debug",message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:"debug",message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new o.VpxDecoder,e.debug(E),!e.init(l?o.VpxType.VP9:o.VpxType.VP8))){e=null,self.postMessage({type:"frame",error:"Decoder failed to create"});return}try{e.allocateBuffer(g.byteLength).set(new Uint8Array(g))}catch(n){self.postMessage({type:"debug",message:n}),e=null,self.postMessage({type:"frame",error:String(n)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:"frame",error:"Decode failed"});return}let p=e.getImageBuffer();if(!p){self.postMessage({type:"frame",error:"No decoded data"});return}let d=e.getImageWidth(),c=e.getImageHeight();e.nextImage()&&(self.postMessage({type:"debug",message:"LibVPxDecoder dropped frame"}),self.postMessage({type:"log_error",message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(p.byteLength);if(i.set(p),y){let n=new ImageData(i,d,c);createImageBitmap(n,0,0,d,c).then(f=>{self.postMessage({type:"frame",data:f},[f]),f.close()})}else self.postMessage({type:"frame",data:i.buffer,width:d,height:c},[i.buffer])}m().then(()=>{self.onmessage=r=>{switch(r.data.type){case"frame":b(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:"ready"})}).catch(r=>{self.postMessage({type:"error",error:String(r)})})};return V(F);})();\n',e=>{if(e.error)d.warn("LibVPxDecoder",e.error);else if(e.data instanceof ArrayBuffer){let t=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);r(t)}else r(e.data)},[mr.default,mr.default.getUrl])})}decodeFrame(r,e,t,i){let a="ImageBitmap"in window;this._sendToWorker("frame",{timestamp:r,data:e.buffer,isVP9:t,keyFrame:i,useImageBitmap:a,debug:d.enabled()},[e.buffer])}destroy(){this._removeWorker(),d.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var je=class extends Le{init(r){return c(this,null,function*(){d.debug("WebCodecsDecoder started"),yield this._createWorker('"use strict";var exports=(()=>{var s=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var E=(o,e)=>{for(var t in e)s(o,t,{get:e[t],enumerable:!0})},g=(o,e,t,c)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of m(e))!b.call(o,r)&&r!==t&&s(o,r,{get:()=>e[r],enumerable:!(c=f(e,r))||c.enumerable});return o};var D=o=>g(s({},"__esModule",{value:!0}),o);var V={};E(V,{default:()=>R});var R=o=>{let e=null,t=!0;function c(){self.postMessage({type:"ready"})}function r(d,l,a,i=!1){if(!e||t!==a){if(!i){self.postMessage({type:"debug",message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}t=a,e?self.postMessage({type:"debug",message:`WebCodecsDecoder codec changed to ${a?"VP9":"VP8"}`}):(self.postMessage({type:"debug",message:`WebCodecsDecoder codec ${a?"VP9":"VP8"}`}),e=new VideoDecoder({output:n=>{let u=o?[n]:[];self.postMessage({type:"frame",data:n},u),n.close()},error:n=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:"frame",error:"WebCodecsDecoder failed, reinitialize: "+String(n)})}})),e.configure({codec:a?"vp09.00.50.08":"vp8"})}let p=new EncodedVideoChunk({type:i?"key":"delta",timestamp:d,data:l});e.decode(p)}self.onmessage=d=>{switch(d.data.type){case"init":c();break;case"frame":r(d.data.timestamp,d.data.data,d.data.isVP9,d.data.keyFrame);break}}};return D(V);})();\n',e=>{e.error?d.warn("WebCodecsDecoder",e.error):r(e.data)},[C.baseChromeVersion()>=92])})}decodeFrame(r,e,t,i=!1){this._sendToWorker("frame",{timestamp:r,data:e.buffer,isVP9:t,keyFrame:i},[e.buffer])}destroy(){this._removeWorker(),d.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window}};var va=require("bit-buffer");var Bn=65536,et=class{constructor(r,e){this._chunks=[];this._firstFrameReceived=!1;this._participantId=r,this._onStream=e}appendChunk(r){let e=this._chunks.length;if(r.start)e&&(d.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!e||(this._chunks[e-1].sequence+1)%Bn!==r.sequence){d.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(r),r.end){let t=this._processFrameData(),{width:i,height:a}=et.getFrameSize(t);if(this._processFrame({timestamp:r.timestamp,frameData:t,isVP9:r.isVP9,keyframe:r.keyframe,width:i,height:a}),!this._firstFrameReceived){this._firstFrameReceived=!0;let s=Ci(this._participantId),o=Ri(s);if(o===null)return;let l=Math.max(i,a),u=(()=>l>=1920?v.SCREENSHARE_FIRST_FRAME_LARGE:l>=1280?v.SCREENSHARE_FIRST_FRAME_MEDIUM:v.SCREENSHARE_FIRST_FRAME_SMALL)();_.logCustom(u,{param:o})}}}destroy(){this._chunks=[]}_processFrameData(){let r=this._chunks;this._chunks=[];let e=r.reduce((a,s)=>a+s.data.byteLength,0),t=new Uint8Array(e),i=0;for(let a of r)t.set(new Uint8Array(a.data),i),i+=a.data.byteLength;return t}static getFrameSize(r){let e={width:0,height:0},t=new va.BitStream(r.buffer);t.bigEndian=!0,t.index+=2;let i=t.readBits(1),s=t.readBits(1)<<1|i;return s===3&&t.index++,t.readBits(1)===1||t.readBits(1)!==0||(t.index++,t.index++,t.index+=24,s>=2&&t.index++,t.readBits(3)!==7?(t.index++,(s===1||s===3)&&(t.index+=3)):(s===1||s===3)&&t.index++,e.width=t.readBits(16)+1,e.height=t.readBits(16)+1),e}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var mt=class{constructor(r){this._onStream=r}drawFrame(r){return c(this,null,function*(){throw new Error("Method `drawFrame` is not supported by this implementation")})}drawImage(r){throw new Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var yt=class extends mt{constructor(e){super(e);this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;d.debug("CanvasRenderer started"),this._useImageBitmap="ImageBitmap"in window}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}drawFrame(e){return c(this,null,function*(){let t="createImageBitmap"in e?yield e.createImageBitmap():yield createImageBitmap(e);this.drawImage(t),t.close()})}drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}destroy(){this._removeStream(),d.debug("CanvasRenderer destroyed")}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(C.browserName()==="Safari"&&Number(C.browserVersion())===15)&&!(C.browserName()==="Firefox"&&Number(C.browserVersion())<60)}};var ht=class extends mt{constructor(e){super(e);d.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:"video"}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}drawFrame(e){return c(this,null,function*(){yield this._writer.write(e)})}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),d.debug("TrackGeneratorRenderer destroyed")}static isBrowserSupported(){return"VideoFrame"in window&&"MediaStreamTrackGenerator"in window&&je.isBrowserSupported()}};var bt=class extends et{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];d.debug(`StreamBuilder started for participant [${e}]`),ht.isBrowserSupported()?this._renderer=new ht(t):this._renderer=new yt(t),je.isBrowserSupported()?this._decoder=new je:this._decoder=new ut;let i=a=>c(this,null,function*(){"VideoFrame"in window&&a instanceof VideoFrame?yield this._renderer.drawFrame(a):this._renderer.drawImage(a)});this._decoder.init(i).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._renderer.destroy(),d.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return yt.isBrowserSupported()||ht.isBrowserSupported()}};function Ea(n,r,e,t,i,a,s){let o=0;r&&(o|=1),e&&(o|=2),t&&(o|=4),s||(o|=8);let l=new ArrayBuffer(11),u=new DataView(l);if(u.setUint8(0,1),u.setUint16(1,i),u.setUint32(3,n),u.setUint8(7,a?1:0),u.setUint16(8,0),u.setUint8(10,o),!s)return l;let g=new Uint8Array(l.byteLength+s.byteLength);return g.set(new Uint8Array(l),0),g.set(new Uint8Array(s),l.byteLength),g.buffer}function Ia(n){let r=new DataView(n),e=r.getUint8(0),t=r.getUint16(1),i=r.getUint32(3),a=r.getUint8(7)===1,s=r.getUint16(8),o=r.getUint8(10),l=!!(o&1),u=!!(o&2),g=!!(o&4),T=!!(o&8);if(e!==1)throw new Error(`Unexpected protocol version. Got ${e}, expected 1`);return{timestamp:i,start:l,end:u,keyframe:g,sequence:t,isVP9:a,ssrc:s,eos:T,data:n.slice(11)}}function Ta(n){if(!n||!n.byteLength||n.byteLength!==4)return!1;let r=new DataView(n);return!(r.getUint8(0)!==1||r.getUint8(1)!==1||r.getUint16(2)!==0)}function Ra(n){if(!n||!n.byteLength||n.byteLength!==10)return null;let r=new DataView(n);if(r.getUint8(0)!==1||r.getUint8(1)!==2||r.getUint16(2)!==0)return null;let a=r.getUint16(4),s=r.getUint32(6);return{seq:a,ts2:s}}var P=si(require("simple-ebml-builder"));var Fn=xr(2,15)-1,hr=1,Vn=5,jn=5;var qt=class{constructor(r){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=r;let e=()=>{this._mediaSource.removeEventListener("sourceopen",e),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",e,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let t=this._sourceBuffer.buffered.start(0);t<this._clearBufferTill&&(this._sourceBuffer.remove(t,this._clearBufferTill),d.debug(`[WebmBuilder] SourceBuffer cleanup from ${t} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let r=this._queue;this._queue=[];let e=qt._buildQueue(r);this._sourceBuffer.appendBuffer(e)}static _buildQueue(r){if(r.length){if(r.length===1)return P.build(r[0])}else return new Uint8Array;let e=r.reduce((a,s)=>a+s.countSize(),0),t=new Uint8Array(e),i=0;for(let a of r){let s=P.build(a);t.set(s,i),i+=s.byteLength}return t}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(r){var e;return this._codec=r,(e=this._sourceBuffer)==null?void 0:e.changeType(r)}append(r,e=!1){this._queue.push(r),e&&this._handleQueue()}cleanup(){var a,s,o;((a=this._mediaSource)==null?void 0:a.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let r=(o=this._sourceBuffer)==null?void 0:o.buffered,e=r==null?void 0:r.length;if(!e)return;let t=r.start(0),i=Math.max(0,r.end(e-1)-Vn);i-t>jn&&(this._clearBufferTill=i)}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 r;return(r=this._sourceBuffer)==null?void 0:r.buffered}},ye=class extends et{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;d.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return P.element(P.ID.EBML,[P.element(P.ID.EBMLVersion,P.number(1)),P.element(P.ID.EBMLReadVersion,P.number(1)),P.element(P.ID.EBMLMaxIDLength,P.number(4)),P.element(P.ID.EBMLMaxSizeLength,P.number(8)),P.element(P.ID.DocType,P.string("webm")),P.element(P.ID.DocTypeVersion,P.number(2)),P.element(P.ID.DocTypeReadVersion,P.number(2))])}static _genSegmentHeader(e,t,i){let a=P.element(P.ID.Info,[P.element(P.ID.TimecodeScale,P.number(1e6)),P.element(P.ID.MuxingApp,P.string("vk-webm-builder")),P.element(P.ID.WritingApp,P.string("vk-webm-builder"))]),s=[P.element(P.ID.PixelWidth,P.number(e)),P.element(P.ID.PixelHeight,P.number(t))],o=P.element(P.ID.Tracks,P.element(P.ID.TrackEntry,[P.element(P.ID.TrackNumber,P.number(hr)),P.element(P.ID.TrackUID,P.number(hr)),P.element(P.ID.TrackType,P.number(1)),P.element(P.ID.FlagLacing,P.number(0)),P.element(P.ID.DefaultDuration,P.number(1e9)),P.element(P.ID.CodecID,P.string(`V_${i.toUpperCase()}`)),P.element(P.ID.Video,s)]));return P.unknownSizeElement(P.ID.Segment,[a,o])}static _genClusterHeader(e){return P.unknownSizeElement(P.ID.Cluster,[P.element(P.ID.Timecode,P.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new qt(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){d.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=()=>d.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,d.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),d.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let o=ye._genWebmHeader();this._mediaBuffer.append(o);let l=ye._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(l)}let a=Math.round(i-this._clusterStartTime);if(a>Fn&&(this._clusterStartTime=i,a=0),a===0){d.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let o=ye._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(o)}let s=P.element(P.ID.SimpleBlock,[P.vintEncodedNumber(hr),P.bytes(ye._intToU16BE(a)),P.number((e.keyframe?1:0)<<7),P.bytes(e.frameData)]);this._mediaBuffer.append(s,!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),d.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var _t=class{constructor(r,e,t,i){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};d.debug("ScreenCaptureReceiver started"),this._datachannel=r,this._participantIdRegistry=e,this._onStream=t,this._onEos=i,this._datachannel.onmessage=a=>this._onDataChannelMessage(a.data)}_onDataChannelMessage(r){var a,s;let e=Ia(r),t=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(e.ssrc))==null?void 0:s.participantId;if(!t){d.warn(`Participant id for ssrc ${e.ssrc} not found in registry`);return}if(e.eos){this.close(t),this._onEos(t);return}let i=this._streamBuilders[t];if(!i){let o=l=>this._onStream(t,l);p.screenShareWebmBuilder&&ye.isBrowserSupported()?i=new ye(t,o):i=new bt(t,o),this._streamBuilders[t]=i}i.appendChunk(e)}close(r){let e=this._streamBuilders[r];e&&(e.destroy(),delete this._streamBuilders[r])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(r=>r.destroy()),this._streamBuilders={},this._participantIdRegistry=null,d.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(je.isBrowserSupported()||ut.isBrowserSupported())&&(bt.isBrowserSupported()||ye.isBrowserSupported())}};var _r=si(require("@vkontakte/libvpx"));var Hn=1e3,Mt=class extends Le{constructor(e,t,i,a){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._useCongestionControl=i,this._maxBitrate=a,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return c(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let a=this._video;a.srcObject=new MediaStream([e]),a.onloadeddata=l=>t(),a.onerror=()=>i(new Error("Video element error"));let s=a.play(),o=()=>i(new Error("Autoplay is disabled"));s?s.catch(o):o()}})})}_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");this._video.paused&&this._video.play();let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return c(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var a;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(),(a=this._canvasCtx)==null?void 0:a.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return c(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;d.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`"use strict";var exports=(()=>{var b=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var V=(a,r)=>{for(var s in r)b(a,s,{get:r[s],enumerable:!0})},h=(a,r,s,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of x(r))!y.call(a,e)&&e!==s&&b(a,e,{get:()=>r[e],enumerable:!(i=R(r,e))||i.enumerable});return a};var M=a=>h(b({},"__esModule",{value:!0}),a);var F={};V(F,{default:()=>A});var A=(a,r,s,i)=>{let e;function m(t,o){return a({locateFile:r}).then(n=>{if(e=new n.VpxEncoder,e.debug(o),!e.init(t?n.VpxType.VP9:n.VpxType.VP8))throw self.postMessage({type:"log_error",message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");if(s){let d=Math.round(i/1e3);e.setTargetBitrate(d)}else e.setMaxQuantizer(10),e.setTargetBitrate(1024)})}function E(t,o,n,p){let d=e.allocateImage(t,o);if(!d){self.postMessage({type:"frame",error:"No buffer data"});return}d.set(new Uint8Array(n));let f=Math.round(performance.now()),u=150;if(!e.encode(f,u,p)){self.postMessage({type:"frame",error:"Encode failed"});return}let c=e.readFrame();if(!c){self.postMessage({type:"frame",error:"No encoded data"});return}e.readFrame()&&(self.postMessage({type:"debug",message:"LibVPxEncoder dropped frame"}),self.postMessage({type:"log_error",message:"LibVPxEncoder-drop"}));let l=new Uint8Array(c.byteLength);l.set(c),self.postMessage({type:"frame",frameType:p?"key":"delta",timestamp:f,duration:u,width:t,height:o,data:l.buffer},[l.buffer])}function g(t,o){let n=Math.round(t/1e3);e.setTargetBitrate(n)}self.onmessage=t=>{switch(t.data.type){case"init":m(t.data.isVP9,t.data.debug).then(()=>self.postMessage({type:"ready"})).catch(o=>self.postMessage({type:"error",error:String(o)}));break;case"frame":E(t.data.width,t.data.height,t.data.imageData,t.data.keyFrame);break;case"set_bitrate":g(t.data.bitrate,t.data.useCbr);break}}};return M(F);})();
10
- `,i=>{var a;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(a=i.data)==null?void 0:a.byteLength,width:i.width,height:i.height})},[_r.default,_r.default.getUrl,this._useCongestionControl,this._maxBitrate],{isVP9:this.isVP9(),debug:d.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker("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)},Hn),this._getFrameBitmap().then(t=>{var a;window.clearTimeout(this._frameReadTimeout),(a=this._lastFrame)==null||a.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)}setBitrate(e,t=!1){this._sendToWorker("set_bitrate",{bitrate:e,useCbr:t})}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),d.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var gt=class extends Le{constructor(e,t,i,a,s,o){super();this._sourceTrack=e,this._onFrame=t,this._useCongestionControl=i,this._maxBitrate=a,this._useCbr=s,this._frameRate=o,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return c(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;d.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`"use strict";var exports=(()=>{var b=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var _=(a,t)=>{for(var n in t)b(a,n,{get:t[n],enumerable:!0})},x=(a,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of T(t))!B.call(a,r)&&r!==n&&b(a,r,{get:()=>t[r],enumerable:!(i=C(t,r))||i.enumerable});return a};var I=a=>x(b({},"__esModule",{value:!0}),a);var O={};_(O,{default:()=>M});var M=()=>{let t,n,i,r,R,E,l=null,p=0,s=!1,d=0,g,V,c=!1;function h(e){t=e.readable,n=t.getReader(),i=e.width,r=e.height,R=e.isVP9,E=e.framerate,g=e.useCongestionControl,V=e.maxBitrate,g&&(d=V,c=e.useCbr),u(),self.postMessage({type:"ready"})}function y(e){p=self.setTimeout(()=>{l&&A(l,e)},1e3),!s&&(s=!0,n.read().finally(()=>{s=!1,self.clearTimeout(p)}).then(({done:o,value:m})=>{if(l==null||l.close(),l=null,!(o||!m)){if(!f){n.releaseLock(),t.cancel();return}l=m,A(m,e)}}))}function A(e,o){(e.codedWidth!==i||e.codedHeight!==r)&&(i=e.codedWidth,r=e.codedHeight,u()),f.encode(e,{keyFrame:o})}function u(){let e={framerate:E,codec:R?"vp09.00.50.08":"vp8",width:i,height:r,latencyMode:"realtime",bitrateMode:c?"constant":"variable"};d>0&&(e.bitrate=d),f.configure(e)}function F(e,o=!1){d=e,c=o,u()}let f=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:"frame",frameType:e.type,timestamp:e.timestamp,duration:e.duration,width:i,height:r,data:o},[o])},error:e=>{self.postMessage({type:"frame",error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case"init":h(e.data);break;case"frame":y(e.data.keyFrame);break;case"set_bitrate":F(e.data.bitrate,e.data.useCbr);break}}};return I(O);})();
11
- `,a=>{var s;a.error?this._onFrame(null,a.error):this._onFrame({type:a.frameType,timestamp:a.timestamp,duration:a.duration,data:a.data,byteLength:(s=a.data)==null?void 0:s.byteLength,width:a.width,height:a.height})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:this._frameRate,useCongestionControl:this._useCongestionControl,maxBitrate:this._maxBitrate,useCbr:this._useCbr},[i])})}requestFrame(e=!1){this._sendToWorker("frame",{keyFrame:e})}setBitrate(e,t){this._sendToWorker("set_bitrate",{bitrate:e,useCbr:t})}isVP9(){return!0}destroy(){this._removeWorker(),d.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var Gn=1.2,Ca=.8,Wn=2e3,Kn=8e3,gr=8e3,$n=16e3,qn=4,Jn=2e3,yi=(t=>(t[t.NONE=0]="NONE",t[t.UP=1]="UP",t[t.DOWN=2]="DOWN",t))(yi||{}),Jt=class{constructor(r,e,t,i,a){this._upPenalty=0;this._delayAvgShort=-1;this._delayAvgLong=-1;this._minDelay=Number.MAX_VALUE;this._maxDelay=0;this._largeDelayDuration=0;this._onCongestion=r,this._ccEnabled=i,this._minBitrate=e,this._maxBitrate=t,this._fastSharing=a,this._targetBitrate=this._maxBitrate,this._probing=!1;let s=Date.now();this._lastDown=0,this._lastUp=s,this._lastProbing=s,this._lastCheckDelay=0}checkDelay(r,e,t){let i=Date.now();if(this._calcDelay(e,i),this._delayAvgShort<=0||this._delayAvgLong<=0||!this._ccEnabled)return;let a=0,s=this._delayAvgShort-this._delayAvgLong,o=Math.round(Math.abs(s)*100/this._delayAvgLong),l=this._fastSharing?200:700,u=s>40&&o>30&&this._delayAvgShort>l,g=this._delayAvgShort>2e3;u||g?a=2:Math.abs(s)<40&&o<10&&this._delayAvgShort<2e3&&(a=1);let T=Math.round(this._targetBitrate/1e3),b=t;r%10===0&&d.debug(`#${r}: cc: delay=${e} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${o} -> ${yi[a]} tr=${T} br=${t}`);let D=i-this._lastDown;if(a===2&&D>Wn){this._probing&&(this._upPenalty=Math.min(++this._upPenalty,qn),this._probing=!1);let W=Ca*b*1e3;if(W>=this._targetBitrate&&(W=this._targetBitrate*Ca),W=Math.max(W,this._minBitrate),W<this._targetBitrate){let ee=Math.round(W/1e3),ue=Math.round(this._upPenalty*gr/1e3);d.log(`#${r}: cc: delay=${e} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${o} -> ${yi[a]}`),d.log(`#${r}: cc: DOWN delay=${e} bitrate=${b} target=${T} -> newBitrate=${ee} penalty=${ue}s`),this._setBitrate(W,!0),this._targetBitrate=W}this._lastDown=i}let A=i-this._lastUp,Y=Kn+this._upPenalty*gr;if(a===1&&A>Y&&D>Y){let W=Math.min(this._targetBitrate*Gn,this._maxBitrate);if(W>this._targetBitrate){let ee=Math.round(W/1e3),ue=Math.round(this._targetBitrate/1e3),Se=Math.round(this._upPenalty*gr/1e3);d.log(`#${r}: cc: delay=${e} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${o} -> ${yi[a]}`),d.log(`#${r}: cc: UP bitrate=${b} target=${ue} -> newBitrate=${ee} penalty=${Se}s`),this._setBitrate(W,!1),this._targetBitrate=W,this._probing=!0,this._lastProbing=i,this._lastUp=i}}let H=i-this._lastProbing;this._probing&&H>$n&&(this._probing=!1);let ge=i-this._lastDown;this._upPenalty>0&&ge>3*Y&&(d.log(`#${r}: cc: UP reset penalty: oldPenalty=${this._upPenalty}`),this._upPenalty=0)}_setBitrate(r,e){this._fastSharing&&(e=!0),this._onCongestion(r,e)}_calcDelay(r,e){if(!(r<=0)){if(this._delayAvgShort===-1&&(this._delayAvgShort=r,this._delayAvgLong=r),this._delayAvgShort=Math.round((this._delayAvgShort*3+r)/4),this._delayAvgLong=Math.round((this._delayAvgLong*23+r)/24),r>0&&r<this._minDelay?this._minDelay=r:r>this._maxDelay&&(this._maxDelay=r),this._lastCheckDelay===0&&(this._lastCheckDelay=e),r>Jn){let t=e-this._lastCheckDelay;this._largeDelayDuration+=t}this._lastCheckDelay=e}}reconfigure(r,e){this._minBitrate=r,this._maxBitrate=e}getStat(){if(this._minDelay===Number.MAX_VALUE||this._maxDelay===0||this._delayAvgLong<=0)return null;let r={minDelay:this._minDelay,maxDelay:this._maxDelay,avgDelay:this._delayAvgLong,largeDelayDuration:this._largeDelayDuration};return this._minDelay=Number.MAX_VALUE,this._maxDelay=0,this._largeDelayDuration=0,r}};var zt=class{constructor(r){this._size=0;this._head=0;this._tail=0;this._maxSize=r,this._buffer=new Array(r)}add(r,e,t,i,a){this._tail===this._head&&this._size>0&&(this._head=++this._head%this._maxSize);let s=this._tail;return this._buffer[this._tail]={seq:r,ts:e,size:t,sent:Date.now(),start:i,end:a,ts2:-1,recv:-1},this._tail=++this._tail%this._maxSize,this._size++,s}update(r,e){let t=this.get(r);return t===null?null:(t.ts2=e,t.recv=Date.now(),t)}get(r){let e=this._head;for(let t=0;t<this._maxSize;t++){if(r===this._buffer[e].seq)return this._buffer[e];if(e=++e%this._maxSize,e===this._tail)break}return null}getServerBitrateK(r){let e=0,t=0,i=-1,a=-1,s=this._tail;for(let o=0;o<this._maxSize;o++){s>0?--s:s=this._maxSize-1;let l=this._buffer[s];if(l===null||(a===-1&&(a=l.ts2,t=0),a>=0&&(t+=l.size),i=l.ts2,a-i>=r)||s===this._head)break}if(i>=0&&a>=0){let o=a-i;e=Math.round(o>0?t*8/o:0)}return e}getCurrentDelay(){let r=this._tail;for(let e=0;e<this._maxSize;e++){r>0?--r:r=this._maxSize-1;let t=this._buffer[r];if(t===null)break;if(t.recv>=0&&t.sent>=0)return t.recv-t.sent;if(r===this._head)break}return 0}getMaxBandwidth(){let r=0,e=0,t=-1,i=-1,a=this._tail;for(let s=0;s<this._maxSize;s++){if(a>0?--a:a=this._maxSize-1,i===-1&&this._buffer[a].end&&!this._buffer[a].start&&(i=this._buffer[a].ts2,e=0),t===-1&&i>=0&&this._buffer[a].start&&!this._buffer[a].end&&(t=this._buffer[a].ts2),t>=0&&i>=0){let o=i-t;r=o>0?e*8/o:0;break}if(i>=0&&(e+=this._buffer[a].size),a===this._head)break}return Math.round(r)}};var Yn=65536,Qn=50,Xn=400,Zn=1e6,es=3e4,bi=0,ft=class{constructor(r,e,t,i){this._destroyed=!1;this._needKeyframe=!0;this._frameNum=0;this._feedback=new zt(1024);this._lastSharingStat=Date.now();this._congestionControlEnabled=!1;d.debug("ScreenCaptureSender started"),this.DATA_SIZE=p.consumerScreenDataChannelPacketSize-11,this._datachannel=e,this._signaling=t,this._fastSharing=i,this._congestionControlEnabled=p.screenShareCongestionControl||this._fastSharing,this._width=r.getSettings().width,this._height=r.getSettings().height;let{minBitrate:a,maxBitrate:s}=this._calcMinMaxBitrate(this._width,this._height),o=this._onCongestionCallback.bind(this);d.log(`ScreenCaptureSender: CongestionControl: enabled=${this._congestionControlEnabled} minBitrate=${Math.round(a/1e3)}k maxBitrate=${Math.round(s/1e3)}k`),this._congestionControl=new Jt(o,a,s,this._congestionControlEnabled,this._fastSharing);let l=(u,g)=>{if(!this._destroyed){if(!u){d.warn("requestFrame failed, keyFrame: "+this._needKeyframe,g),this._needKeyframe=!0,this._requestFrame();return}(u.width!==this._width||u.height!==this._height)&&(this._width=u.width,this._height=u.height,this._onResize(this._width,this._height)),this._send(u).catch(T=>{d.warn("sendFrame failed",T),this._needKeyframe=!0}).finally(()=>{this._frameNum++,u.type==="key"&&d.debug(`#${this._frameNum}: sharing: send keyframe size=${Math.round(u.byteLength/1e3)}k`);let T=this._feedback.getCurrentDelay(),b=this._feedback.getServerBitrateK(2e3);T>0&&this._congestionControl.checkDelay(this._frameNum,T,b),this._requestFrame()}),this._sendSharingStat()}};if(gt.isBrowserSupported()){let u=this._fastSharing,g=p.getScreenFrameRate(this._fastSharing);this._encoder=new gt(r,l,this._congestionControlEnabled,s,u,g)}else this._encoder=new Mt(r,l,this._congestionControlEnabled,s);this._datachannel.onmessage=u=>{Ta(u.data)&&(d.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0);let g=Ra(u.data);g!==null&&this._checkCcFeedback(g)},this._encoder.init().then(()=>this._requestFrame()).catch(u=>d.warn("ScreenCaptureSender init failed",u))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(r,e,t,i,a){let s=Ea(r,e,t,i,bi,this._encoder.isVP9(),a);return bi=(bi+1)%Yn,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(r){return c(this,null,function*(){return new Promise((e,t)=>{this._sendChunk(r,0,e,t)})})}_sendChunk(r,e,t,i){if(!this._datachannel||this._datachannel.readyState!=="open"){i();return}let a=r.data.slice(e,e+this.DATA_SIZE),s=r.data.byteLength<=e+a.byteLength;this._feedback.add(bi,r.timestamp,a.byteLength,!e,s);let o=this._wrapHeader(r.timestamp,!e,s,r.type==="key",a);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&t()}:null;try{this._datachannel.send(o)}catch(l){d.warn("Error send data to DataChannel",l),i();return}s||I.setImmediate(()=>this._sendChunk(r,e+this.DATA_SIZE,t,i))}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),d.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return gt.isBrowserSupported()||Mt.isBrowserSupported()}_onCongestionCallback(r,e){this._encoder.setBitrate(r,e)}_onResize(r,e){let{minBitrate:t,maxBitrate:i}=this._calcMinMaxBitrate(r,e),a=Math.round(t/1e3),s=Math.round(i/1e3);d.log(`cc: resize to ${r}x${e}, minBitrate=${a} maxBitrate=${s}`),this._congestionControl.reconfigure(t,i)}_calcMinMaxBitrate(r,e){(r===void 0||r<640)&&(r=640),(e===void 0||e<360)&&(e=360);let t=r*e/256,i=Math.min(Zn,Math.round(t*Qn)),a=Math.round(t*Xn);return{minBitrate:i,maxBitrate:a}}_checkCcFeedback(r){this._feedback.update(r.seq,r.ts2)===null&&d.debug(`cc: update failed, seq=${r.seq}`)}_sendSharingStat(){let r=Date.now();if(r-this._lastSharingStat>es){let t=this._congestionControl.getStat();t!==null&&(d.debug(`cc: send stats: ${JSON.stringify(t)}`),this._signaling.reportSharingStat(t)),this._lastSharingStat=r}}};var ae=class{static get sessionKey(){return ae._sessionKey}static set sessionKey(r){ae._sessionKey=r}static get sessionSecretKey(){return ae._sessionSecretKey}static set sessionSecretKey(r){ae._sessionSecretKey=r}static get accessToken(){return ae._accessToken}static set accessToken(r){ae._accessToken=r}static isEmpty(){return!ae._sessionKey||!ae._sessionSecretKey}};var S=class{static set(r){r.hasOwnProperty("voiceParams")&&(Object.assign(S._params.voiceParams,r.voiceParams),delete r.voiceParams),r.hasOwnProperty("specListenerParams")&&(Object.assign(S._params.specListenerParams,r.specListenerParams),delete r.specListenerParams),r.hasOwnProperty("apiAuth")&&(ae.accessToken=r.apiAuth.accessToken,ae.sessionKey=r.apiAuth.sessionKey,ae.sessionSecretKey=r.apiAuth.sessionSecretKey),r.hasOwnProperty("api")&&(Object.assign(S._params.api,r.api),delete r.api),Object.assign(S._params,I.objectFilterOutValues(r,void 0))}static get(r){return S._params[r]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.7.2-beta.8"}static get debug(){}static get protocolVersion(){return S._params.joinFromMultipleDevices?6:5}static get platform(){return S._params.platform}static set platform(r){S._params.platform=r}static get clientType(){return S._params.clientType}static set clientType(r){S._params.clientType=r}static get externalUserType(){return S._params.externalUserType}static set externalUserType(r){S._params.externalUserType=r}static get device(){return S._params.device}static get apiKey(){return S._params.apiKey}static get apiEnv(){return S._params.apiEnv}static get apiEndpoint(){switch(S.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return S._params.apiEnv}}static get authToken(){return S._params.authToken}static set authToken(r){S._params.authToken=r}static get anonymToken(){return S._params.anonymToken}static set anonymToken(r){S._params.anonymToken=r}static get domain(){return S._params.domain}static get externalDomain(){return S._params.externalDomain}static get iceServers(){return S._params.iceServers}static set iceServers(r){S._params.iceServers=r}static get wssBase(){return S._params.wssBase}static set wssBase(r){S._params.wssBase=r}static get wssToken(){return S._params.wssToken}static set wssToken(r){S._params.wssToken=r}static get signalingReconnectDelay(){return S._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return S._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return S._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return S._params.waitConnectionDelay}static get waitResponseDelay(){return S._params.waitResponseDelay}static get waitMessageDelay(){return S._params.waitMessageDelay}static get waitAnotherTabDelay(){return S._params.waitAnotherTabDelay}static get debugLog(){return S._params.debugLog}static get forceRelayPolicy(){return S._params.forceRelayPolicy}static set forceRelayPolicy(r){S._params.forceRelayPolicy=r}static get videoMinWidth(){return S._params.videoMinWidth}static get videoMaxWidth(){return S._params.videoMaxWidth}static set videoMaxWidth(r){S._params.videoMaxWidth=r}static get videoMinHeight(){return S._params.videoMinHeight}static get videoMaxHeight(){return S._params.videoMaxHeight}static set videoMaxHeight(r){S._params.videoMaxHeight=r}static get videoAspectRatio(){return S._params.videoAspectRatio}static get videoFrameRate(){return S._params.videoFrameRate}static get videoFacingMode(){return S._params.videoFacingMode||(C.isMobile()?"user":null)}static set videoFacingMode(r){S._params.videoFacingMode=r}static get displaySurface(){return S._params.displaySurface}static get videoEffects(){return S._params.videoEffects}static set videoEffects(r){S._params.videoEffects=r}static get videoEffectMaxWidth(){return S._params.videoEffectMaxWidth}static set videoEffectMaxWidth(r){S._params.videoEffectMaxWidth=r}static get videoEffectMaxHeight(){return S._params.videoEffectMaxHeight}static set videoEffectMaxHeight(r){S._params.videoEffectMaxHeight=r}static get useVmoji(){var r;return((r=S._params.vmoji)==null?void 0:r.isBrowserSupported())||!1}static get vmoji(){return S._params.vmoji}static set vmoji(r){S._params.vmoji=r}static get voiceParams(){return S._params.voiceParams}static get specListenerParams(){return S._params.specListenerParams}static get iceRestartWaitTime(){return S._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return S._params.transportConnectionWaitTime}static get statisticsInterval(){return S._params.statisticsInterval}static set statisticsInterval(r){S._params.statisticsInterval=r}static get networkStatisticsInterval(){return S._params.networkStatisticsInterval}static get perfStatReportEnabled(){return S._params.perfStatReportEnabled}static get callStatReportEnabled(){return S._params.callStatReportEnabled}static get producerNotificationDataChannel(){return S._params.producerNotificationDataChannel}static get producerCommandDataChannel(){return S._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return S._params.consumerScreenDataChannel&&ft.isBrowserSupported()}static get producerScreenDataChannel(){return S._params.producerScreenDataChannel&&S.producerNotificationDataChannel&&_t.isBrowserSupported()}static get asrDataChannel(){return S._params.asrDataChannel&&S.producerNotificationDataChannel}static get consumerScreenDataChannelPacketSize(){return S._params.consumerScreenDataChannelPacketSize}static get screenShareWebmBuilder(){return S._params.screenShareWebmBuilder}static get noiseSuppression(){return S._params.noiseSuppression}static set noiseSuppression(r){S._params.noiseSuppression=r}static get preferH264(){return S._params.preferH264}static get preferVP9(){return S._params.preferVP9}static get audioNack(){return S._params.audioNack}static get consumerScreenTrack(){return S._params.consumerScreenTrack&&S.consumerScreenDataChannel}static get producerScreenTrack(){return S._params.producerScreenTrack}static get movieShare(){return S._params.movieShare&&S.videoTracksCount>0}static get videoTracksCount(){return S.producerNotificationDataChannel?S._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return S._params.breakVideoPayloadTypes}static get filteredMessages(){return S._params.filteredMessages}static get useParticipantListChunk(){return S._params.useParticipantListChunk&&S._params.videoTracksCount>0}static get useRooms(){return S._params.useRooms}static get participantListChunkInitIndex(){var r;return(r=S._params.participantListChunkInitIndex)!=null?r:0}static get participantListChunkInitCount(){var r;return(r=S._params.participantListChunkInitCount)!=null?r:null}static get serverAudioRed(){return S._params.serverAudioRed&&C.canPreferRed()}static get p2pAudioRed(){return S._params.p2pAudioRed&&C.canPreferRed()}static get h264spsPpsIdrInKeyframe(){return S._params.h264spsPpsIdrInKeyframe}static get batchParticipantsOnStart(){return S._params.batchParticipantsOnStart}static get filterObservers(){return S._params.filterObservers}static get muteMode(){return S._params.muteMode}static get preserveAudioTracks(){return S._params.preserveAudioTracks}static get audioShare(){return C.isAudioShareSupported()&&S._params.audioShare}static get fastScreenShare(){return S._params.fastScreenShare}static get screenShareCongestionControl(){return S._params.screenShareCongestionControl}static get api(){return S._params.api}static get fastScreenShareWidth(){return S._params.fastScreenShareWidth}static get fastScreenShareHeight(){return S._params.fastScreenShareHeight}static getScreenFrameRate(r){return r?S._params.fastScreenShareFrameRate:S._params.screenFrameRate}},p=S;p._params={platform:"WEB",clientType:"PORTAL",externalUserType:"",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",externalDomain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoFacingMode:null,displaySurface:"monitor",videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,vmoji:null,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,asrDataChannel:!1,consumerScreenDataChannelPacketSize:64*1024,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,useParticipantListChunk:!1,useRooms:!1,participantListChunkInitIndex:0,participantListChunkInitCount:null,serverAudioRed:!1,p2pAudioRed:!1,h264spsPpsIdrInKeyframe:!0,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1,audioShare:!1,fastScreenShare:!1,screenShareCongestionControl:!1,api:{userIdsByOkBatchedTimeout:1e3},fastScreenShareFrameRate:24,fastScreenShareWidth:1280,fastScreenShareHeight:720};var Mi=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))(Mi||{});function V(n,...r){let e=p.get(n);e&&setTimeout(e,0,...r)}function ce(n,r,...e){if(p.filterObservers){if(Array.isArray(r)){if(r=r.filter(t=>!t.observer),!r.length)return}else if(r.observer)return}V(n,r,...e)}function Ie(n){return Object.assign({},n)}function St(n){return n.slice()}var fr;(ac=>{function n(h,y){V("onLocalStream",h,Ie(y))}ac.onLocalStream=n;function r(h,y){V("onScreenStream",h,Ie(y))}ac.onScreenStream=r;function e(h,y){V("onVmojiStream",h,Ie(y))}ac.onVmojiStream=e;function t(h,y){V("onLocalStreamUpdate",Ie(h),y)}ac.onLocalStreamUpdate=t;function i(h){V("onLocalStatus",h)}ac.onLocalStatus=i;function a(h,y){ce("onRemoteStream",h,y)}ac.onRemoteStream=a;function s(h,y){ce("onRemoteLive",h,y)}ac.onRemoteLive=s;function o(h,y){ce("onLocalLive",h,y)}ac.onLocalLive=o;function l(h,y){ce("onRemoteLiveUpdate",h,y)}ac.onRemoteLiveUpdate=l;function u(h,y){ce("onLocalLiveUpdate",h,y)}ac.onLocalLiveUpdate=u;function g(h,y){ce("onRemoteScreenStream",h,y)}ac.onRemoteScreenStream=g;function T(h,y){ce("onRemoteVmojiStream",h,y)}ac.onRemoteVmojiStream=T;function b(h,y,Z,We,Vt){ce("onConversation",h,Ie(y),Ie(Z),We,Vt)}ac.onConversation=b;function D(h){h&&V("onConversationParticipantListChunk",h)}ac.onConversationParticipantListChunk=D;function A(h,y,Z){ce("onRemoteMediaSettings",h,Ie(y),Z)}ac.onRemoteMediaSettings=A;function Y(h,y){ce("onLocalMediaSettings",h,Ie(y))}ac.onLocalMediaSettings=Y;function H(h,y){ce("onRemoteSharedMovieInfo",h,Ie(y))}ac.onRemoteSharedMovieInfo=H;function ge(h,y){ce("onRemoteSharedMovieStoppedInfo",h,Ie(y))}ac.onRemoteSharedMovieStoppedInfo=ge;function W(h,y){ce("onLocalSharedMovieInfo",h,Ie(y))}ac.onLocalSharedMovieInfo=W;function ee(h,y){ce("onLocalSharedMovieStoppedInfo",h,Ie(y))}ac.onLocalSharedMovieStoppedInfo=ee;function ue(h,y){ce("onParticipantAdded",h,y)}ac.onParticipantAdded=ue;function Se(h,y){ce("onParticipantJoined",h,y)}ac.onParticipantJoined=Se;function nt(h,y,Z){ce("onRemoteParticipantState",h,Ie(y),Z)}ac.onRemoteParticipantState=nt;function ni(h,y,Z=null){ce("onRemoteStatus",h,y,Z)}ac.onRemoteStatus=ni;function Q(h,y,Z=null){ce("onParticipantStatus",h,y,Z)}ac.onParticipantStatus=Q;function yr(){V("onPermissionsRequested")}ac.onPermissionsRequested=yr;function br(h,y){V("onPermissionsError",h,y)}ac.onPermissionsError=br;function Mr(h,y){ce("onRemoteRemoved",h,y)}ac.onRemoteRemoved=Mr;function Ar(h,y,Z){V("onCallState",h,y,Ie(Z))}ac.onCallState=Ar;function Gi(h,y){V("onDeviceSwitched",h,y)}ac.onDeviceSwitched=Gi;function Wi(h,y,Z,We=!1,Vt=!1,$i=null,qi=null,tn,Dr,rn=null){let an=Dr?St(Dr):void 0;V("onMuteStates",Ie(h),St(y),St(Z),We,Vt,$i,qi,tn,an,rn)}ac.onMuteStates=Wi;function Ki(h,y){ce("onRolesChanged",h,St(y))}ac.onRolesChanged=Ki;function E(h){V("onLocalRolesChanged",St(h))}ac.onLocalRolesChanged=E;function R(h,y,Z){ce("onPinnedParticipant",h,y,Z)}ac.onPinnedParticipant=R;function M(h){V("onLocalPin",h)}ac.onLocalPin=M;function O(h){V("onOptionsChanged",St(h))}ac.onOptionsChanged=O;function m(){V("onCallAccepted")}ac.onCallAccepted=m;function k(){V("onRateNeeded")}ac.onRateNeeded=k;function G(h){ce("onSpeakerChanged",h)}ac.onSpeakerChanged=G;function J(h){V("onVolumesDetected",St(h))}ac.onVolumesDetected=J;function de(h,y){V("onLocalVolume",h,y)}ac.onLocalVolume=de;function me(h,y){V("onJoinStatus",h,y)}ac.onJoinStatus=me;function Ne(h,y){V("onHangup",h,y)}ac.onHangup=Ne;function De(h){V("onMultipartyChatCreated",Ie(h))}ac.onMultipartyChatCreated=De;function ke(){V("onDeviceChange")}ac.onDeviceChange=ke;function Oe(h){V("onFingerprintChange",h)}ac.onFingerprintChange=Oe;function Ue(){V("onTokenExpired")}ac.onTokenExpired=Ue;function N(h,y,Z=!1){V("onChatMessage",h,y,Z)}ac.onChatMessage=N;function Ft(h,y,Z=!1){V("onCustomData",h,y,Z)}ac.onCustomData=Ft;function B(h,y,Z,We,Vt,$i,qi=null){V("onRecordStarted",h,y,Z,We,Vt,$i,qi)}ac.onRecordStarted=B;function q(h=null){V("onRecordStopped",h)}ac.onRecordStopped=q;function he(h){V("onLocalNetworkStatusChanged",h)}ac.onLocalNetworkStatusChanged=he;function ve(h){V("onNetworkStatusChanged",h)}ac.onNetworkStatusChanged=ve;function te(h,...y){V("onDebugMessage",h,...y)}ac.onDebugMessage=te;function X(h,y){let Z=Object.assign({},h,{memory:y});V("onStatistics",Z)}ac.onStatistics=X;function se(){V("onAutoplayError")}ac.onAutoplayError=se;function Ge(h,y,Z){V("onChatRoomUpdated",h,y,Z)}ac.onChatRoomUpdated=Ge;function Ko(h){V("onRemoteMixedAudioStream",h)}ac.onRemoteMixedAudioStream=Ko;function $o(h){V("onJoinLinkChanged",h)}ac.onJoinLinkChanged=$o;function qo(h){V("onRoomsUpdated",h)}ac.onRoomsUpdated=qo;function Jo(h,y,Z,We){V("onRoomUpdated",h,y,Z,We)}ac.onRoomUpdated=Jo;function zo(h){V("onRoomParticipantsUpdated",h)}ac.onRoomParticipantsUpdated=zo;function Yo(h){V("onRoomSwitched",h)}ac.onRoomSwitched=Yo;function Qo(h){V("onRoomStart",h)}ac.onRoomStart=Qo;function Xo(h,y=null){V("onFeedback",h,y)}ac.onFeedback=Xo;function Zo(h){V("onFeaturesPerRoleChanged",h)}ac.onFeaturesPerRoleChanged=Zo;function ec(h){V("onVmojiSvgUpdate",h)}ac.onParticipantVmojiUpdate=ec;function tc(h,y){V("onAsrStarted",h,y)}ac.onAsrStarted=tc;function ic(){V("onAsrStopped")}ac.onAsrStopped=ic;function rc(h,y,Z,We){V("onAsrTranscription",h,y,Z,We)}ac.onAsrTranscription=rc})(fr||(fr={}));var f=fr;var vr=(i=>(i.DEBUG="DEBUG",i.LOG="LOG",i.WARN="WARN",i.ERROR="ERROR",i))(vr||{}),Sr;(ee=>{let n="📞",r=(ue,...Se)=>{f.onDebugMessage(ue,...Se)},e=!1,t=(ue,Se)=>(...nt)=>{ue(...nt),da(Se,nt)},i=console.debug.bind(console,n),a=console.log.bind(console,n),s=console.warn.bind(console,n),o=console.error.bind(console,n),l=r.bind(null,"DEBUG"),u=r.bind(null,"LOG"),g=r.bind(null,"WARN"),T=r.bind(null,"ERROR");ee.debug=l,ee.log=u,ee.warn=g,ee.error=T;function H(){return e}ee.enabled=H;function ge(ue){e=ue,p.debugLog&&Zi(),ue?(ee.debug=p.debugLog?t(i,"DEBUG"):i,ee.log=p.debugLog?t(a,"LOG"):a,ee.warn=p.debugLog?t(s,"WARN"):s,ee.error=p.debugLog?t(o,"ERROR"):o):(ee.debug=p.debugLog?t(l,"DEBUG"):l,ee.log=p.debugLog?t(u,"LOG"):u,ee.warn=p.debugLog?t(g,"WARN"):g,ee.error=p.debugLog?t(T,"ERROR"):T)}ee.toggle=ge;function W(ue,...Se){switch(ue){case"DEBUG":(0,ee.debug)(...Se);break;case"LOG":(0,ee.log)(...Se);break;case"WARN":(0,ee.warn)(...Se);break;case"ERROR":(0,ee.error)(...Se);break}}ee.send=W})(Sr||(Sr={}));var d=Sr;var Ai=(t=>(t.USER="USER",t.ANONYM="ANONYM",t.GROUP="GROUP",t))(Ai||{}),fe;(o=>{function n(l){return l.length?typeof l[0]=="object"?l:l.map(u=>r(u)):[]}o.fromIds=n;function r(l,u="USER"){return{id:l,type:u}}o.fromId=r;function e(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}o.fromSignaling=e;function t(l){return`{"id":"${l.id}","type":"${l.type}"}`}o.toString=t;function i(l,u="USER"){return t(r(l,u))}o.fromIdToString=i;function a(l){try{return JSON.parse(l)}catch(u){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}o.fromString=a;function s(l,u){return l.id===u.id&&l.type===u.type}o.compare=s})(fe||(fe={}));var pe;(i=>{function n(a,s="USER",o=0){return{id:a,type:s,deviceIdx:o}}i.fromId=n;function r(a){return`{"id":"${a.id}","type":"${a.type}","deviceIdx":"${a.deviceIdx}"}`}i.toString=r;function e(a,s){return Object.assign({deviceIdx:s},fe.fromSignaling(a))}i.fromSignaling=e;function t(a){return a&&typeof a=="object"?a.deviceIdx:0}i.getDeviceIdx=t})(pe||(pe={}));var ts="kf";function At(n){return n.stopStream}function Er(n){return n.keyFrameRequested}function Pa(n){if(At(n))return"ss";if(Er(n))return ts;let r="";return n.priority!==void 0&&(r+="p="+n.priority),n.width!==void 0&&n.height!==void 0&&(r!==""&&(r+=":"),r+="sz="+Math.round(n.width)+"x"+Math.round(n.height)),n.fit!==void 0&&(r!==""&&(r+=":"),r+="fit="+n.fit),r}var Dt=(s=>(s.CAMERA="CAMERA",s.SCREEN="SCREEN",s.STREAM="STREAM",s.MOVIE="MOVIE",s.AUDIOSHARE="AUDIOSHARE",s.ANIMOJI="ANIMOJI",s))(Dt||{}),ya="s",ba="m";function He(n){return n.participantId+(n.mediaType?Pt+ya+n.mediaType:"")+(n.streamName?Pt+ba+n.streamName:"")}function Yt(n){let r=n.split(Pt),e=r.shift();if(!e)throw new Error("Illegal stream description: "+n);let t=null,i,a=0;for(let o of r)switch(o.charAt(0)){case ya:t=is(o.slice(1));break;case ba:i=o.slice(1);break;case Ii:a=Number.parseInt(o.slice(1),10);break;default:throw new Error("Unexpected parameter type "+o.charAt(0)+" in stream description "+n)}return{participantId:I.compose(e,a),mediaType:t,streamName:i}}function is(n){for(let r of Object.keys(Dt))if(r===n)return Dt[r];return null}function Ir(n,r){return n===null||r===null?n===null&&r===null:!(n.maxDimension!==r.maxDimension||n.maxBitrateK!==r.maxBitrateK||n.maxFramerate!==r.maxFramerate||n.degradationPreference!==r.degradationPreference)}function Di(n,r){return!(!Ir(n.camera,r.camera)||!Ir(n.screenSharing,r.screenSharing))}function Tr(n,r){return{camera:Object.assign({},n.camera,r.camera),screenSharing:Object.assign({},n.screenSharing,r.screenSharing)}}function Ma(n){try{return btoa(JSON.stringify(n))}catch(r){d.warn("WaitingParticipant: failed convert to string",n,r)}return null}function Aa(n){try{return JSON.parse(atob(n))}catch(r){d.warn("WaitingParticipant: failed convert from string",n,r)}return null}var kt=(n,r)=>I.objectReduce(n,(e,t,i)=>(t===r&&e.push(i),e),[]);var Ot=class{constructor(r){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=r}_fixAudioDeviceNoPackets(r){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,_.log(v.ERROR,`audio_device_recover_${r.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!r.bandwidth&&(this._fixNoPacketsApplied=!0,_.log(v.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(r){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let e=75,t=Date.now();if(!this._lastPacketsSentTime)r.packetsSent>0&&(this._lastPacketsSentTime=t,this._lastPacketsSent=r.packetsSent);else if(t-this._lastPacketsSentTime>500){let i=(r.packetsSent-this._lastPacketsSent)*1e3/(t-this._lastPacketsSentTime);this._lastPacketsSentTime=t,this._lastPacketsSent=r.packetsSent,this._fixTooManyPacketsApplied?i>e?(d.log("Failed to fix RV"),_.log(v.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):t-this._fixTooManyPacketsTime>6e4&&(d.log("Fixed RV"),_.log(v.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):i>e&&(this._fixTooManyPacketsApplied=!0,d.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=t)}}fix(r){if(!this._mediaSource)return;let e=r.find(t=>t.kind==="audio");e&&(this._fixAudioDeviceNoPackets(e),this._fixAudioDeviceTooManyPackets(e))}};var Qt=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(r){this.destroy(),this._output={},this._output.audioTrack=r,this._initAudioElement()}remove(r){!this._output||this._output.audioTrack!==r||this.destroy()}get volume(){return this._volume}set volume(r){this._volume=Math.max(0,Math.min(1,r)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(p.muteMode||!((s=this._output)!=null&&s.audioTrack))return;let r=C.browserName()!=="Safari"||C.isMobile(),e=document.createElement(r?"audio":"video");e.muted=!1,e.volume=this._volume,e.preload="auto";let t=()=>{d.warn("Error on play audio"),f.onAutoplayError()},i=o=>{e.srcObject=new MediaStream([o]),e.load();let l=e.play();l&&l.catch(t)},a=()=>{var l;d.debug("Recover audio playback");let o=(l=this._output)==null?void 0:l.audioTrack;o?i(o):d.warn("Broken audio track")};e.onpause=a,e.onstalled=a,e.onerror=a,i(this._output.audioTrack),this._output.audioElement=e}_stopAudioElement(){var r,e,t;(r=this._output)!=null&&r.audioElement&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(t=(e=this._output)==null?void 0:e.audioTrack)==null||t.stop()}destroy(){this._output&&(this._stopAudioElement(),this._output=null)}changeOutput(){return c(this,null,function*(){var r,e,t;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((r=this._output)!=null&&r.audioElement))throw new Error("Audio Element is not initialized");let i=C.getSavedOutput();i&&(yield(t=(e=this._output.audioElement).setSinkId)==null?void 0:t.call(e,i.deviceId))}catch(i){throw _.log(v.ERROR,"change_output"),d.error("Output change failed",i),i}})}};var rs=90,as=3,Xt=class extends ie{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let a=typeof i.userId=="string"&&t[i.userId]||null;i.userId=a==null?void 0:a.externalId}),f.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var a;let e=(a=window==null?void 0:window.performance)==null?void 0:a.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>rs?d.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=as)&&(d.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var ns=44100,wt=class{constructor(r,e){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=r,this._stream=e;try{let t=C.getAudioContext();this._gainNode=t.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(t.destination),this._analyser=t.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=t.createMediaStreamSource(e),this._mediaStreamSource.connect(this._analyser)}catch(t){}}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 r=ns/this._fftBins.length,e=Math.ceil(p.voiceParams.minFreq/r),t=Math.floor(p.voiceParams.maxFreq/r);return this._fftBins.subarray(e,t)}getLevel(){let r=this._getBins(),t=r.reduce((a,s)=>a+s,0)/r.length/255,i=this._lastSmoothedLevel*p.voiceParams.smoothing+t*(1-p.voiceParams.smoothing);return this._lastSmoothedLevel=i,{real:t,smoothed:i}}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 ie{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&f.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 a=e.getStream();a&&this.init(a)};this.subscribe(e,"SOURCE_CHANGED",a=>{a.kind==="audio"&&a.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks().find(i=>!i.contentHint);t&&(this._track=t.clone(),this._detector=new wt("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 Da=(s=>(s.producerNotification="producerNotification",s.producerCommand="producerCommand",s.consumerScreenShare="consumerScreenShare",s.producerScreenShare="producerScreenShare",s.asr="asr",s.animoji="animoji",s))(Da||{}),Je=Da;var ka="videochat-epi",ss=5e3,os=3e4,tt=class extends ie{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,"REMOTE_DATA_STATS",this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(ka)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return c(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&p.perfStatReportEnabled&&this._previousTimestamp+ss<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),p.callStatReportEnabled&&this._previousCallStatReportTimestamp+os<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return c(this,null,function*(){let t=e.inbound.rtps.reduce((i,a)=>(a.kind==="video"&&(i.framesDecoded+=a.framesDecoded||0,i.framesReceived+=a.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(ka,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((a,s)=>(s.kind==="video"?(s.framesReceived&&(a.jitter_video=a.jitter_video*a.inbound_video_count/(a.inbound_video_count+1)+s.jitter*1e3/(a.inbound_video_count+1),a.interframe_delay_variance=a.interframe_delay_variance*a.inbound_video_count/(a.inbound_video_count+1)+s.interframeDelayVariance*1e6/(a.inbound_video_count+1),a.inbound_video_count++),a.frames_dropped+=s.framesDropped,a.nack_sent+=s.nackCount,a.pli_sent+=s.pliCount,a.fir_sent+=s.firCount):(s.totalSamplesReceived&&(a.jitter_audio=a.jitter_audio*a.inbound_audio_count/(a.inbound_audio_count+1)+s.jitter*1e3/(a.inbound_audio_count+1),a.total_audio_energy=a.total_audio_energy*a.inbound_audio_count/(a.inbound_audio_count+1)+s.totalAudioEnergy/(a.inbound_audio_count+1),a.inbound_audio_count++),a.total_audio_samples_received+=s.totalSamplesReceived,a.inserted_audio_samples_for_deceleration+=s.insertedSamplesForDeceleration,a.removed_audio_samples_for_acceleration+=s.removedSamplesForAcceleration,a.concealed_audio_samples+=s.concealedSamples,a.silent_concealed_audio_samples+=s.silentConcealedSamples,a.audio_concealment_events+=s.concealmentEvents),a),t),e.outbound.rtps.reduce((a,s)=>(s.kind==="video"&&(a.nack_received+=s.nackCount,a.pli_received+=s.pliCount,a.fir_received+=s.firCount),a),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let a=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,s=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,o=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,l=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,u=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,g=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=s/a*1e3,i.removed_audio_samples_for_acceleration=o/a*1e3,i.concealed_audio_samples=l/a*1e3,i.concealed_silent_audio_samples=u/a*1e3,i.concealment_audio_avg_size=l/g,i.total_audio_energy=t.total_audio_energy}_.logCustom("callStat",i),d.log("Sent call stats",i),this._previousCallStatReport=t}};var Oi=.8,it=class extends ie{constructor(e,t,i,a,s,o={}){super();this._remoteSDP={};this._remoteCandidates={};this._state="IDLE";this._animojiDataChannel=null;this._animojiReceiver=null;this._animojiSender=null;this._animojiSvgDataByParticipantId={};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=a,this._participantId=e,this._isMaster=t,this._serverSettings=s,this._animojiSvgDataByParticipantId=o,this._perfStatReporter=new tt(this,i,!0),this.subscribe(this._signaling,Ee.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,"TRACK_REPLACED",this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,"SOURCE_CHANGED",this._applySettings.bind(this)),this.subscribe(this._mediaSource,"ANIMOJI_STATUS",this._onAnimojiStatus.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={},p.useVmoji&&this._createDataChannel(this._pc,Je.animoji,l=>{this._animojiDataChannel=l,this._animojiDataChannel.binaryType="arraybuffer",this._createAnimojiReceiver(),this._mediaSource.isAnimojiRequested&&this._createAnimojiSender()}),this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,p.p2pAudioRed),this._applySettings()}catch(l){_.log(v.ERROR,"addTrack-direct"),d.error("Unable to add media source tracks",l,{participantId:this._participantId}),this._failedOnCreate=l;return}this._createOffer(!1).catch(l=>{this._state==="IDLE"?this._failedOnCreate=l:this.close(l)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!=="IDLE"&&e!=="CLOSED"&&e!=="FAILED"&&this._startStatInterval()}open(e=null){return c(this,null,function*(){if(this._isOpen){d.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(d.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,p.p2pAudioRed),this._applySettings()}catch(i){_.log(v.ERROR,"addTrack-direct"),d.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState("OPENED");let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={}})}updateSettings(e){Di(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._removeAnimojiReceiver(),this._removeAnimojiSender(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent("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?(d.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState("FAILED")):(d.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState("CLOSED")),this._triggerEvent("PEER_CONNECTION_CLOSED")}setAnimojiSvg(e,t){var i;(i=this._animojiReceiver)==null||i.setParticipantSvg(e,t)}_setState(e){this._state!==e&&(d.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent("STATE_CHANGED",e))}_onSignalingNotification(e){var t,i,a,s;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=((a=e.data.sdk)==null?void 0:a.rtt)||0,this._remoteNetworkStat.loss=((s=e.data.sdk)==null?void 0:s.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=I.getPeerIdString(e.peerId);I.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){d.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw _.log(v.ERROR,"addIceCandidate-direct"),d.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else d.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return c(this,null,function*(){if(!this._remoteCandidates[e]){d.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(a){}})}_setRemoteDescription(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){d.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 _.log(v.ERROR,"setRemoteDescription-direct"),d.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){d.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),_.logMeasure(v.FIRST_DATA_RECEIVED_P2P),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent("REMOTE_TRACK_REMOVED",this._remoteStream,t.track)}),this._triggerEvent("REMOTE_TRACK_ADDED",this._remoteStream,e.track)}_handleIceCandidate(e){return c(this,null,function*(){e.candidate&&this._signaling.ready&&(d.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(d.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>c(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(d.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e==="IDLE"||e==="OPENED"?this._setState("CONNECTING"):this._setState("RECONNECTING");break}}_onConnectionStateChange(){switch(d.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),_.log(v.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState("CONNECTED"),this._stopReconnection(),I.getPeerConnectionHostInfo(this._pc).then(e=>{e&&_.log(v.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState("RECONNECTING"),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(d.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&&(d.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology("SERVER"))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(_.log(v.ICE_RESTART),d.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):d.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,d.error("Ice restart failed",{participantId:this._participantId}),_.log(v.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},p.iceRestartWaitTime)}_createOffer(e){return c(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return d.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw d.error("Unable to create offer",i,{participantId:this._participantId}),_.log(v.ERROR,"createOffer-direct"),i}).then(i=>c(this,null,function*(){return d.debug("Created offer",{participantId:this._participantId,offer:i}),i=it._patchDescription(i),d.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw d.error("Unable to set local description",i,{participantId:this._participantId}),_.log(v.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return c(this,null,function*(){return d.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw d.error("Unable to create answer",e,{participantId:this._participantId}),_.log(v.ERROR,"createAnswer-direct"),e}).then(e=>c(this,null,function*(){return d.debug("Created answer",{participantId:this._participantId,answer:e}),e=it._patchDescription(e),d.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw d.error("Unable to set local description",e,{participantId:this._participantId}),_.log(v.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!C.baseChromeVersion();return e.sdp=I.patchLocalSDP(e.sdp,p.preferH264&&C.canPreferH264(),C.isBrokenH264(),p.preferVP9,p.h264spsPpsIdrInKeyframe,t&&p.audioNack,p.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&t.track.contentHint===e.contentHint&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{d.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),_.log(v.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_onAnimojiStatus(e){e?this._createAnimojiSender():this._removeAnimojiSender(),this._mediaSource.onAnimojiSender(e)}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}$t(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:"DIRECT",transport:t.transport,rtps:t.rtps.filter(a=>a.type==="inbound-rtp"?(a.userId=this._participantId,!0):!1)},outbound:{topology:"DIRECT",transport:t.transport,rtps:t.rtps.filter(a=>a.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent("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=W=>W.rtt<=this._networkLimits.goodNet.rtt&&W.loss<=this._networkLimits.goodNet.loss,i=W=>W.rtt>=this._networkLimits.badNet.rtt||W.loss>=this._networkLimits.badNet.loss,a=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,s=e.inbound.rtps.reduce((W,ee)=>Math.max(W,ee.packetLoss||0),0),o={rtt:this._lastNetworkStat.rtt*(1-Oi)+a*Oi,loss:this._lastNetworkStat.loss*(1-Oi)+s*Oi},l=i(o),u=t(o),g=i(this._remoteNetworkStat),T=t(this._remoteNetworkStat),b=i(this._lastNetworkStat),D=t(this._lastNetworkStat),H=l||g?.2:u&&T?1:0,ge=Date.now();if((b!==l||D!==u||ge-this._lastNetworkStat.date>p.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},o)},null).catch(W=>{d.warn("Unable to send [bad-net]",W)})),H){let W={};W[this._participantId]=W[""]=H,this._triggerEvent("NETWORK_STATUS",W)}this._lastNetworkStat.rtt=o.rtt,this._lastNetworkStat.loss=o.loss}_startSettingsInterval(){if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,2e3)};this._settingsInterval=window.setTimeout(t,2e3)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=I.sdpFingerprint(e);if(t===null){d.warn("Fingerprint calculation is unsupported");return}this._fingerprint===null?this._fingerprint=t:(f.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=I.applySettings(this._pc,e,this._prevConsumerSettings)),this._animojiSender){let i=this._mediaSource.getStream();i&&this._animojiSender.setStream(i)}}_createDataChannel(e,t,i){d.debug(`[${t}] data channel opening`);let a=e.createDataChannel(t,{negotiated:!0,id:1});a.onopen=()=>{let s=a.readyState;s==="open"?(d.debug(`[${t}] data channel opened`),a.onerror=o=>{d.error(`[${t}] data channel error`,o)},i(a)):d.error(`[${t}] data channel open failed, state [${s}]`)}}_createAnimojiReceiver(){!p.useVmoji||!this._animojiDataChannel||!this._participantId||(this._animojiReceiver&&this._removeAnimojiReceiver(),this._animojiReceiver=new p.vmoji.AnimojiReceiver(this._animojiDataChannel,this._participantId,(e,t)=>{this._triggerEvent("ANIMOJI_STREAM",e,t)},e=>{this._triggerEvent("ANIMOJI_STREAM",e,null)}),Object.entries(this._animojiSvgDataByParticipantId).forEach(([e,t])=>{this._animojiReceiver.setParticipantSvg(e,t)}))}_removeAnimojiReceiver(){var e;(e=this._animojiReceiver)==null||e.destroy(),this._animojiReceiver=null}_createAnimojiSender(){if(!p.useVmoji||!this._animojiDataChannel)return;let e=this._mediaSource.getStream();e&&(this._animojiSender&&this._removeAnimojiSender(),this._animojiSender=new p.vmoji.AnimojiSender(this._animojiDataChannel,e))}_removeAnimojiSender(){var e;(e=this._animojiSender)==null||e.destroy(),this._animojiSender=null}};var cs=16,Lt=class{constructor(r,e,t){d.debug("AsrReceiver started"),this._datachannel=r,this._participantIdRegistry=e,this._asrCallback=t,this._textDecoder=new TextDecoder,this._datachannel.onmessage=i=>this._onDataChannelMessage(i.data)}static parse(r){let e=new DataView(r),t=e.getUint8(0),i=e.getUint8(1);if(i!==0)throw new Error(`Unsupported message type. Message type: ${i}`);let a=e.getUint16(2),s=e.getUint32(4),o=e.getUint32(8),l=e.getUint32(12);if(t!==1)throw new Error(`Unexpected protocol version. Got ${t}, expected 1`);return{sequence:a,ssrc:s,timestamp:o,duration:l,data:r.slice(cs)}}_onDataChannelMessage(r){var a,s;let e=Lt.parse(r),t=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(e.ssrc))==null?void 0:s.participantId;if(!t){d.warn(`Participant id for ssrc ${e.ssrc} not found in registry`);return}let i={participantId:t,text:this._textDecoder.decode(e.data),timestamp:e.timestamp,duration:e.duration};this._asrCallback(i)}destroy(){this._datachannel.onmessage=null}};var at=require("messagepack");var wi=class{constructor(){this.streamDescriptionByCompactId=new Map;this.compactIdByStreamDescription=new Map}getStreamDescription(r){return this.streamDescriptionByCompactId.get(r)}getCompactId(r){return this.compactIdByStreamDescription.get(r)}handleMessage(r){var a,s;let e=new Uint8Array(r),t=e[0],i=e.subarray(1);switch(t){case 1:let o=(0,at.decode)(i);return Object.entries(o).forEach(([A,Y])=>{let H=Yt(A);this.streamDescriptionByCompactId.set(Y,H),this.compactIdByStreamDescription.set(A,Y)}),null;case 2:case 4:let l=(0,at.decode)(i),u=[];for(let A of l){let Y=this.getStreamDescription(A);Y&&u.push(Y.participantId)}return t===2?{type:"notification",notification:x.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:x.STALLED_ACTIVITY,stalledParticipants:u};case 3:let g=(0,at.decode)(i);return{type:"notification",notification:x.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(g))==null?void 0:a.participantId};case 5:let T=(0,at.decode)(i);return{type:"notification",notification:x.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:T[0],maxDimension:T[1]}};case 6:let b=(0,at.decode)(i),D={};for(let[A,Y]of Object.entries(b)){let H=(s=this.getStreamDescription(Number(A)))==null?void 0:s.participantId;H&&(D[H]=Y/100)}return{type:"notification",notification:x.NETWORK_STATUS,statuses:D};case 7:return this._createParticipantSourcesUpdateNotification(i);case 8:{let Y=(0,at.decode)(i).map(H=>{var Q;let[ge,W,ee,ue,Se,nt,ni]=H;return{participantId:(Q=this.getStreamDescription(ge))==null?void 0:Q.participantId,gain:W,pause:ee,offset:ue,mute:Se,liveStatus:nt,startTimeMs:ni}});return{type:"notification",notification:x.MOVIE_UPDATE_NOTIFICATION,data:Y}}default:return d.debug("unsupported message type: "+t),null}}_createParticipantSourcesUpdateNotification(r){let e=(0,at.decode)(r),t=[];for(let[i,a]of Object.entries(e)){let s=a[0],o=a[1],l=a[2],u;if(s!==null){if(u=this.getStreamDescription(s),!u){d.error(`could not uncompress participant ID ${s}`);continue}}else u=null;if(l===null){d.error("unexpected null sequenceNumber",i,a);continue}let g=we.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+i,T=o?o>>>0:null;t.push({participantStreamDescription:u,streamId:g,rtpTimestamp:T,sequenceNumber:l})}return{type:"notification",notification:x.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:t}}};var ds=90,ls=4294967295,be=class extends ie{constructor(e,t,i,a={}){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._asr=null;this._animojiDataChannel=null;this._animojiReceiver=null;this._animojiSender=null;this._animojiSvgDataByParticipantId={};this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state="IDLE";this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._asrTrack=null;this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._newAudioShareTrack=null;this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,Ee.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,"TRACK_REPLACED",this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,"SOURCE_CHANGED",this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,"SCREEN_STATUS",this._onScreenSharingStatus.bind(this)),this.subscribe(this._mediaSource,"ANIMOJI_STATUS",this._onAnimojiStatus.bind(this)),this._perfStatReporter=new tt(this,e),this._serverSettings=i,this._animojiSvgDataByParticipantId=a,d.debug("ServerTransport: Created")}getState(){return this._state||"IDLE"}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!=="IDLE"&&e!=="CLOSED"&&e!=="FAILED"&&this._startStatInterval()}open(e=!1){if(this._isOpen){d.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(d.error("ServerTransport: Closed",e),this._setState("FAILED")):(d.debug("ServerTransport: Closed"),this._setState("CLOSED"))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Di(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}setAnimojiSvg(e,t){var i;(i=this._animojiReceiver)==null||i.setParticipantSvg(e,t)}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeAsrTrack(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._removeAnimojiReceiver(),this._removeAnimojiSender(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,be._closeDataChannel(this._producerNotification),be._closeDataChannel(this._producerCommand),be._closeDataChannel(this._producerScreen),be._closeDataChannel(this._consumerScreen),be._closeDataChannel(this._asr),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent("PEER_CONNECTION_CLOSED")}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){d.debug(`[${t}] data channel opening`);let a=e.createDataChannel(t,{ordered:!0});a.onopen=()=>{let s=a.readyState;s==="open"?(d.debug(`[${t}] data channel opened`),i(a)):d.error(`[${t}] data channel open failed, state [${s}]`)},a.onerror=s=>{let o=s.error;d.error(`[${t}] data channel error`,o==null?void 0:o.errorDetail,o==null?void 0:o.message)}}_openConnection(e=!1){d.debug("ServerTransport: Open single connection"),this._pc=new RTCPeerConnection({},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=I.throttle(t=>{this._pc&&this._onConnectionStateChange(this._pc,t)},500),this._pc.onsignalingstatechange=be._onSignalingStateChange.bind(this,this._pc),this._participantIdRegistry=new wi,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),p.producerNotificationDataChannel&&this._createDataChannel(this._pc,Je.producerNotification,t=>{this._producerNotification=t,this._producerNotification.binaryType="arraybuffer",this._signaling.setProducerNotificationDataChannel(t)}),p.producerCommandDataChannel&&(this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,Je.producerCommand,t=>{this._producerCommand=t,this._signaling.setProducerCommandDataChannel(t)})),p.producerScreenDataChannel&&this._createDataChannel(this._pc,Je.producerScreenShare,t=>{this._producerScreen=t,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()}),p.asrDataChannel&&this._createDataChannel(this._pc,Je.asr,t=>{this._asr=t,this._asr.binaryType="arraybuffer",this._removeAsrTrack(),this._asrTrack=new Lt(t,this._participantIdRegistry,i=>{this._onAsrTranscription(i)}),this._signaling.setAsrDataChannel(t)}),p.useVmoji&&this._createDataChannel(this._pc,Je.animoji,t=>{this._animojiDataChannel=t,this._animojiDataChannel.binaryType="arraybuffer",this._createAnimojiReceiver(),this._mediaSource.isAnimojiRequested&&this._createAnimojiSender()}),this._newAudioShareTrack=this._mediaSource.getAudioShareTrack();try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,p.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(t){d.error("ServerTransport: Unable to add media source tracks",t),_.log(v.ERROR,"addTrack-single"),this.close(t);return}p.consumerScreenDataChannel&&this._createDataChannel(this._pc,Je.consumerScreenShare,t=>{this._consumerScreen=t,this._consumerScreen.binaryType="arraybuffer";let i=this._mediaSource.getScreenTrack();i&&this._createCaptureSender(i)}),e||this._allocateConsumer(),this._setState("OPENED"),this._startStatInterval(),this._startSettingsInterval()}_removeAsrTrack(){var e;(e=this._asrTrack)==null||e.destroy(),this._asrTrack=null}_reconnect(){this.getState()!=="OPENED"&&(this._setState("RECONNECTING"),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_signalStalledParticipants(e){this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_signalSpeakerChanged(e){this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_signalNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
- `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${we.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,a=new RegExp(i).exec(t);a&&(this._ssrcMap[a[1]]=a[3])})}_createCaptureSender(e){let t=this._mediaSource.getMediaSettings();!e||!p.consumerScreenDataChannel||!this._consumerScreen||!t.isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new ft(e,this._consumerScreen,this._signaling,t.isFastScreenSharingEnabled))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!p.producerScreenDataChannel||!this._producerScreen||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new _t(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent("REMOTE_STREAM_SECOND",e,t)},e=>{this._triggerEvent("REMOTE_STREAM_SECOND",e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_createAnimojiSender(){if(!p.useVmoji||!this._animojiDataChannel)return;let e=this._mediaSource.getStream();e&&(this._animojiSender&&this._removeAnimojiSender(),this._animojiSender=new p.vmoji.AnimojiSender(this._animojiDataChannel,e))}_removeAnimojiSender(){var e;(e=this._animojiSender)==null||e.destroy(),this._animojiSender=null}_createAnimojiReceiver(){!p.useVmoji||!this._animojiDataChannel||!this._participantIdRegistry||(this._animojiReceiver&&this._removeAnimojiReceiver(),this._animojiReceiver=new p.vmoji.AnimojiReceiver(this._animojiDataChannel,this._participantIdRegistry,(e,t)=>{this._triggerEvent("ANIMOJI_STREAM",e,t)},e=>{this._triggerEvent("ANIMOJI_STREAM",e,null)}),Object.entries(this._animojiSvgDataByParticipantId).forEach(([e,t])=>{this._animojiReceiver.setParticipantSvg(e,t)}))}_removeAnimojiReceiver(){var e;(e=this._animojiReceiver)==null||e.destroy(),this._animojiReceiver=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 a=!this._disabledSenders.has(i),s=e.maxDimension!==0;if(a&&!s){d.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(C.getBlackMediaTrack()).catch(l=>{d.error("Could not disable video upload",l)});return}let o=this._mediaSource.getSendVideoTrack();if(!a&&s&&o){d.log("Enabling video upload"),this._disabledSenders.delete(i);let l=i.track;l.enabled=o.enabled,i.replaceTrack(o).then(()=>l.stop()).catch(u=>{d.error("Could not enable video upload",u)})}I.applyVideoTrackSettings(e,i,o!=null?o:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}if(this._animojiSender){let t=this._mediaSource.getStream();t&&this._animojiSender.setStream(t)}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_onAnimojiStatus(e){e?this._createAnimojiSender():this._removeAnimojiSender(),this._mediaSource.onAnimojiSender(e)}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent("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(){if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,2e3)};this._settingsInterval=window.setTimeout(t,2e3)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return c(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield $t(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent("REMOTE_DATA_STATS",{inbound:{topology:"SERVER",transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:"SERVER",transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(o=>o.type==="inbound-rtp"&&o.kind==="audio"&&this._ssrcMap[o.ssrc]==="mix");if(!t)return;let i=we.AUDIO_MIX,a=this._statBytes[i],s=!1;if(a){let o=t.bytesReceived-a.bytesReceived;o>=0&&o<=5&&(s=!0),a.stalled!==s&&this._triggerEvent("REMOTE_ALL_STALL",s)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:s}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:tt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:p.producerNotificationDataChannel?7:0,producerCommandDataChannelVersion:p.producerCommandDataChannel?3:0,consumerScreenDataChannelVersion:p.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:p.producerScreenDataChannel?1:0,asrDataChannelVersion:p.asrDataChannel?1:0,animojiDataChannelVersion:p.useVmoji?1:0,onDemandTracks:!0,unifiedPlan:!0,singleSession:!0,videoTracksCount:p.videoTracksCount,red:p.serverAudioRed,audioShare:p.audioShare,fastScreenShare:p.fastScreenShare};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return c(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,d.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:I.patchRemoteSDP(e)});if(d.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw d.error("[single] unable to set remote offer",i),_.log(v.ERROR,"setRemoteDescription-single"),i}).then(()=>c(this,null,function*(){if(d.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this.handleTracks(),this._pc.createAnswer()})).catch(i=>{throw d.error("[single] unable to create answer",i),_.log(v.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=I.patchLocalSDP(i.sdp,!1,C.isBrokenH264(),!1,p.h264spsPpsIdrInKeyframe),i)).then(i=>c(this,null,function*(){if(d.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw d.error("[single] unable to set local answer",i),_.log(v.ERROR,"setLocalDescription-single"),i}).then(i=>c(this,null,function*(){d.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),d.debug("[single] remote offer has been processed")})).catch(i=>{d.warn("[single] unable to send local answer",i),_.log(v.ERROR,"acceptProducer")}).then(()=>c(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){d.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))})}handleTracks(){this._newAudioShareTrack&&(this._pc.getTransceivers().forEach(e=>{e.mid.endsWith("s")&&(e.sender.track!==null&&d.warn("Unexpected track assigned to audioshare"),e.direction="sendonly",e.sender.replaceTrack(this._newAudioShareTrack).catch(t=>{d.error("ServerTransport: Unable to replace track",t),_.log(v.ERROR,"replaceTrack-single")}),this._newAudioShareTrack=null)}),this._newAudioShareTrack&&d.warn("Cannot find audioshare transceiver"))}_onSignalingNotification(e){return c(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}})}_onAsrTranscription(e){this._triggerEvent("ASR_TRANSCRIPTION",e)}_onProducerUpdated(e){return c(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),p.breakVideoPayloadTypes&&(d.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes",null)),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){var a;d.debug("[single] remote track (added)",{track:t.track}),((a=t.track)==null?void 0:a.kind)==="audio"&&_.logMeasure(v.FIRST_AUDIO_MIX_DATA_RECEIVED);let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=o=>{this._triggerEvent("REMOTE_TRACK_REMOVED",i.id,i,o.track)}),i.getTracks().find(o=>o.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent("REMOTE_TRACK_ADDED",i.id,i,t.track)):d.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){d.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(d.debug("[single] connection state changed",{state:e.connectionState},t),_.log(v.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):(_.logCustom(v.RECONNECT,{param:1}),this._reconnect());break;case"connecting":let i=this.getState();i==="IDLE"||i==="OPENED"?this._setState("CONNECTING"):e.iceConnectionState==="checking"&&this._setState("RECONNECTING");break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState("RECONNECTING");break;case"connected":this._setState("CONNECTED"),I.getPeerConnectionHostInfo(e).then(a=>{a&&_.log(v.ICE_CONNECTION_TYPE,a.type)}),_.logCustom(v.RECONNECT,{param:0});break}}_onReplacedTrack(e,t){if(this._pc){p.consumerScreenDataChannel&&t&&(e=t);let i=!1;this._pc.getSenders().forEach(a=>{a.track&&a.track.kind===e.kind&&!this._disabledSenders.has(a)&&a.track.contentHint===e.contentHint&&(a.track.enabled=e.enabled,a.replaceTrack(e).catch(s=>{d.error("ServerTransport: Unable to replace track",s),_.log(v.ERROR,"replaceTrack-single")}),i=!0)}),!i&&e.kind==="audio"&&e.contentHint==="music"&&(this._newAudioShareTrack=e)}this._applyConsumerSettings()}getStreamWaitingTimeMs(e,t){if(!this._pc)return _.log(v.PAT_WAITING_TIME_ERROR,"noConnection"),d.error("Cannot get stream waiting time, peer connection is not initialized"),0;if(!RTCRtpReceiver.prototype.getSynchronizationSources)return _.log(v.PAT_WAITING_TIME_ERROR,"oldBrowser"),d.error("Cannot get stream waiting time, RTCRtpReceiver.getSynchronizationSources is not supported"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return _.log(v.PAT_WAITING_TIME_ERROR,"noReceiver"),d.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let a=i.getSynchronizationSources();if(!a||!a.length)return d.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let o=a[0].rtpTimestamp;if(!Number.isInteger(o))return _.log(v.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),d.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${o}`),0;let l=t-o&ls,u=Math.ceil(l/ds);return Math.min(100,Math.max(0,u))}};var rt=(e=>(e.DIRECT="DIRECT",e.SERVER="SERVER",e))(rt||{}),xi=class extends ie{constructor(e,t,i,a){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._animojiSvgDataByParticipantId={};this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=a,this.subscribe(this._signaling,Ee.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,"ANIMOJI_STATUS",this._onAnimojiStatus.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){d.log("Update transport settings",e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(d.log(`Trying allocate participant [${e}]`),this._allocated.indexOf(e)!==-1){d.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,i=!1,a=!1){d.log("Trying open participant",{participantIds:e});let s=a;for(let o of e){if(this._opened.indexOf(o)!==-1){d.warn(`The participant [${o}] has already had opened transport`);continue}if(this._allocated.indexOf(o)===-1){d.warn(`The participant [${o}] has no allocated transport`);continue}this._opened.push(o),s=!0}s&&(this._topology==="DIRECT"&&this._directTransport&&(pt(v.FIRST_DATA_RECEIVED_P2P),this._directTransport.open(t)),this._topology==="SERVER"&&this._serverTransport&&(pt(v.FIRST_AUDIO_MIX_DATA_RECEIVED),this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),d.debug("The transport has been opened",e))}close(e){var a;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&d.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((a=this._serverTransport)==null||a.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}getState(){var e,t;return this._topology==="SERVER"?(e=this._serverTransport)==null?void 0:e.getState():(t=this._directTransport)==null?void 0:t.getState()}setAnimojiSvg(e,t){this._animojiSvgDataByParticipantId[e]=t,(!(t.svg instanceof ArrayBuffer)||t.svg.byteLength!==0)&&(this._topology==="DIRECT"&&this._directTransport?this._directTransport.setAnimojiSvg(e,t):this._topology==="SERVER"&&this._serverTransport&&this._serverTransport.setAnimojiSvg(e,t))}_setStates(e,t){let i=e.filter(a=>this._states[a]!==t?(this._states[a]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===x.TOPOLOGY_CHANGED)return this._onTopologyChanged(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(d.log(`Topology changed ${this._topology} -> ${e.topology}`),_.log(v.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],a=e.offerToTypes||[],s=e.offerToDeviceIdxs||[],o=i.length&&a.length?I.composeParticipantId(i[0],a[0],s[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){d.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&d.warn("Topology changed to DIRECT, but the allocated participants count more then one");let l=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let u=o===l;this._directTransport=this._createDirectTransport(l,u)}this._opened.indexOf(l)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_createDirectTransport(e,t=!1){let i=new it(e,t,this._signaling,this._mediaSource,this._serverSettings,this._animojiSvgDataByParticipantId);return this._dtListeners&&this._dtListeners.length>0&&d.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT")),i.addEventListener("ANIMOJI_STREAM",this._onAnimojiStream.bind(this))),i}_createServerTransport(){let e=new be(this._signaling,this._mediaSource,this._serverSettings,this._animojiSvgDataByParticipantId);return this._stListeners&&this._stListeners.length>0&&d.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER")),e.addEventListener("ASR_TRANSCRIPTION",this._onAsrTranscription.bind(this)),e.addEventListener("ANIMOJI_STREAM",this._onAnimojiStream.bind(this))),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==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let a=this._allocated.indexOf(e);a>=0&&this._allocated.splice(a,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onAsrTranscription(e){this._triggerEvent("ASR_TRANSCRIPTION",e)}_onAnimojiStream(e,t){this._triggerEvent("ANIMOJI_STREAM",e,t)}_onAnimojiStatus(e){!this._directTransport&&!this._serverTransport&&this._mediaSource.onAnimojiSender(e)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(_.log(v.PAT_WAITING_TIME_ERROR,"wrongTopology"),d.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(_.log(v.PAT_WAITING_TIME_ERROR,"noTransport"),d.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Li=class extends ie{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,"REMOTE_TRACK_ADDED",this._onRemoteTrackAdded.bind(this)),this.subscribe(e,"REMOTE_TRACK_REMOVED",this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,"SIGNALLED_ACTIVE_PARTICIPANTS",this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,"TOPOLOGY_CHANGED",this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var a;if(i.kind==="audio"&&((a=this._detector)==null||a.destroy(),this._detector=new wt(e,t),!this._interval)){let s=()=>{this._collectVolumes(),this._interval=window.setTimeout(s,p.voiceParams.interval)};this._interval=window.setTimeout(s,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===we.AUDIO_MIX){if(this._activeParticipants)for(let a of this._activeParticipants)e[a]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e==="DIRECT"&&(this._activeParticipants=null)}};var Ni=class extends ie{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i==="SERVER",this.subscribe(e,"VOLUMES_DETECTED",this._onVolumesDetected.bind(this)),this.subscribe(t,"SIGNALLED_SPEAKER_CHANGED",this._onServerSpeakerChanged.bind(this)),this.subscribe(t,"TOPOLOGY_CHANGED",this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(a=>{let s=e[a].smoothed;s>t&&s>p.voiceParams.threshold&&(t=s,i=a)}),i&&i!==this._speakerId){let a=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>a*p.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent("SPEAKER_CHANGED",e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e==="SERVER"}};var ei=class extends ie{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,"STATE_CHANGED",this._onTransportStateChanged.bind(this)),this.subscribe(t,"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==="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==="FAILED"&&this._connectionTimeout&&(d.warn("Transport failed, send callSpecError"),_.log(v.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!=="CONNECTED";(()=>Object.values(this._states).filter(e).length>0)()&&(d.warn("There is not connected transport, send callSpecError"),_.log(v.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",a=this._participants[t];a&&a.platform&&(i=a.platform),e.indexOf(i)<0&&(e.push(i),_.log(v.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&d.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var ps=1e3,us=1e4;var ms=15,$=class extends ie{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._myLastRequestedLayouts={};this._state="IDLE";this._participantState=K.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;_.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),_.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new Qt,p.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),ps))}static current(){return $._current}static hangupAfterInit(){$._activationMutex&&!$._current&&($._delayedHangup=!0)}static id(){var e,t;return((t=(e=$._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,a="",s=!1,o=!1,l){return c(this,null,function*(){if($._activationMutex)throw _.log(v.ERROR,"startCall"),d.warn("Conversation: there is already running activation"),new F(w.FAILED);$._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let u=this._mediaSource.getMediaSettings();t===Be.CHAT||e.length>1?this._logWithMediaSettings(v.OUTGOING_MULTIPARTY_CALL,u):this._logWithMediaSettings(v.OUTGOING_CALL,u);let g=yield this._startConversation(e,t,Ke.OUTGOING,i,a,s,o,l);if(!this._conversation)throw new F(w.UNKNOWN_ERROR);if(this._participantState=K.ACCEPTED,this._signaling.changeMediaSettings(u),yield this._processConnection(g),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),$._delayedHangup)throw new F(w.CANCELED);d.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let T=Object.values(this._participants),b;return p.batchParticipantsOnStart&&(b=I.mapSharedParticipants(T)),yield this._processConnectionSharedMovieInfo(g),f.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),f.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),b),this._onConversationParticipantListChunk(g),f.onLocalStatus("WAITING"),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),$._current=this,this._conversation.concurrent?yield this._acceptConcurrent():p.batchParticipantsOnStart||this._setParticipantsStatus(T,"WAITING"),this._conversation}catch(u){throw this._close(u,"Unable to start conversation"),u}finally{$._activationMutex=!1}})}onJoin(e){return c(this,null,function*(){var t;if($._activationMutex)throw _.log(v.ERROR,"joinCall"),d.warn("Conversation: there is already running activation"),new F(w.FAILED);$._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)!=null&&t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let a=this._mediaSource.getMediaSettings();this._logWithMediaSettings(v.JOIN_CONVERSATION,a);let s=yield this._joinConversation(e);if(!this._conversation)throw new F(w.UNKNOWN_ERROR);return this._conversation.observer=i,f.onLocalStream(this._mediaSource.getStream(),a),this._conversation.waitingHall?(d.log("In waiting hall"),$._current=this,$._activationMutex=!1,this._signaling.readyToSend(),f.onLocalStatus("WAITING_HALL"),this._conversation):this._onJoinPart2(s)}catch(i){throw $._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return c(this,null,function*(){var t,i,a,s,o,l,u;d.debug("Join conversation part 2"),$._activationMutex=!0;try{if(this._participantState=K.ACCEPTED,!this._conversation||!this._mediaSource)throw new F(w.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._processConnection(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),$._delayedHangup)throw new F(w.CANCELED);let g=Object.values(this._participants),T;p.batchParticipantsOnStart&&(T=I.mapSharedParticipants(g.filter(A=>!A.isInRoom)));let b=[];if((i=(t=e==null?void 0:e.rooms)==null?void 0:t.rooms)!=null&&i.length)for(let A of e.rooms.rooms)b.push({id:A.id,name:A.name,participantCount:A.participantCount,participantIds:yield Promise.all(((s=(a=A==null?void 0:A.participantIds)==null?void 0:a.map)==null?void 0:s.call(a,this._getExternalIdByParticipantId.bind(this)))||[]),participants:(o=A==null?void 0:A.participants)!=null&&o.participants?this._participantListChunkToExternalChunk(A.participants):void 0,active:A.active,muteStates:A.muteStates});let D=(u=(l=e==null?void 0:e.rooms)==null?void 0:l.roomId)!=null?u:null;return yield this._processConnectionSharedMovieInfo(e),f.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),T,{rooms:b,roomId:D}),this._onConversationParticipantListChunk(e),f.onLocalStatus("WAITING"),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),$._current=this,p.batchParticipantsOnStart||this._setParticipantsStatus(g,"WAITING"),this._openTransport(g,!1),this._conversation}catch(g){throw this._close(g,"Unable to join conversation"),g}finally{$._activationMutex=!1}})}onPush(a){return c(this,arguments,function*(e,t=z.USER,i){if($._activationMutex)throw d.warn("Conversation: there is already running activation"),new F(w.REJECTED);$._activationMutex=!0;try{let s=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new F(w.UNKNOWN_ERROR);if(!s.conversation.participants.find(l=>{var u;return l.state===K.CALLED&&l.id===((u=this._conversation)==null?void 0:u.userId)}))throw d.log("Push rejected (there is an active call)"),_.log(v.PUSH,"rejected"),new F(w.REJECTED);if(yield this._processConnection(s),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),_.log(v.PUSH,"accepted"),$._current=this,$._delayedHangup)throw new F(w.CANCELED);$._activationMutex=!1}catch(s){throw $._activationMutex=!1,this._close(s,"Unable to handle inbound call push"),s}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(di.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>I.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return c(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new F(w.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(v.ACCEPT_CONCURRENT,e),d.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),f.onCallAccepted(),this._state="ACTIVE",this._participantState=K.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return c(this,null,function*(){var t;if(this._state!=="IDLE")throw _.log(v.ERROR,"acceptIncoming"),d.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new F(w.UNKNOWN_ERROR);this._state="PROCESSING",d.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let i=this._mediaSource.getMediaSettings();this._logWithMediaSettings(v.ACCEPT_INCOMING,i),this._signaling.changeMediaSettings(i),yield this._signaling.acceptCall(i),this._participantState=K.ACCEPTED;let a=Object.values(this._participants),s;if(p.batchParticipantsOnStart&&(s=I.mapSharedParticipants(a)),f.onCallAccepted(),f.onLocalStream(this._mediaSource.getStream(),i),f.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),s),p.useParticipantListChunk){let u=yield this._getInitialParticiapntListChunk();(t=u==null?void 0:u.participants)==null||t.forEach(g=>{let T=I.composeId(g),b=this._participants[T];b&&(b.movieShareInfos=g.movieShareInfos)}),this._onConversationParticipantListChunk({participants:u})}f.onLocalStatus("WAITING"),this._toggleJoinAvailability(),this._changeNeedRate();let o=kt(this._getMuteStatesForCurrentRoom(),Pe.MUTE),l=kt(this._getMuteStatesForCurrentRoom(),Pe.MUTE_PERMANENT);for(let u of[o,l])u.length&&(yield this._processMuteState({mediaOptions:u,stateUpdated:!0}));return this._state="ACTIVE",this._changeFeatureSet(),p.batchParticipantsOnStart||this._setParticipantsStatus(a,"WAITING"),this._openTransport(a,!0),this._conversation}catch(i){throw this._close(i,"Unable to accept call"),i}})}decline(){return c(this,null,function*(){var e;if(this._state!=="IDLE")throw _.log(v.ERROR,"declineIncoming"),d.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",d.debug("Decline incoming call"),this._logWithMediaSettings(v.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=K.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(w.REJECTED)),this._close(new F(w.REJECTED))})}hangup(){return c(this,null,function*(){d.debug("Hangup");let e=this._state==="ACTIVE"?w.HUNGUP:w.CANCELED;_.log(v.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new F(e))):f.onHangup(new F(w.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return c(this,null,function*(){if(!this._signaling.ready){this._close(new F(w.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),a=null;i.type==="error"&&(i.error==="call-unfeasible"?a=i.status:a=w.UNKNOWN_ERROR);let s=i.participant;yield this._onAddParticipant(I.composeId(s),s,a)})}removeParticipant(e,t=!1){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var a;if(!this._transport)return;let i=[];for(let s of e)(s.state===K.CALLED||s.state===K.ACCEPTED)&&(this._transport.isAllocated(s.id)||this._transport.allocate(s.id,t)),s.state===K.ACCEPTED&&i.push(s.id);i.length&&this._transport.open(i,null,!!((a=this._conversation)!=null&&a.observer))}_close(e,t){t&&d.error(t,e),d.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(w.FAILED):_.log(v.ERROR,e.hangup),$._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([w.CANCELED,w.NOT_FRIENDS,w.CALLEE_IS_OFFLINE,w.CALLER_IS_BLOCKED,w.CALLER_IS_REJECTED].indexOf(e.hangup)!==-1||e.hangup===w.REJECTED&&!e.remote){f.onHangup(e,i),this.destroy();return}if(e.hangup===w.HUNGUP&&(!e.remote||this._participantState===K.CALLED)){f.onHangup(e,i),this.destroy();return}if(e.hangup===w.MISSED&&!e.remote){f.onHangup(e,i),this.destroy();return}if(e.hangup===w.SOCKET_CLOSED&&$._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===w.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=K.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),_.destroy(),this._conversation=null,this._myLastRequestedLayouts={},$._current=null,$._delayedHangup=!1,f.onHangup(e||new F(w.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;d.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),_.destroy(),this._conversation=null,this._myLastRequestedLayouts={},$._current=null,$._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return c(this,null,function*(){let t=yield this._api.getConversationParams(e);d.debug("Api.getConversationParams",t);let i=[],{turn_server:a,stun_server:s}=t;if(s&&i.push(s),a){let o=a.urls.filter((l,u,g)=>g.indexOf(l)===u);o.push(`${o[o.length-1]}?transport=tcp`),i.push({urls:o,username:a.username,credential:a.credential})}return p.iceServers=i,p.wssBase=t.endpoint,p.wssToken=t.token,t.client_type&&(p.clientType=t.client_type),p.externalUserType=t.external_user_type,t})}_addGeoParamsToEndpoint(e,t){return t.isp_as_no&&(e+=`&ispAsNo=${t.isp_as_no}`),t.isp_as_org&&(e+=`&ispAsOrg=${t.isp_as_org}`),t.loc_cc&&(e+=`&locCc=${t.loc_cc}`),t.loc_reg&&(e+=`&locReg=${t.loc_reg}`),e}_startConversation(e,t,i,a,s="",o=!1,l=!1,u){return c(this,null,function*(){let g=I.uuid();d.debug("Conversation: start",{conversationId:g,opponentIds:e,opponentType:t,direction:i});let T=a.includes(oe.VIDEO),b=yield this._api.startConversation(g,e,t,T,s,o,l,{onlyAdminCanShareMovie:u});d.debug("Api.startConversation",b);let D=yield this._getConversationParams(b.id);b.endpoint=this._addGeoParamsToEndpoint(b.endpoint,D);let A=yield this._connectSignaling(Fe.START,b);return yield this._setConversation(b,A,i),A})}_joinConversation(e){return c(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:a,joinLink:s,observedIds:o,payload:l}=e;d.debug("Conversation: join",{conversationId:t,joinLink:s,observedIds:o});let u=i.includes(oe.VIDEO),g;if(t)g=yield this._api.joinConversation(t,u,a);else if(s)g=yield this._api.joinConversationByLink(s,u,o,l);else throw new F(w.UNKNOWN_ERROR);d.debug("Api.joinConversation",g),yield this._getConversationParams(g.id);let T=yield this._connectSignaling(Fe.JOIN,g);return yield this._setConversation(g,T,Ke.JOINING),T})}_prepareConversation(a){return c(this,arguments,function*(e,t=z.USER,i){d.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let s=this._api.getUserId();if(!s)throw new F(w.UNKNOWN_ERROR);let o=yield this._getConversationParams(e),l=o.device_idx||0,u=`${p.wssBase}?userId=${s}&entityType=${t}&deviceIdx=${l}&conversationId=${e}&token=${p.wssToken}`;u=this._addGeoParamsToEndpoint(u,o);let g={id:e,peerId:i,endpoint:u,is_concurrent:!1,p2p_forbidden:!1,device_idx:l},T=yield this._connectSignaling(Fe.ACCEPT,g);return $._current&&($._current._participantState===K.ACCEPTED||$._current._participantState===K.CALLED)?(d.log("Push rejected (busy)"),_.log(v.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(w.BUSY),Promise.reject({hangup:w.BUSY})):($._current&&($._current.destroy(),$._current=null),yield this._setConversation(g,T,Ke.INCOMING,t),T)})}_createParticipant(e){return c(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:_e(),participantState:{},state:K.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[],isInRoom:!1},e);if(e.externalId){let a=I.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(a,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return(i=t.observedIds)!=null&&i.length&&(t.externalId.observer=!0),this._setParticipantMarkers(t,t.markers),t})}_getParticipantId(e){return c(this,null,function*(){try{let t=I.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new F(w.NETWORK_ERROR),t),t}})}_setConversation(s,o,l){return c(this,arguments,function*(e,t,i,a=z.USER){yield this._prepareParticipants(t.conversation.participants);let u=this._api.getUserId(),g=e.device_idx||0;if(!u){let D=(t.conversation.participants||[]).find(A=>I.comparePeerId(A.peerId,t.peerId));if(!D)throw new F(w.UNKNOWN_ERROR);u=Number(D.id),D.idType&&(a=D.idType),D.deviceIdx&&(g=D.deviceIdx),this._api.setUserId(u)}let T=I.composeParticipantId(u,a,g),b=yield this._getParticipantId(T);this._conversation={userId:u,compositeUserId:T,externalId:b,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],featuresPerRole:t.conversation.featuresPerRole,id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||"DIRECT",direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordsInfoByRoom:new Map,muteStates:new Map,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1,asrInfo:null,roomId:null},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(p.forceRelayPolicy=e.p2p_forbidden),_.log(v.RELAY_POLICY,p.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new F(w.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.featuresPerRole=e.conversation.featuresPerRole,this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||"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 Ei;return this.subscribe(e,"SOURCE_CHANGED",this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,"SCREEN_STATUS",this._onScreenSharingStatus.bind(this)),this._audioFix=new Ot(e),e}_connectSignaling(e,t){return c(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,Ee.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,Ee.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,Ee.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_processConnection(e){return c(this,null,function*(){yield this._registerConnectionParticipants(e),this._processConnectionData(e)})}_prepareParticipants(e){return c(this,null,function*(){let t=e.map(i=>i.id);t.length&&(yield this._api.prepareUserIds(t))})}_onConversationParticipantListChunk(e){let t=e.participants;t&&f.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(this._createParticipantListChunk(t)))}_createParticipantListChunk(e){return Re(Re({},{participants:[],countBefore:0,countAfter:0,markerFound:!1}),e)}_participantListChunkToExternalChunk(e){let t=I.mapSharedParticipants(e.participants.map(i=>{let a=I.composeId(i);return this._participants[a]}));return ze(Re({},e),{participants:t})}_registerConnectionParticipants(e){return c(this,null,function*(){var i,a,s,o,l,u;yield this._registerParticipants(e.conversation.participants),(i=e.participants)!=null&&i.participants&&(yield this._registerParticipants((a=e.participants)==null?void 0:a.participants));let t=(o=(s=e==null?void 0:e.rooms)==null?void 0:s.rooms)!=null?o:[];for(let g of t)yield this._registerParticipants((u=(l=g==null?void 0:g.participants)==null?void 0:l.participants)!=null?u:[],!0)})}_registerParticipants(e,t=!1){return c(this,null,function*(){if(this._conversation)for(let i of e){let a=I.composeId(i);if(this._isMe(a)){this._conversation.roles=i.roles||[],this._conversation.roles.length&&(d.debug(`Local roles changed: ${i.roles}`),f.onLocalRolesChanged(this._conversation.roles)),yield this._registerParticipantLocalMuteState(i);continue}if(i.state===K.HUNGUP||i.state===K.REJECTED){this._participants[i.id]&&this._removeParticipant(this._participants[i.id],w.HUNGUP);continue}this._registerParticipantInCache(yield this._createParticipant({id:a,externalId:i.externalId&&pe.fromSignaling(i.externalId,i.deviceIdx||0),mediaSettings:_e(i.mediaSettings),participantState:I.mapParticipantState(i),state:i.state,roles:i.roles||[],status:p.batchParticipantsOnStart?"WAITING":null,muteStates:i.muteStates||{},unmuteOptions:i.unmuteOptions||[],observedIds:i.observedIds||[],markers:this._denormalizeMarkers(a,i.markers),movieShareInfos:i.movieShareInfos,isInRoom:t})),i.roles&&i.roles.length&&(d.debug(`Roles for participant [${a}] changed: ${i.roles}`),f.onRolesChanged(this._participants[a].externalId,i.roles))}})}_registerParticipantLocalMuteState(e){return c(this,null,function*(){if(!e.muteStates)return Promise.resolve();let t=kt(e.muteStates,Pe.MUTE),i=kt(e.muteStates,Pe.MUTE_PERMANENT);for(let a of[t,i])a.length&&(yield this._onMuteParticipant({muteStates:e.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:a,stateUpdated:!0}))})}_getStatusByTransportState(e){let t;return e==="CONNECTED"?t="CONNECTED":e==="CONNECTING"||e==="OPENED"?t="CONNECTING":e==="RECONNECTING"&&(t="RECONNECT"),t}_registerParticipantInCache(e){return this._participants[e.id]=e}_getExistedParticipantByIdOrCreate(e){return c(this,null,function*(){return this._participants[e]||this._createParticipant({id:e})})}_getExternalIdByParticipantId(e){return c(this,null,function*(){var t;if(this._isMe(e))return this._conversation.externalId;if(p.useParticipantListChunk)return(yield this._getExistedParticipantByIdOrCreate(e)).externalId;if((t=this._participants[e])!=null&&t.externalId)return this._participants[e].externalId;{let i=yield this._getParticipantId(e);return this._api.cacheExternalId(e,i),i}})}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){return c(this,null,function*(){if(p.useParticipantListChunk){let i=this._registerParticipantInCache(yield this._getExistedParticipantByIdOrCreate(e));return this._setParticipantMarkers(i,t),i}return this._participants[e]})}_warnParticipantNotInConversation(e){d.warn(`Participant [${e}] isn't in conversation`)}_setParticipantMarkers(e,t){return e.markers=this._denormalizeMarkers(e.id,t),e}_denormalizeMarkers(e,t){if(!t)return null;let i=Object.values(t).find(a=>"ts"in a&&"rank"in a);return Object.entries(t).reduce((a,[s,o])=>(a[s]=ze(Re(Re({},i),o),{id:e}),a),{})}_processConnectionData(e){return c(this,null,function*(){this._processRooms(e),this._processMuteStates(e),e.conversation.pinnedParticipantId&&(yield this._onPinParticipant(e.conversation.pinnedParticipantId)),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(oi.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)})}_processRooms(e){var i,a;let t=(a=(i=e.rooms)==null?void 0:i.roomId)!=null?a:null;this._onRoomSwitched(t,!0)}_processMuteStates(e){var i,a,s;this._setMuteStatesForRoomId((i=e.conversation)==null?void 0:i.muteStates,null);for(let o of(s=(a=e.rooms)==null?void 0:a.rooms)!=null?s:[])this._setMuteStatesForRoomId(o.muteStates,o.id);let t=this._getMuteStatesForCurrentRoom();this._onMuteParticipant({muteStates:t,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(t),muteAll:!0,stateUpdated:!0,roomId:this._conversation.roomId})}_processRecordInfos(e){var t,i,a,s;this._onRecordInfo((t=e.conversation.recordInfo)!=null?t:null);for(let o of(a=(i=e.rooms)==null?void 0:i.rooms)!=null?a:[])this._onRecordInfo((s=o.recordInfo)!=null?s:null,o.id)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new xi(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new Xt,this.subscribe(this._transport,"STATE_CHANGED",this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,"LOCAL_STATE_CHANGED",this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,"REMOTE_TRACK_ADDED",this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,"REMOTE_TRACK_REMOVED",this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,"REMOTE_ALL_STALL",this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,"REMOTE_DATA_STATS",this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,"SIGNALLED_STALLED_PARTICIPANTS",this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,"TOPOLOGY_CHANGED",this._onTopologyChanged.bind(this)),this.subscribe(this._transport,"NETWORK_STATUS",this._onNetworkStatus.bind(this)),this.subscribe(this._transport,"REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,"PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this)),this.subscribe(this._transport,"ASR_TRANSCRIPTION",this._onAsrTranscription.bind(this)),this.subscribe(this._transport,"ANIMOJI_STREAM",this._onAnimojiStream.bind(this));let e=this._conversation.direction===Ke.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===K.ACCEPTED||t.state===K.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new Li(this._transport),this.subscribe(this._volumesDetector,"VOLUMES_DETECTED",this._onVolumesDetected.bind(this)),this._speakerDetector=new Ni(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,"SPEAKER_CHANGED",this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Zt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new ei(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=C.getCameras().length,t=C.getMicrophones().length;d.debug("Cameras: "+e+(C.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(C.hasMicrophonePermission()?"✔":"✖")),_.log(v.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){_.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===K.CALLED||e.state===K.ACCEPTED||this._state==="CLOSE"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),this._participants[e.id]&&(t===w.HUNGUP?this._setParticipantsStatus([e],"HANGUP"):this._setParticipantsStatus([e],"ERROR",t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:"CAMERA",stopStream:!0}]),delete this._participants[e.id],f.onRemoteRemoved(e.externalId,e.markers)))}_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,a;(t=e.remoteStream)==null||t.getTracks().forEach(s=>s.stop()),(i=e.secondStream)==null||i.getTracks().forEach(s=>s.stop()),(a=e.mediaSource)==null||a.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){d.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return c(this,null,function*(){d.debug(`Add new participant [${e}]`);let a=this._participants[e];if(a&&(a.state===K.ACCEPTED||a.state===K.CALLED)){d.warn(`Participant [${a.id}:${a.state}] is already in conversation`);return}a||(a=this._registerParticipantInCache(yield this._createParticipant({id:e,externalId:t.externalId&&pe.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:_e(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}))),this._setParticipantsStatus([a],"WAITING"),i?(a.state=K.HUNGUP,this._removeParticipant(a,i)):this._transport&&(a.state=K.CALLED,this._transport.allocate(a.id,!0),_.log(v.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(a))})}_onRemoveParticipant(e){d.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=ms;i++){let a=I.compose(e,i),s=this._participants[a];s&&t.push(s)}if(!t.length){this._warnParticipantNotInConversation(e);return}if(this._transport)for(let i of t)this._transport.close(i.id);_.log(v.REMOVE_PARTICIPANT)}changeDevice(e){return c(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new Ot(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(re.UNKNOWN)})}stopVideoTrack(){return this._mediaSource.stopVideoTrack()}toggleScreenCapturing(e){return c(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(re.UNKNOWN)})}disableScreenCapturing(){return c(this,null,function*(){return this._mediaSource?this._mediaSource.disableScreenCapturing():Promise.reject(re.UNKNOWN)})}toggleAnimojiCapturing(e){this._mediaSource&&this._mediaSource.toggleAnimojiCapturing(e)}setAnimojiSvg(e,t=null,i=null){if(!this._transport)return;let a=!t,s=t!=null?t:this._conversation.compositeUserId;if(e instanceof ArrayBuffer){let o=i!=null?i:this._conversation.externalId.id;this._transport.setAnimojiSvg(s,{svg:e,userId:o,isMe:a});return}this._transport.setAnimojiSvg(s,{svg:e,isMe:a})}setVideoStream(e,t=!1){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return c(this,null,function*(){if(this._mediaSource)return _.log(v.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return c(this,null,function*(){if(this._mediaSource)return _.log(v.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return c(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let a of e){let s=typeof a.uid=="object"?a.uid:pe.fromId(a.uid),o=pe.toString(s);i[o]=a.priority}for(let a of Object.values(this._participants)){let s=pe.toString(a.externalId);i.hasOwnProperty(s)&&(t[a.id]=i[s])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return c(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return c(this,null,function*(){let t={};return t[He(e)]={keyFrameRequested:!0},this._signaling.updateDisplayLayout(t)})}requestTestMode(e,t){return c(this,null,function*(){return this._signaling.requestTestMode(e,t)})}updateDisplayLayout(e){return c(this,null,function*(){if(e.length<1||!this._signaling.ready)return;d.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let a of e){let s=typeof a.uid=="object"?a.uid:pe.fromId(a.uid),o=this._api.getCachedOkIdByExternalId(s);if(!o){let T=pe.toString(s);d.log(`Unknown participant external ID ${T}`);continue}let l=I.compose(o,s.deviceIdx),u=He({participantId:l,mediaType:a.mediaType,streamName:a.streamName}),g=this._participants[l];g?g.lastRequestedLayouts[u]=a:this._isMe(l)&&(this._myLastRequestedLayouts[u]=a),At(a)?(this._isMe(l)&&delete this._myLastRequestedLayouts[u],this._streamIdByStreamDescription.has(u)&&!this._cooldownTimestampByStreamDescription.has(u)&&this._cooldownTimestampByStreamDescription.set(u,Date.now())):(this._cooldownTimestampByStreamDescription.delete(u),!this._streamIdByStreamDescription.has(u)&&p.videoTracksCount>0&&this._streamIdByStreamDescription.set(u,null),t[u]=a),a.mediaType==="SCREEN"&&!At(a)&&pt(Ci(l))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>p.videoTracksCount;){let a=i.next();if(a.done){d.error("Cannot accommodate all streaming requests: tracks available "+p.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(a.value),t[a.value]={stopStream:!0}}yield this._sendUpdateDisplayLayout(t)})}feedback(e){return this._signaling.feedback(e)}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(d.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=Yt(e),a=this._participants[i.participantId],{externalId:s}=this._conversation,o=this._isMe(i.participantId);if(a){if(i.streamName&&(i.mediaType==="STREAM"||i.mediaType==="MOVIE")){let l={stream:null,streamName:i.streamName,mediaType:i.mediaType};o?f.onLocalLive(s,l):f.onRemoteLive(a.externalId,l)}else o||f.onRemoteStream(a.externalId,null);_.log(v.PAT_DEALLOCATED)}else d.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return c(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[a,s]of Object.entries(t.errorCodeByParticipantId||{})){let o=Yt(a),l=this._participants[o.participantId];if(l){let u;typeof s!="number"?(d.warn(`Unexpected error code ${s} received for participant ${o.participantId}`),u=ta.UNKNOWN_ERROR):u=ia(s),i.push({externalId:l.externalId,errorReason:u})}}if(i&&i.length)throw new ti("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 a=i.value;if(a[1]+us>Date.now())break;let o=a[0];this._stopStreaming(o),e[o]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e)}_onParticipantSourcesUpdate(e){if(this._conversation){d.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return c(this,null,function*(){d.log("Promoted in waiting hall",!e.demote),e.demote?(d.log("Kicked from waiting hall"),this._close(new F(w.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(a){return c(this,arguments,function*(e,t=0,i=[]){d.log(`Chat room updated: ${e}`);let s=[],o=[];i.length&&(i.forEach(l=>{if(l.externalId){let u=fe.fromSignaling(l.externalId);s.push(u),this._api.cacheExternalId(l.id.id,u)}else o.push(I.decomposeId(l.id.id).id)}),o.length&&!s.length&&(s=yield this._api.getExternalIdsByOkIds(o))),f.onChatRoomUpdated(e,t,s)})}_onSharedMovieUpdate(e){return c(this,null,function*(){let{externalId:t}=this._conversation,{data:i}=e;for(let a of i)if(this._isMe(a.participantId))f.onLocalLiveUpdate(t,a);else{let o=yield this._getExternalIdByParticipantId(a.participantId);o&&f.onRemoteLiveUpdate(o,a)}})}_onSharedMovieInfoStarted(e){return c(this,null,function*(){d.log(`Shared movie started data received: ${e.notification}`),yield this._processSharedMovieInfo(e.movieShareInfo)})}_processSharedMovieInfos(e){return c(this,null,function*(){e&&(yield Promise.all(e.map(t=>this._processSharedMovieInfo(t))))})}_processSharedMovieInfo(e){return c(this,null,function*(){var a;if(!e)return;let{externalId:t}=this._conversation;if(this._isMe(e.initiatorId))f.onLocalSharedMovieInfo(t,e);else{let s=yield this._getExternalIdByParticipantId(e.initiatorId);s&&f.onRemoteSharedMovieInfo(s,e)}this._transport.getTopology()==="SERVER"&&this._transport.getState()==="IDLE"&&this._participantState!==K.CALLED&&this._transport.open(this._transport.allocated(),null,!!((a=this._conversation)!=null&&a.observer),!0)})}_processConnectionSharedMovieInfo(e){return c(this,null,function*(){let t=e.conversation.participants.find(i=>this._isMe(I.composeId(i)));yield this._processSharedMovieInfos(t==null?void 0:t.movieShareInfos)})}_onSharedMovieInfoStopped(e){return c(this,null,function*(){d.log(`Shared movie stopped data received: ${e.notification}`);let{externalId:t}=this._conversation,{initiatorId:i,movieId:a,source:s}=e,o={initiatorId:i,movieId:a,source:s};if(this._isMe(i))f.onLocalSharedMovieStoppedInfo(t,o);else{let u=yield this._getExternalIdByParticipantId(i);u&&f.onRemoteSharedMovieStoppedInfo(u,o)}})}_onFeaturesPerRoleChanged(e){d.log(`Features per role changed: ${e.notification}`),f.onFeaturesPerRoleChanged(e.featuresPerRole)}_waitForStreamIfNeeded(e){var g,T,b;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||t.mediaType==="ANIMOJI")return;let i=t.participantId,a=this._participants[i];if(p.producerScreenDataChannel&&t.mediaType==="SCREEN"&&!((g=a.mediaSettings)!=null&&g.isFastScreenSharingEnabled))return;let s=He(t),o=this._sequenceNumberByStreamDescription.get(s);if(o&&o>e.sequenceNumber){d.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${o}`),_.log(v.PAT_OUTDATED_RESPONSE);return}let l=e.streamId,u=e.rtpTimestamp?this._getWaitingTime(l,e.rtpTimestamp):0;if(u<=0){this._streamWaitTimerByStreamDescription.delete(s);let{externalId:D}=this._conversation,A=this._isMe(i);if(!a&&!A){_.log(v.PAT_ERROR,"participantMissing"),d.error(`Could not find participant by ID: ${i}`);return}let Y=A?D:a.externalId,H=this._streamByStreamId.get(l);if(!H){_.log(v.PAT_ERROR,"streamNotFound"),d.error(`Could not find stream by ID: ${l}`);return}_.log(v.PAT_ALLOCATED),this._streamIdByStreamDescription.set(s,l);let ge=(T=e.participantStreamDescription)==null?void 0:T.mediaType;if(ge==="STREAM"||ge==="MOVIE"){if((b=e.participantStreamDescription)!=null&&b.streamName){let W={streamName:e.participantStreamDescription.streamName,stream:H,mediaType:ge};A?f.onLocalLive(Y,W):f.onRemoteLive(Y,W)}}else if(p.producerScreenTrack&&ge==="SCREEN")f.onRemoteScreenStream(a.externalId,H);else if(!A){let W=(p.producerScreenTrack?null:a.secondStream)||H;f.onRemoteStream(a.externalId,W)}}else{d.debug(`Waiting for ${u} until stream ${l} for ${s} is switched`);let D=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),u);this._streamWaitTimerByStreamDescription.set(s,D)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(He(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(He(i)))return i}else{let i={participantId:t,mediaType:"CAMERA"};if(this._streamIdByStreamDescription.has(He(i)))return i;let a={participantId:t,mediaType:"SCREEN"};if(this._streamIdByStreamDescription.has(He(a)))return a}return d.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,[$e.ADMIN,$e.CREATOR]):!1}_checkAdminRole(){if(this._conversation&&!I.includesOneOf(this._conversation.roles,[$e.ADMIN,$e.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}startAsr(e){return c(this,null,function*(){yield this._signaling.startAsr(e)})}stopAsr(){return c(this,null,function*(){yield this._signaling.stopAsr()})}requestAsr(e){return c(this,null,function*(){yield this._signaling.requestAsr(e)})}muteParticipant(){return c(this,arguments,function*(e=null,t,i=[],a=null){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i,a)})}enableFeatureForRoles(e,t){return c(this,null,function*(){yield this._signaling.enableFeatureForRoles(e,t)})}pinParticipant(e,t){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return c(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return c(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Hr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return c(this,null,function*(){if(!this._signaling)return Promise.reject();let a=null;e&&(a=Aa(e));let s=yield this._signaling.getWaitingHall(a,t,i);if(s.error)return Promise.reject(s.message);let o=s.participants||[],l=[],u=[],g=null;return o.length&&(o.forEach(T=>{if(T.externalId){let b=fe.fromSignaling(T.externalId);l.push(b),this._api.cacheExternalId(T.id.id,b)}else u.push(I.decomposeId(T.id.id).id)}),u.length&&!l.length&&(l=yield this._api.getExternalIdsByOkIds(u)),s.hasMore&&(g=Ma(o[o.length-1].id))),{participants:l,pageMarker:g,totalCount:s.totalCount||0}})}promoteParticipant(e,t){return c(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return c(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let a=t.messages[i];yield this._onChatMessage(a)}}})}customData(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return c(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return c(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(a){return c(this,arguments,function*({movieId:e,gain:t,metadata:i}){let s={movieId:e};(t||t===0)&&(s.gain=t),i&&(s.metadata=i);let o=yield this._signaling.addMovie(s);if(o.error)throw new Error(o.error);return{movieId:o.movieId,streamType:o.streamType}})}updateMovie(e){return c(this,null,function*(){let t=yield this._signaling.updateMovie(e);if(t.error)throw new Error(t.error)})}removeMovie(e){return c(this,null,function*(){let t={movieId:e},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}updateRooms(e,t){return c(this,null,function*(){let i=yield this._signaling.updateRooms(e,t);if(i.error)throw new Error(i.error)})}activateRooms(e,t){return c(this,null,function*(){let i=yield this._signaling.activateRooms(e,t);if(i.error)throw new Error(i.error)})}switchRoom(e,t){return c(this,null,function*(){let i=yield this._signaling.switchRoom(e,t);if(i.error)throw new Error(i.error)})}removeRooms(e){return c(this,null,function*(){let t=yield this._signaling.removeRooms(e);if(t.error)throw new Error(t.error)})}startStream(e=!1,t=null,i=null,a="DIRECT_LINK",s=null,o=null){return c(this,null,function*(){let l={movieId:i,name:t,privacy:a,groupId:s,roomId:o,streamMovie:!e},u=yield this._signaling.startStream(l);if(u.error)return Promise.reject(u.message)})}stopStream(e=null){return c(this,null,function*(){if((yield this._signaling.stopStream({roomId:e})).error)return Promise.reject()})}recordSetRole(e,t,i=null){return c(this,null,function*(){let a=yield this._signaling.recordSetRole(e,t,i);if(a.error)throw new Error(a.error)})}getStreamInfo(){return c(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(i){return c(this,arguments,function*({video:e,effect:t}){var a;if(e.width<p.videoMinWidth||e.height<p.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(t){if(t.width<p.videoMinWidth||t.height<p.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");p.videoEffectMaxHeight=t.height,p.videoEffectMaxWidth=t.width}return p.videoMaxWidth=e.width,p.videoMaxHeight=e.height,d.debug("Set local video resolution:",`video ${e.width}x${e.height}`+(t?`, effect ${t.width}x${t.height}`:"")),(a=this._mediaSource)==null?void 0:a.setResolution({video:e,effect:t})})}videoEffect(e){return c(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}getParticipants(e){return c(this,null,function*(){let t=e.externalIds.map(o=>({id:o.id,type:p.externalUserType})),i=yield this._signaling.getParticipants(t);if(i.error)throw new Error(i.error);let a=i.participants,s=this._transport.getState();return Promise.all(a.map(o=>c(this,null,function*(){var u;let l=I.composeId(o);return this._createParticipant({id:l,externalId:o.externalId&&pe.fromSignaling(o.externalId,o.deviceIdx||0),mediaSettings:_e(o.mediaSettings),participantState:I.mapParticipantState(o),state:o.state,roles:o.roles||[],status:(u=this._getStatusByTransportState(s))!=null?u:"WAITING",muteStates:o.muteStates||{},unmuteOptions:o.unmuteOptions||[],observedIds:o.observedIds||[],markers:this._denormalizeMarkers(l,o.markers)})}))).then(I.mapSharedParticipants)})}getParticipantListChunk(e){return c(this,null,function*(){var l;d.log("Request participant list chunk",e);let t=yield this._signaling.getParticipantListChunk(e);if(t.error)throw new Error(t.error);let i=this._createParticipantListChunk(t.chunk),a=i.participants.filter(u=>{let g=I.composeId(u);return!this._participants[g]});yield this._registerParticipants(a);let s=(l=this._transport)==null?void 0:l.getState();return i.participants.forEach(u=>{var b,D;let g=I.composeId(u),T=this._participants[g];T.status=(b=this._getStatusByTransportState(s))!=null?b:"WAITING",T.movieShareInfos=u.movieShareInfos,Object.assign(T.mediaSettings,_e(u.mediaSettings)),Object.assign(T.muteStates,u.muteStates),T.unmuteOptions=(D=u.unmuteOptions)!=null?D:T.unmuteOptions,this._openTransport([T],!0)}),this._participantListChunkToExternalChunk(i)})}_getInitialParticiapntListChunk(){return c(this,null,function*(){let e=p.participantListChunkInitIndex,t=p.participantListChunkInitCount,i="GRID",a=yield this._signaling.getParticipantListChunk({listType:i,fromIdx:e,count:t});return d.debug("Get initial participant list chunk",a.chunk),a.chunk})}_onLocalMediaStreamChanged(e){return c(this,null,function*(){var t,i;this._conversation&&(d.debug("Local media stream changed",e.mediaSettings),f.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)!=null&&t.waitingHall)&&!((i=this._conversation)!=null&&i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return c(this,null,function*(){var t,i;if(d.log("Screen sharing changed",e.track,e.mediaSettings),p.consumerScreenTrack){let a=e.track?new MediaStream([e.track]):null;f.onScreenStream(a,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)!=null&&t.waitingHall)&&!((i=this._conversation)!=null&&i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){d.debug(`Remote media settings changed [${e}]`,t);let{externalId:i}=this._conversation;if(this._isMe(e)){f.onLocalMediaSettings(i,t);return}let s=this._participants[e];if(!s){this._warnParticipantNotInConversation(e);return}s.mediaSettings=t,this._state==="ACTIVE"&&f.onRemoteMediaSettings(s.externalId,t,s.markers),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t)}_changeRemoteParticipantState(e,t){d.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];if(!i){this._warnParticipantNotInConversation(e);return}i.participantState=t||{},this._state==="ACTIVE"&&f.onRemoteParticipantState(i.externalId,i.participantState,i.markers)}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(d.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),f.onRolesChanged(e.externalId,e.roles))}_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,e.roomId);case x.RECORD_STOPPED:return this._onRecordInfo(null,e.roomId);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,e.markers);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);case x.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e);case x.FEEDBACK:return this._onFeedback(e);case x.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e);case x.MOVIE_SHARE_STARTED:return this._onSharedMovieInfoStarted(e);case x.MOVIE_SHARE_STOPPED:return this._onSharedMovieInfoStopped(e);case x.ROOMS_UPDATED:return this._onRoomsUpdated(e);case x.ROOM_UPDATED:return this._onRoomUpdated(e);case x.ROOM_PARTICIPANTS_UPDATED:return this._onRoomParticipantsUpdated(e);case x.FEATURES_PER_ROLE_CHANGED:return this._onFeaturesPerRoleChanged(e);case x.PARTICIPANT_ANIMOJI_CHANGED:return this._onParticipantAnimojiChanged(e);case x.ASR_STARTED:return this._onAsrInfo(e.asrInfo);case x.ASR_STOPPED:return this._onAsrInfo(null)}}_onSignalingReconnect(e){return c(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._conversation.featuresPerRole=e.conversation.featuresPerRole,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?yield this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&(yield this._onPinParticipant(this._conversation.pinnedParticipantId,!0))),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),a=[];for(let s of e.conversation.participants){let o=I.composeId(s),l=s.roles||[];if(this._isMe(o)){t=_e(s.mediaSettings),Ht(this._conversation.roles,l)||this._onRolesChanged(o,l);continue}a.push(o);let u=this._participants[o];if(!u)yield this._onJoinedParticipant({participantId:s.id,participant:s,mediaSettings:s.mediaSettings});else{let g=_e(s.mediaSettings);_a(g,u.mediaSettings)||this._changeRemoteMediaSettings(o,g);let T=I.mapParticipantState(s),b=u.participantState;I.isEqualParticipantState(T,b)||this._changeRemoteParticipantState(o,T),Ht(l,u.roles)||this._onRolesChanged(u.id,l)}}for(let s of i)a.indexOf(s)<0&&this._removeParticipant(this._participants[s],w.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){d.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return c(this,null,function*(){let t=I.composeMessageId(e),i=I.getPeerIdString(e.peerId);if(d.debug(`Participant accepted call [${t}]`),this._conversation&&this._isMe(t)){this._close(new F(w.MISSED),"Call accepted on other device");return}let a=this._participants[t];a||(a=this._registerParticipantInCache(yield this._createParticipant({id:t,mediaSettings:_e(e.mediaSettings)}))),a.state=K.ACCEPTED,a.mediaSettings=_e(e.mediaSettings),this._logWithMediaSettings(v.ACCEPTED_OUTGOING,a.mediaSettings),this._conversation&&this._conversation.direction===Ke.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([a.id],i),this._changeRemoteMediaSettings(t,a.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){return c(this,null,function*(){d.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=I.composeMessageId(e);if(this._conversation&&this._isMe(t)){this._close(new F(e.reason,{remote:!0}));return}yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers);let i=this._participants[t];if(!i){this._warnParticipantNotInConversation(t);return}this._transport&&this._transport.close(t),i.state=e.reason===w.REJECTED?K.REJECTED:K.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,w.HUNGUP)})}_onAddedParticipant(e){return c(this,null,function*(){var a,s;d.debug(`Participant added [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state!==K.HUNGUP&&i.state!==K.REJECTED){d.debug(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&pe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:_e(e.participant.mediaSettings),state:e.participant.state,participantState:I.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}))),i.state=K.CALLED,i.mediaSettings=_e((a=e.participant)==null?void 0:a.mediaSettings),i.participantState=I.mapParticipantState(e.participant),i.roles=((s=e.participant)==null?void 0:s.roles)||[],this._setParticipantsStatus([i],"WAITING"),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),f.onParticipantAdded(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return c(this,null,function*(){var a,s;d.debug(`Participant joined [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state===K.ACCEPTED){d.warn(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&pe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:_e(e.participant.mediaSettings),state:e.participant.state,participantState:I.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},movieShareInfos:e.participant.movieShareInfos,unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[],markers:this._denormalizeMarkers(t,e.participant.markers)}))),this._conversation&&this._conversation.direction===Ke.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=K.ACCEPTED,i.mediaSettings=_e(e.mediaSettings),i.participantState=I.mapParticipantState(e.participant),i.roles=e.participant.roles||[],(a=this._transport)!=null&&a.isAllocated(i.id)?this._setParticipantsStatus([i],"CONNECTED"):this._setParticipantsStatus([i],"WAITING"),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((s=this._conversation)!=null&&s.observer))),f.onParticipantJoined(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i),f.onMuteStates(i.muteStates,i.unmuteOptions,Object.keys(i.muteStates),!1,!1,i.externalId,void 0,!0),yield this._processSharedMovieInfos(i.movieShareInfos)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new F(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){return c(this,null,function*(){let t=I.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,_e(e.mediaSettings))})}_onParticipantStateChanged(e){return c(this,null,function*(){let t=I.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),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._conversation.featuresPerRole=e.featuresPerRole,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),f.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return c(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=_e(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({captureScreen:i.isScreenSharingEnabled,fastScreenSharing:i.isFastScreenSharingEnabled,captureAudio:i.isAudioSharingEnabled}))})}_onSettingsUpdate(e){d.debug("Got settings update notification",e);let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Tr(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){d.debug("Got video quality update notification",e);let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,a={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=Tr(this._serverSettings,a),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=I.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return c(this,null,function*(){f.onDeviceSwitched(oe.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return c(this,null,function*(){let t=I.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),f.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return c(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=I.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),f.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e,t=null){return c(this,null,function*(){var s;if(!this._conversation)return;let i=this._conversation.recordsInfoByRoom.get(t),a=!1;if(!i!=!e?a=!0:i&&e&&(a=i.recordMovieId!==e.recordMovieId),a)if(this._conversation.recordsInfoByRoom.set(t,e),e){let o=yield this._getParticipantId(e.initiator);f.onRecordStarted(o,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId,t)}else f.onRecordStopped(t);e&&this._transport.getTopology()==="SERVER"&&this._participantState!==K.CALLED&&this._transport.open(this._transport.allocated(),null,!!((s=this._conversation)!=null&&s.observer),!0)})}_changeRecordInfoForRoom(){return c(this,null,function*(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.recordsInfoByRoom.get(e);if(t){let i=yield this._getParticipantId(t.initiator);f.onRecordStarted(i,t.recordMovieId,t.recordStartTime,t.recordType,t.recordExternalMovieId,t.recordExternalOwnerId,e)}else f.onRecordStopped(e)})}_onParticipantAnimojiChanged(e){return c(this,null,function*(){if(this._conversation){let t=yield this._getParticipantId(e.participantId);f.onParticipantVmojiUpdate(t)}})}_onAsrInfo(e){return c(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.asrInfo!=!e?t=!0:this._conversation.asrInfo&&e&&(t=this._conversation.asrInfo.movieId!==e.movieId),t)if(e){let i=yield this._getParticipantId(e.initiatorId);f.onAsrStarted(i,e.movieId)}else f.onAsrStopped();this._conversation.asrInfo=e})}_onAsrTranscription(e){return c(this,null,function*(){if(!this._conversation)return;let t=yield this._getParticipantId(e.participantId);f.onAsrTranscription(t,e.text,e.timestamp,e.duration)})}_onRolesChanged(e,t){if(this._conversation&&this._isMe(e)&&!Ht(this._conversation.roles,t)){d.debug(`Local roles changed: ${t}`),this._conversation.roles=t,f.onLocalRolesChanged(t),this._processMuteState({mediaOptions:kt(this._getMuteStatesForCurrentRoom(),Pe.MUTE_PERMANENT),stateUpdated:!0}),I.includesOneOf(t,[$e.ADMIN,$e.CREATOR])&&this._refreshRooms(!0);return}let i=this._participants[e];i&&!Ht(i.roles,t)&&(d.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,f.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return c(this,null,function*(){var g;if(!this._conversation)return;let i=(g=e.roomId)!=null?g:null,a=e.muteStates||{},s=e.unmuteOptions||[],o=e.mediaOptions||[],l=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&!this._isMe(e.participantId)){if(!this._isCallAdmin()){d.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let T=this._participants[e.participantId];T&&(d.debug(`Mute states for participant [${e.participantId}] changed`,a),f.onMuteStates(a,s,o,e.muteAll,e.unmute,T.externalId,l==null?void 0:l.externalId,e.stateUpdated,e.requestedMedia,e.roomId));return}let u=this._getMuteStatesForRoomId(i);if(!(I.isObjectsEquals(u,a)&&I.isArraysEquals(this._conversation.unmuteOptions,s)&&!o.length)){if(this._setMuteStatesForRoomId(a,i),this._conversation.unmuteOptions=s,this._isMe(e.adminId)){e.muteAll&&f.onMuteStates(a,s,o,e.muteAll,e.unmute,null,this._conversation.externalId,e.stateUpdated,e.requestedMedia,e.roomId);return}yield this._processMuteState({mediaOptions:o,muteAll:e.muteAll,unmute:e.unmute,serverSettings:t,admin:l,stateUpdated:e.stateUpdated,requestedMedia:e.requestedMedia,roomId:e.roomId})}})}_changeMuteStatesForRoom(e,t){if(!this._conversation)return;this._conversation.unmuteOptions=[];let i=this._getMuteStatesForRoomId(t),a=this._getMuteStatesForRoomId(e),s=Object.keys(i),o=Object.keys(a);this._processMuteState({mediaOptions:Array.from(new Set([...s,...o])),roomId:e,muteAll:!0,stateUpdated:!0})}_processMuteState(g){return c(this,arguments,function*({mediaOptions:e=[],muteAll:t=!1,unmute:i=!1,serverSettings:a=null,admin:s=null,stateUpdated:o,requestedMedia:l,roomId:u=null}){if(!this._conversation||!this._mediaSource||this._participantState!==K.ACCEPTED)return;let T=Object.assign({},this._getMuteStatesForRoomId(u)),b=this._conversation.unmuteOptions,D=this._mediaSource.getMediaSettings(),A=Object.entries(T);for(let[Y,H]of A)if(!(H!==Pe.MUTE&&H!==Pe.MUTE_PERMANENT)&&(this._isCallAdmin()&&H===Pe.MUTE_PERMANENT&&!t&&(T[Y]=Pe.MUTE),!(!e.includes(Y)||i)))switch(Y){case oe.VIDEO:D.isVideoEnabled&&!(a!=null&&a.isVideoEnabled)&&(f.onDeviceSwitched(oe.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case oe.AUDIO:D.isAudioEnabled&&!(a!=null&&a.isAudioEnabled)&&(f.onDeviceSwitched(oe.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case oe.SCREEN_SHARING:D.isScreenSharingEnabled&&!(a!=null&&a.isScreenSharingEnabled)&&(f.onDeviceSwitched(oe.SCREEN_SHARING,!1),yield this.disableScreenCapturing());break;case oe.AUDIO_SHARING:D.isAudioSharingEnabled&&!(a!=null&&a.isAudioSharingEnabled)&&(f.onDeviceSwitched(oe.AUDIO_SHARING,!1),yield this.toggleScreenCapturing({captureScreen:D.isScreenSharingEnabled,fastScreenSharing:D.isFastScreenSharingEnabled,captureAudio:!1}));break}f.onMuteStates(T,b,e,t,i,null,s==null?void 0:s.externalId,o,l,u)})}_onPinParticipant(e,t=!1,i){return c(this,null,function*(){if(!this._conversation)return;let a=this._conversation.pinnedParticipantId;if(a&&a!==e)if(this._isMe(a))f.onLocalPin(!0);else{let s=yield this._getExternalIdByParticipantId(a);s&&f.onPinnedParticipant(s,!0,this._denormalizeMarkers(e,i))}if(this._isMe(e))f.onLocalPin(t);else{let s=yield this._getExternalIdByParticipantId(e);s&&f.onPinnedParticipant(s,t,this._denormalizeMarkers(e,i))}this._conversation.pinnedParticipantId=t?null:e})}_onOptionsChanged(e){this._conversation&&!jr(this._conversation.options,e)&&(this._conversation.options=e,f.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,a]of Object.entries(e)){let s;if(this._isMe(i)||i==="")s=this._conversation.networkRating;else if(this._participants[i])s=this._participants[i].networkRating;else continue;if(s!==a)if(this._isMe(i)||i==="")this._conversation.networkRating=a,f.onLocalNetworkStatusChanged(a);else{let o=this._participants[i];o.networkRating=a,t.push({uid:o.externalId,rating:a})}}if(t.length===0)return;d.log("Received network status update: ",e),f.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(i){if(p.producerScreenTrack){f.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,p.videoTracksCount>0){let a=e;if(!this._streamIdByStreamDescription.has(a)){d.error("Received remote stream notification for a participant that has no track associated with it",a);return}let s=this._streamIdByStreamDescription.get(a);if(!s||this._streamWaitTimerByStreamDescription.has(a)){d.log("Delaying secondary stream start/stop until main stream becomes available",a);return}let o=this._streamByStreamId.get(s);if(!o){_.log(v.PAT_ERROR,"streamNotFound"),d.error(`Could not find stream by ID: ${s}`);return}f.onRemoteStream(i.externalId,i.secondStream||o)}else{let a=t||i.remoteStream;a&&f.onRemoteStream(i.externalId,a)}}}_onAnimojiStream(e,t){if(this._isMe(e)){f.onVmojiStream(t,this._mediaSource.getMediaSettings());return}let i=this._participants[e];i&&f.onRemoteVmojiStream(i.externalId,t)}_onPeerConnectionClosed(e){e==="SERVER"&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(ci.ADD_PARTICIPANT);f.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&f.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,a]of Object.entries(e)){let s=this._participants[i];s&&s.externalId&&t.push({uid:s.externalId,volume:a.real})}f.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(f.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return c(this,null,function*(){d.debug(`Transport state has changed: ${t}`,e);let i=this._getStatusByTransportState(t);if(!i)return;let a=e.reduce((s,o)=>{if(o in this._participants){let l=this._participants[o];s.push(l),t==="CONNECTED"&&(l.remoteStream||(l.mediaSettings&&this._changeRemoteMediaSettings(o,l.mediaSettings),this._changeRemoteParticipantState(o,l.participantState)),this._updateDisplayLayoutFromCache(o))}else this._warnParticipantNotInConversation(o);return s},[]);a.length&&this._setParticipantsStatus(a,i)})}_onTransportLocalStateChanged(e){return c(this,null,function*(){var t;if(d.debug(`Local transport state has changed: ${e}`),e==="CONNECTED"&&(f.onLocalStatus("CONNECTED"),((t=this._transport)==null?void 0:t.getTopology())==="SERVER")){let i=Object.values(this._myLastRequestedLayouts);yield this.updateDisplayLayout(i)}e==="CONNECTING"&&f.onLocalStatus("CONNECTING"),e==="RECONNECTING"&&f.onLocalStatus("RECONNECT"),e==="FAILED"&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(w.FAILED)),this._close(new F(w.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return c(this,null,function*(){if(e.endsWith(we.AUDIO_MIX))d.debug("Remote audio mix track added"),this._audioOutput.add(i),f.onRemoteMixedAudioStream(t);else if(e.startsWith(we.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))d.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{d.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let a=this._participants[e];if(a||(d.warn(`Conversation: track added before participant [${e}]`),a=this._registerParticipantInCache(yield this._createParticipant({id:e})),this._setParticipantsStatus([a],"WAITING"),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(f.onSpeakerChanged(a.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(a.id)&&this._transport.allocate(a.id,!1),i.kind==="audio"&&(this._audioOutput.add(i),p.preserveAudioTracks||t.removeTrack(i)),a.remoteStream!==t){if(a.remoteStream=t,a.secondStream)return;f.onRemoteStream(a.externalId,t)}a.mediaSettings&&this._changeRemoteMediaSettings(e,a.mediaSettings),p.batchParticipantsOnStart||this._changeRemoteParticipantState(e,a.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(d.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!==we.AUDIO_MIX){let a=this._participants[e];if(!a||a.remoteStream&&a.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e==="DIRECT"&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let a in this._participants)if(this._participants.hasOwnProperty(a)){let s=this._participants[a];e||this._lastStalled[a]?t.push(s):i.push(s)}t.length&&this._setParticipantsStatus(t,"RECONNECT"),i.length&&this._setParticipantsStatus(i,"CONNECTED")}_onRemoteSignalledStall(e){let t={},i=[],a=[];e.forEach(s=>{if(t[s]=!0,!this._lastStalled[s]){let o=this._participants[s];o&&!this._remoteAllStalled&&i.push(o)}delete this._lastStalled[s]}),Object.keys(this._lastStalled).forEach(s=>{let o=this._participants[s];o&&!this._remoteAllStalled&&a.push(o)}),i.length&&this._setParticipantsStatus(i,"RECONNECT"),a.length&&this._setParticipantsStatus(a,"CONNECTED"),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!C.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)!=null&&t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(d.debug("Toggle join availability",{available:t,chatId:e}),f.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return c(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!=="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 a=e.reduce((s,o)=>(o.status!==t&&(o.status=t,p.batchParticipantsOnStart?s.push(o.externalId):f.onParticipantStatus(o.externalId,t,i)),s),[]);a.length&&p.batchParticipantsOnStart&&f.onRemoteStatus(a,t,i)}_onJoinLinkChanged(e){f.onJoinLinkChanged(e.joinLink)}_onRoomsUpdated(e){return c(this,null,function*(){var i,a;let t={};for(let s of Object.keys(Et)){let o=e.updates[s];o&&(t[s]={rooms:yield Promise.all(((a=(i=o==null?void 0:o.rooms)==null?void 0:i.map)==null?void 0:a.call(i,this._convertRoomToExternal.bind(this)))||[]),roomIds:o==null?void 0:o.roomIds,deactivated:o==null?void 0:o.deactivated})}f.onRoomsUpdated(t)})}_onRoomUpdated(e){return c(this,null,function*(){let t=yield this._convertRoomToExternal(e.room);e.events.some(i=>i===Et.UPDATE)&&(e.muteStates!==void 0&&this._setMuteStatesForRoomId(e.muteStates,e.roomId),e.recordInfo!==void 0&&this._conversation.recordsInfoByRoom.set(e.roomId,e.recordInfo)),f.onRoomUpdated(e.events,e.roomId,t,e.deactivate)})}_convertRoomToExternal(e){return c(this,null,function*(){var s,o,l,u,g,T;if(!e)return null;let[t,i,a]=yield Promise.all([Promise.all(((o=(s=e==null?void 0:e.participantIds)==null?void 0:s.map)==null?void 0:o.call(s,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((u=(l=e==null?void 0:e.addParticipantIds)==null?void 0:l.map)==null?void 0:u.call(l,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((T=(g=e==null?void 0:e.removeParticipantIds)==null?void 0:g.map)==null?void 0:T.call(g,this._getExternalIdByParticipantId.bind(this)))||[])]);return{id:e.id,name:e.name,participantCount:e.participantCount,participantIds:t,addParticipantIds:i,removeParticipantIds:a,participants:e.participants,active:e.active,muteStates:e.muteStates}})}_onRoomParticipantsUpdated(e){return c(this,null,function*(){var T,b,D,A,Y;let t=this._transport.getState(),i=(T=e.roomId)!=null?T:null,[a,s]=yield Promise.all([Promise.all(((D=(b=e.addedParticipantIds)==null?void 0:b.map)==null?void 0:D.call(b,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((Y=(A=e==null?void 0:e.addedParticipants)==null?void 0:A.map)==null?void 0:Y.call(A,H=>c(this,null,function*(){var W;let ge=I.composeId(H);return this._createParticipant({id:ge,externalId:H.externalId&&pe.fromSignaling(H.externalId,H.deviceIdx||0),mediaSettings:_e(H.mediaSettings),participantState:I.mapParticipantState(H),state:H.state,roles:H.roles||[],status:(W=this._getStatusByTransportState(t))!=null?W:"WAITING",muteStates:H.muteStates||{},unmuteOptions:H.unmuteOptions||[],observedIds:H.observedIds||[],markers:this._denormalizeMarkers(ge,H.markers)})})))||[])]),o=!1;for(let H of s)H.id===this._conversation.compositeUserId&&(o=!0),this._registerParticipantInCache(H);this._openTransport(s,!0);let l=[],u=[];if(e!=null&&e.removedParticipantMarkers){for(let H of e.removedParticipantMarkers)H.GRID&&u.push(this._getExternalIdByParticipantId(H.GRID.id));l=yield Promise.all(u)}o&&(yield this._onRoomSwitched(i));let g={roomId:i,participantCount:e.participantCount,addedParticipantIds:a,addedParticipants:I.mapSharedParticipants(s),removedParticipantMarkers:e==null?void 0:e.removedParticipantMarkers,removedParticipantIds:l};f.onRoomParticipantsUpdated(g)})}_onRoomSwitched(e,t=!1){return c(this,null,function*(){if(!this._conversation||this._conversation.roomId===e)return;let i=this._conversation.roomId;if(this._conversation.roomId=e,t){f.onRoomStart(e);return}f.onRoomSwitched(e),e!==null&&!this._isCallAdmin()&&(yield this._refreshRooms(!1)),this._changeRecordInfoForRoom(),this._changeMuteStatesForRoom(e,i)})}_refreshRooms(e){return c(this,null,function*(){var a,s;let i=(s=(a=(yield this._signaling.getRooms(e)).rooms)==null?void 0:a.rooms)!=null?s:[];for(let o of i)this._setMuteStatesForRoomId(o.muteStates,o.id),this._conversation.recordsInfoByRoom.set(o.id,o.recordInfo);e&&f.onRoomsUpdated({[Et.UPDATE]:{rooms:yield Promise.all(i.map(this._convertRoomToExternal.bind(this)))}})})}_onFeedback(e){return c(this,null,function*(){let t=s=>c(this,null,function*(){return(yield this._registerParticipantAndSetMarkersIfChunkEnabled(s)).externalId}),i=e.feedback.map(s=>c(this,null,function*(){let o=s.items.map(u=>c(this,null,function*(){if(u.participantId===this._conversation.compositeUserId)return Promise.resolve(ze(Re({},u),{participantId:this._conversation.externalId}));let g=yield t(u.participantId);return ze(Re({},u),{participantId:g})})),l=yield Promise.all(o);return ze(Re({},s),{items:l})})),a=yield Promise.all(i);f.onFeedback(a,e.roomId)})}_isMe(e){var t;return e===((t=this._conversation)==null?void 0:t.compositeUserId)}_getMuteStatesForRoomId(e=null){var i;return(i=this._conversation.muteStates.get(e))!=null?i:{}}_getMuteStatesForCurrentRoom(){return this._getMuteStatesForRoomId(this._conversation.roomId)}_setMuteStatesForRoomId(e={},t=null){this._conversation.muteStates.set(t,e)}},U=$;U._delayedHangup=!1;var ti=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,ti.prototype),this.participantErrors=t}};var Nt,ii=null;function hs(){return c(this,null,function*(){var n;if(p.apiEnv!=="AUTO")return p.apiEndpoint;try{let r=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),t=yield(yield fetch(r,{method:"GET",mode:"cors",cache:"no-cache"})).json(),i=(n=t==null?void 0:t.Answer[0])==null?void 0:n.data;if(!i)throw new Error("Wrong DNS response");return d.debug("Resolved API endpoint",i),i}catch(r){return d.warn("Failed to resolve API endpoint using DNS, default is used",r),p.apiEndpoint}})}function wa(){return c(this,null,function*(){return Nt||ii||(ii=hs(),Nt=yield ii,ii=null,Nt)})}function xa(){if(!p.apiKey)throw new F(re.API,{message:"Required argument apiAppKey not passed"})}function Cr(t){return c(this,arguments,function*(n,r={},e=!1){if(!window.Blob||!window.navigator.sendBeacon)return;yield wa();let i=Na(n,r,e),a=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${Nt}/fb.do`,a)})}function La(t){return c(this,arguments,function*(n,r={},e=!1){yield wa();let i=Na(n,r,e);return _s(i)})}function _s(n){return c(this,null,function*(){return new Promise((r,e)=>{let t=new XMLHttpRequest;t.open("POST",`${Nt}/fb.do`,!0),t.setRequestHeader("Content-type","application/x-www-form-urlencoded"),t.onreadystatechange=()=>{if(t.readyState!==XMLHttpRequest.DONE)return;let i;try{i=JSON.parse(t.responseText)}catch(a){i={result:t.responseText}}t.status!==200||i.hasOwnProperty("error_msg")?e(i):r(i)},t.send(n)})})}function Na(n,r={},e=!1){r.method=n,r.format="JSON",r.application_key||(r.application_key=p.apiKey),e||(ae.sessionKey?r.session_key=ae.sessionKey:ae.accessToken&&(r.access_token=ae.accessToken));for(let[i,a]of Object.entries(r))typeof a=="object"&&(r[i]=JSON.stringify(a));let t="";for(let[i,a]of Object.entries(r))t&&(t+="&"),t+=`${i}=${encodeURIComponent(a)}`;return t}var fs=10,Ss=700,vs=3e3,Ut=class extends st{constructor(){super(...arguments);this._userId=null;this._externalUidsCache=new Map;this._extrnalUidsBatch=new Set;this._extrnalUidsBatchTimeout=null}_callUnsafe(a){return c(this,arguments,function*(e,t={},i=!1){let s=o=>c(this,null,function*(){try{return yield La(e,t,i)}catch(l){if(!l.hasOwnProperty("error_msg")&&(o++,d.debug(`${e} network error, attempt ${o}...`),o<fs))return yield I.delay(Math.min(o*Ss,vs)),s(o);throw d.warn(e,"error",l),l}});return s(0)})}_call(a){return c(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(s){d.warn("Api call error",s);let o=re.API;switch(s.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:o=w.SERVICE_DISABLED;break;case 1102:o=w.CALLEE_IS_OFFLINE;break;case 1103:o=w.NOT_FRIENDS;break;case 1104:case 1106:o=w.EXTERNAL_API_ERROR;break;case 1113:o=w.CALLER_IS_REJECTED;break}throw new F(o,{message:s.error_msg,code:s.error_code})}})}userId(e){return c(this,null,function*(){let t=I.decomposeId(e).id;return ae.isEmpty()?fe.fromId(String(t)):(yield this._prepareUserIdsByOkIdsBatched([t]),fe.fromString(this._externalUidsCache.get(t)))})}prepareUserIds(e){return c(this,null,function*(){ae.isEmpty()||(yield this._prepareUserIdsByOkIdsBatched(e))})}_prepareUserIdsByOkIdsBatched(e){return e.some(i=>!this._externalUidsCache.has(i))?(e.forEach(i=>this._extrnalUidsBatch.add(i)),this._extrnalUidsBatchTimeout||(this._extrnalUidsBatchPromise=new Promise(i=>{this._extrnalUidsBatchTimeout=window.setTimeout(()=>{if(this._extrnalUidsBatch.size>0){let a=[...this._extrnalUidsBatch];this._extrnalUidsBatch.clear(),this._getExternalIdsByOkIds(a).then(s=>{for(let o in s)s.hasOwnProperty(o)&&this._externalUidsCache.set(parseInt(o,10),s[o]);i()})}this._extrnalUidsBatchTimeout=null},p.api.userIdsByOkBatchedTimeout)})),this._extrnalUidsBatchPromise):Promise.resolve()}authorize(){return c(this,null,function*(){if(!this._uuid){let t=Ye.get("uuid");t||(t=I.uuid(),Ye.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)),ae.sessionKey=t.session_key,ae.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&f.onTokenExpired(),new F(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})};Cr("log.externalLog",t)}init(){xa()}joinConversation(e,t=!1,i){return c(this,null,function*(){let a={conversationId:e,isVideo:t,protocolVersion:p.protocolVersion};return i&&(a.chatId=i),this._call("vchat.joinConversation",a)})}createConversation(s){return c(this,arguments,function*(e,t="",i=!1,{onlyAdminCanShareMovie:a}={}){let o=this._preareStartConversationData({conversationId:e,isVideo:!1,joiningAllowed:!0,payload:t,requireAuthToJoin:i,onlyAdminCanShareMovie:a});return this._startConversation(o)})}startConversation(g,T,b){return c(this,arguments,function*(e,t,i,a=!1,s="",o=!1,l=!1,{onlyAdminCanShareMovie:u}={}){let D=this._preareStartConversationData({conversationId:e,isVideo:a,joiningAllowed:o,payload:s,requireAuthToJoin:l,onlyAdminCanShareMovie:u});if(t&&t.length)switch(i){case Be.USER:D.uids=t.join(",");break;case Be.GROUP:D.gid=t[0];break;case Be.CHAT:D.chatId=t[0];break}return this._startConversation(D)})}_preareStartConversationData({conversationId:e,isVideo:t,payload:i="",joiningAllowed:a=!1,requireAuthToJoin:s=!1,onlyAdminCanShareMovie:o}){let l={conversationId:e,isVideo:t,protocolVersion:p.protocolVersion};return a&&(l.createJoinLink=!0),i&&(l.payload=i),p.domain&&(l.domainId=p.domain),p.externalDomain&&(l.externalDomain=p.externalDomain),s&&(l.requireAuthToJoin=!0),o!==void 0&&(l.onlyAdminCanShareMovie=o),l}_startConversation(e){return c(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return c(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return c(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return c(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let a=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(a.uid),a.token})}joinConversationByLink(e,t=!1,i,a){return c(this,null,function*(){let s={joinLink:e,isVideo:t,protocolVersion:p.protocolVersion};return i!=null&&i.length&&(s.observedIds=i.join(",")),p.anonymToken&&(s.anonymToken=p.anonymToken),a&&(s.payload=a),this._call("vchat.joinConversationByLink",s)})}getOkIdsByExternalIds(e){return c(this,null,function*(){let t=fe.fromIds(e),i=[],a={methods:[]},s=[],o=[...this._externalUidsCache.keys()],l=[...this._externalUidsCache.values()];for(let g of t){let T=fe.toString(g),b=l.indexOf(T);b>-1?i.push(Number(o[b])):(s.push(T),a.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:g.id,anonym:g.type==="ANONYM"},onError:"SKIP"}}))}return a.methods.length&&(yield this._call("batch.executeV2",a)).forEach((g,T)=>{if(g.ok){let b=Number(g.ok.ok_id);this._externalUidsCache.set(b,s[T]),i.push(b)}}),i})}getExternalIdsByOkIds(e){return c(this,null,function*(){let t=[],i=[];for(let s of e)this._externalUidsCache.has(s)?t.push(fe.fromString(this._externalUidsCache.get(s))):i.push(s);if(!i.length)return t;let a=yield this._getExternalIdsByOkIds(i);for(let s in a)a.hasOwnProperty(s)&&this._externalUidsCache.set(parseInt(s,10),a[s]);for(let s of i)a.hasOwnProperty(s)&&t.push(fe.fromString(a[s]));return t})}getCachedOkIdByExternalId(e){let t=[...this._externalUidsCache.keys()],i=[...this._externalUidsCache.values()],a=fe.toString(e),s=i.indexOf(a);return s>-1?I.composeUserId(t[s],z.USER):null}cacheExternalId(e,t){let i=I.decomposeId(e).id;this._externalUidsCache.set(i,fe.toString(t))}getConversationParams(e){return c(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:w.HUNGUP};p.anonymToken&&(t.anonymToken=p.anonymToken),Cr("vchat.hangupConversation",t)}removeHistoryRecords(e){return c(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return c(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[a,s]of Object.entries(i.external_ids))t[a]=fe.fromIdToString(s,"USER");if(i.anonym_ids)for(let[a,s]of Object.entries(i.anonym_ids))t[a]=fe.fromIdToString(s,"ANONYM");return t}catch(i){return t}})}};var Ui=class{requestAsr(r){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,1),t.setUint8(1,r?0:1),e}};var j=require("messagepack");var Ua=(N=>(N.RECOVER="recover",N.ACCEPT_CALL="accept-call",N.ADD_PARTICIPANT="add-participant",N.REMOVE_PARTICIPANT="remove-participant",N.HANGUP="hangup",N.TRANSMIT_DATA="transmit-data",N.ACCEPT_PRODUCER="accept-producer",N.ALLOCATE_CONSUMER="allocate-consumer",N.CHANGE_MEDIA_SETTINGS="change-media-settings",N.CHANGE_PARTICIPANT_STATE="change-participant-state",N.CHANGE_STREAM_PRIORITIES="change-streams-priorities",N.UPDATE_DISPLAY_LAYOUT="update-display-layout",N.REPORT_PERF_STAT="report-perf-stat",N.REPORT_SHARING_STAT="report-sharing-stat",N.RECORD_START="record-start",N.RECORD_STOP="record-stop",N.RECORD_SET_ROLE="record-set-role",N.RECORD_GET_STATUS="record-get-status",N.SWITCH_MICRO="switch-micro",N.SWITCH_TOPOLOGY="switch-topology",N.REQUEST_REALLOC="request-realloc",N.CHAT_MESSAGE="chat-message",N.CHAT_HISTORY="chat-history",N.CUSTOM_DATA="custom-data",N.GRANT_ROLES="grant-roles",N.MUTE_PARTICIPANT="mute-participant",N.ENABLE_FEATURE_FOR_ROLES="enable-feature-for-roles",N.PIN_PARTICIPANT="pin-participant",N.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",N.CHANGE_OPTIONS="change-options",N.GET_WAITING_HALL="get-waiting-hall",N.GET_PARTICIPANT_LIST_CHUNK="get-participant-list-chunk",N.GET_PARTICIPANTS="get-participants",N.PROMOTE_PARTICIPANT="promote-participant",N.REQUEST_TEST_MODE="request-test-mode",N.ADD_MOVIE="add-movie",N.UPDATE_MOVIE="update-movie",N.REMOVE_MOVIE="remove-movie",N.GET_ROOMS="get-rooms",N.UPDATE_ROOMS="update-rooms",N.ACTIVATE_ROOMS="activate-rooms",N.REMOVE_ROOMS="remove-rooms",N.SWITCH_ROOM="switch-room",N.FEEDBACK="feedback",N.ASR_START="asr-start",N.ASR_STOP="asr-stop",N.REQUEST_ASR="request-asr",N))(Ua||{}),L=Ua;function ri(){let n=new DataView(new ArrayBuffer(64)),r=0;function e(t){if(r+t>n.byteLength){let i=new Uint8Array(Math.max(r+t,n.byteLength+64));i.set(new Uint8Array(n.buffer.slice(0,r))),n=new DataView(i.buffer)}}return{put(t){if(e(t.byteLength),Es(t)){let i=t.buffer;new Uint8Array(n.buffer).set(new Uint8Array(i),r)}else new Uint8Array(n.buffer).set(new Uint8Array(t),r);r+=t.byteLength},putI8(t){e(1),n.setInt8(r,t),++r},putI16(t){e(2),n.setInt16(r,t),r+=2},putI32(t){e(4),n.setInt32(r,t),r+=4},putI64(t){e(8);let i=t<0;i&&(t=-t);let a=t/4294967296|0,s=t%4294967296|0;i&&(s=~s+1|0,a=s===0?~a+1|0:~a),n.setUint32(r,a),n.setUint32(r+4,s),r+=8},putUi8(t){e(1),n.setUint8(r,t),++r},putUi16(t){e(2),n.setUint16(r,t),r+=2},putUi32(t){e(4),n.setUint32(r,t),r+=4},putUi64(t){e(8),n.setUint32(r,t/4294967296|0),n.setUint32(r+4,t%4294967296),r+=8},putF(t){e(8),n.setFloat64(r,t),r+=8},ui8array(){return new Uint8Array(n.buffer.slice(0,r))}}}function Es(n){return n.buffer!==void 0}function Bi(n){let r=ArrayBuffer.isView(n)?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),e=0;return{peek(){return r.getUint8(e)},get(t){e+=t;let i=r.byteOffset;return r.buffer.slice(i+e-t,i+e)},getI8(){return r.getInt8(e++)},getI16(){return e+=2,r.getInt16(e-2)},getI32(){return e+=4,r.getInt32(e-4)},getI64(){e+=8;let t=r.getInt32(e-8),i=r.getUint32(e-4);return t*4294967296+i},getUi8(){return r.getUint8(e++)},getUi16(){return e+=2,r.getUint16(e-2)},getUi32(){return e+=4,r.getUint32(e-4)},getUi64(){e+=8;let t=r.getUint32(e-8),i=r.getUint32(e-4);return t*4294967296+i},getF32(){return e+=4,r.getFloat32(e-4)},getF64(){return e+=8,r.getFloat64(e-8)}}}var Ba=0,Fa=1,Is=2,Ts=0,Rs=1,Cs=2,Fi=0,Ps=0,ys=0,bs=1,Vi=class{constructor(){this.participantIdRegistry=null}setParticipantIdRegistry(r){this.participantIdRegistry=r}serializeUpdateDisplayLayout(r,e){let t=ri();j.Int.enc(t,Ba),j.Int.enc(t,Fi),j.Int.enc(t,r),j.Nil.enc(t,null);let i=[];for(let a in e)e.hasOwnProperty(a)&&this.writeLayout(e,a,i);return j.Arr.enc(t,i),j.Nil.enc(t,null),t.ui8array()}writeLayout(r,e,t){let i=r[e],a=ri();if(this.writeStreamDesc(e,a),At(i))j.Int.enc(a,Rs);else if(Er(i))j.Int.enc(a,Cs);else if(j.Int.enc(a,Ts),i.priority!==void 0?j.Int.enc(a,i.priority):j.Nil.enc(a,null),i.width!==void 0&&i.height!==void 0?(j.Int.enc(a,Math.round(i.width)),j.Int.enc(a,Math.round(i.height))):(j.Nil.enc(a,null),j.Nil.enc(a,null)),i.fit!==void 0)switch(i.fit){case"cv":j.Int.enc(a,ys);break;case"cn":j.Int.enc(a,bs);break;default:j.Nil.enc(a,null)}else j.Nil.enc(a,null);t.push(a.ui8array())}writeStreamDesc(r,e){if(this.participantIdRegistry){let t=this.participantIdRegistry.getCompactId(r);if(t!==void 0){j.Int.enc(e,t);return}}j.Str.enc(e,r)}serializePerfStatReport(r,e){let t=ri();return j.Int.enc(t,Fa),j.Int.enc(t,Fi),j.Int.enc(t,r),j.Int.enc(t,e.framesDecoded),j.Int.enc(t,e.framesReceived),t.ui8array()}serializeSharingStatReport(r,e){let t=ri();return j.Int.enc(t,Is),j.Int.enc(t,Fi),j.Int.enc(t,r),j.Int.enc(t,e.minDelay),j.Int.enc(t,e.maxDelay),j.Int.enc(t,e.avgDelay),j.Int.enc(t,e.largeDelayDuration),t.ui8array()}deserializeCommandResponse(r){return c(this,null,function*(){let e;if(r instanceof Blob){let s=Blob.prototype.arrayBuffer?yield r.arrayBuffer():yield fa(r);e=Bi(s)}else e=Bi(r);let t=j.Int.dec(e),i=j.Int.dec(e);if(i!==Fi){d.warn("Unsupported version for command type: "+t+", version "+i);return}if(j.Int.dec(e)!==Ps){d.warn("Error code: "+t+"received for command type: "+t+", version "+i);return}switch(t){case Ba:return this.deserializeUpdateDisplayLayoutResponse(e);case Fa:return this.deserializeReportPerfStatResponse(e);default:return d.warn("unsupported command response commandType: "+t),null}})}deserializeUpdateDisplayLayoutResponse(r){let e=j.Int.dec(r),t=j.Arr.dec(r),i={};return t.forEach(a=>{let s=Bi(a),o=j.Any.dec(s);if(typeof o=="string")i[o]=j.Int.dec(s);else{let l=o,u=He(this.participantIdRegistry.getStreamDescription(l));i[u]=j.Int.dec(s)}}),{type:"response",sequence:e,response:L.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:i}}deserializeReportPerfStatResponse(r){let e=j.Int.dec(r),t=j.Int.dec(r);return{type:"response",sequence:e,response:L.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:t}}};var ji="open",Va=[()=>p.producerScreenTrack,()=>p.videoTracksCount>0,()=>!0,()=>p.filteredMessages,()=>p.consumerScreenTrack,()=>!0,()=>p.movieShare,()=>p.useParticipantListChunk,()=>p.useRooms,()=>p.useVmoji],Ms=10,Me=class extends ct{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.asrCommandsQueue=[];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="+Me._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;this.asrDataChannel=null;this.producerCommandDataChannelEnabled=!1;this.producerCommandSerializationService=new Vi;this.asrCommandSerializer=new Ui}static _getCapabilityFlags(){let e=0;for(let t=0;t<Va.length;t++)Va[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,this.producerCommandSerializationService.setParticipantIdRegistry(e)}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var a;let i=(a=this.participantIdRegistry)==null?void 0:a.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=t=>{this.producerCommandSerializationService.deserializeCommandResponse(t.data).then(i=>{i&&this._handleMessage(i)}).catch(i=>{d.warn("Cannot parse message at producerCommandDataChannel",i)})},this._handleCommandsQueue(this.datachannelCommandsQueue)}useCommandDataChannel(e){this.producerCommandDataChannelEnabled=e}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return c(this,null,function*(){return this.postfix+=`&clientType=${p.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){_.log(v.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=a=>{t(a),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=a=>{i(a),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(a){return c(this,arguments,function*(e,t={},i=0){if(t.participantId){let s=I.decomposeParticipantId(t.participantId),o=I.decomposeId(s.compositeUserId);t=Object.assign({},t,{participantId:o.id,participantType:o.type}),s.deviceIdx&&(t.deviceIdx=s.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(a){return c(this,arguments,function*(e,t={},i=0){let s=o=>{var l,u;if(e===L.REQUEST_ASR)this.asrCommandsQueue.push(o),((l=this.asrDataChannel)==null?void 0:l.readyState)===ji&&this._handleCommandsQueue(this.asrCommandsQueue);else if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(o),((u=this.producerCommandDataChannel)==null?void 0:u.readyState)===ji&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){_.log(v.SOCKET_ACTION,"not_opened"),d.warn("Socket not opened"),o.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(_.log(v.SOCKET_ACTION,"invalid_state"),d.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(o),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((o,l)=>{let u=(T,b=!1)=>{!i||b?l(T):(d.debug("Resending a signaling message",e,g.sequence),i--,s(g))},g={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:o,reject:u};s(g)})})}_isDataChannelCommand(e){return this.producerCommandDataChannelEnabled?e===L.UPDATE_DISPLAY_LAYOUT||e===L.REPORT_PERF_STAT||e===L.REPORT_SHARING_STAT:!1}static _isDataChannelResponseRequired(e){return e===L.UPDATE_DISPLAY_LAYOUT||e===L.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return c(this,null,function*(){return this._send(L.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return c(this,null,function*(){return this._send(L.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e,t){return c(this,null,function*(){return this._send(L.REQUEST_TEST_MODE,{consumer:e,producer:t})})}sendSdp(e,t){return c(this,null,function*(){return this._send(L.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return c(this,null,function*(){return this._send(L.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return c(this,null,function*(){return this._send(L.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},Ms)})}changeParticipantState(e){return c(this,null,function*(){return this._send(L.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return c(this,null,function*(){return this._send(L.ADD_PARTICIPANT,Re({participantId:e},t))})}removeParticipant(e,t=!1){return c(this,null,function*(){return this._send(L.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return c(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(L.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return c(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(L.ACCEPT_PRODUCER,i)})}changePriorities(e){return c(this,null,function*(){return this._send(L.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return c(this,null,function*(){return this._send(L.UPDATE_DISPLAY_LAYOUT,e)})}addMovie(e){return c(this,null,function*(){return this._send(L.ADD_MOVIE,e)})}updateMovie(e){return c(this,null,function*(){return this._send(L.UPDATE_MOVIE,e)})}removeMovie(e){return c(this,null,function*(){return this._send(L.REMOVE_MOVIE,e)})}updateRooms(e,t){return c(this,null,function*(){return this._send(L.UPDATE_ROOMS,{rooms:e,assignRandomly:t})})}activateRooms(e,t){return c(this,null,function*(){return this._send(L.ACTIVATE_ROOMS,{roomIds:e,deactivate:t})})}switchRoom(e,t){return c(this,null,function*(){return this._sendRaw(L.SWITCH_ROOM,{toRoomId:e,participantId:t})})}getRooms(e){return c(this,null,function*(){return this._sendRaw(L.GET_ROOMS,{withParticipants:e})})}removeRooms(e){return c(this,null,function*(){return this._send(L.REMOVE_ROOMS,{roomIds:e})})}startStream(e){return c(this,null,function*(){return this._send(L.RECORD_START,e)})}stopStream(){return c(this,arguments,function*(e={roomId:null}){return this._send(L.RECORD_STOP,e)})}recordSetRole(e,t,i=null){return c(this,null,function*(){return this._send(L.RECORD_SET_ROLE,{participantId:e,role:t,roomId:i})})}getRecordStatus(){return c(this,null,function*(){return this._send(L.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return c(this,null,function*(){return this._send(L.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return c(this,null,function*(){return this._send(L.REQUEST_REALLOC)})}reportPerfStat(e){return c(this,null,function*(){return this._send(L.REPORT_PERF_STAT,e)})}reportSharingStat(e){return c(this,null,function*(){return this._send(L.REPORT_SHARING_STAT,e)})}chatMessage(e,t=null){return c(this,null,function*(){return this._send(L.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return c(this,null,function*(){return this._send(L.CHAT_HISTORY,{count:e})})}customData(e,t){return c(this,null,function*(){return this._send(L.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return c(this,null,function*(){let a={participantId:e,roles:t};return i&&(a.revoke=!0),this._sendRaw(L.GRANT_ROLES,a)})}muteParticipant(e,t,i,a=null){return c(this,null,function*(){return this._sendRaw(L.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i,roomId:a})})}enableFeatureForRoles(e,t){return c(this,null,function*(){return this._sendRaw(L.ENABLE_FEATURE_FOR_ROLES,{feature:e,roles:t})})}pinParticipant(e,t){return c(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(L.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return c(this,null,function*(){return this._send(L.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return c(this,null,function*(){return this._send(L.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return c(this,null,function*(){let a={};return e&&(a.fromId=e),t&&(a.count=t),i&&(a.backward=i),this._send(L.GET_WAITING_HALL,a)})}promoteParticipant(e,t=!1){return c(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(L.PROMOTE_PARTICIPANT,i)})}feedback(e){return c(this,null,function*(){return this._sendRaw(L.FEEDBACK,{key:e})})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}getParticipantListChunk(e){return c(this,null,function*(){return this._send(L.GET_PARTICIPANT_LIST_CHUNK,e)})}getParticipants(e){return c(this,null,function*(){return this._send(L.GET_PARTICIPANTS,{externalIds:e})})}startAsr(e){return c(this,null,function*(){return this._send(L.ASR_START,e)})}stopAsr(){return c(this,null,function*(){return this._send(L.ASR_STOP)})}requestAsr(e){return c(this,null,function*(){return this._send(L.REQUEST_ASR,{request:e})})}setAsrDataChannel(e){this.asrDataChannel=e,this._handleCommandsQueue(this.asrCommandsQueue)}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Fe.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),t=i(t),d.debug("Connecting to "+this.endpoint+this.postfix+t),pt(v.SIGNALING_CONNECTED),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();function i(a){if(!p.useParticipantListChunk)return a;let s=p.participantListChunkInitIndex;a+=`&partIdx=${s}`;let o=p.participantListChunkInitCount;return o!==null&&(a+=`&partCount=${o}`),a}}_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(){d.debug("Socket opened"),_.log(v.SOCKET_ACTION,"opened"),_.logMeasure(v.SIGNALING_CONNECTED),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){_.log(v.SOCKET_ACTION,"parse_error"),d.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(d.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(Ee.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Ee.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(Ee.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(_.log(v.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(_.log(v.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new F(w.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(Ee.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 F(re.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(_.log(v.SOCKET_ACTION,"unknown_message"),d.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(Ee.FAILED,e)}_onError(e){_.log(v.SOCKET_ACTION,"error"),d.error("Signaling error",e)}_onClose(e){_.log(v.SOCKET_ACTION,"closed"),d.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Me.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(Me.RECONNECT_MAX_DELAY,Me.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));d.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),_.log(v.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Fe.RETRY),e)}_handleCommandResponse(e,t){var a;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)):((a=this.socket)==null?void 0:a.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],_.log(v.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Me.WAIT_RESPONSE_DELAY)}_serializeAsrCommand(e){let t=e.params;return this.asrCommandSerializer.requestAsr(t.request)}_handleCommandsQueue(e){var t,i,a,s;for(;e.length>0;){let o=e.shift();if(o.name===L.REQUEST_ASR){if(((t=this.asrDataChannel)==null?void 0:t.readyState)!==ji){o.reject(new Error(`Invalid data channel state: ${(i=this.asrDataChannel)==null?void 0:i.readyState}`));return}let l=this._serializeAsrCommand(o);l!==null&&(this.asrDataChannel.send(l),o.resolve({}))}else if(this._isDataChannelCommand(o.name)){if(((a=this.producerCommandDataChannel)==null?void 0:a.readyState)!==ji){o.reject(new Error(`Invalid data channel state: ${(s=this.producerCommandDataChannel)==null?void 0:s.readyState}`));return}Me._isDataChannelResponseRequired(o.name)&&(o.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:o.name,sequence:o.sequence}),Me.WAIT_RESPONSE_DELAY),this.responseHandlers[o.sequence]=o);let l=this._serializeBinary(o);l!==null&&this.producerCommandDataChannel.send(l)}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){o.reject(new Error("Invalid state or socket already closed"));continue}o.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:o.name,sequence:o.sequence}),Me.WAIT_RESPONSE_DELAY),this.responseHandlers[o.sequence]=o,this.socket.send(this._serializeJson(o))}}}_serializeBinary(e){switch(e.name){case L.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case L.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params);case L.REPORT_SHARING_STAT:return this.producerCommandSerializationService.serializeSharingStatReport(e.sequence,e.params)}return d.warn("cannot get binary data for data channel command: "+e.name),null}_serializeJson(e){let t;e.name===L.UPDATE_DISPLAY_LAYOUT?t=this._convertDisplayLayout(e.params):t=e.params;let i=Object.assign({command:e.name,sequence:e.sequence},t);return JSON.stringify(i)}_convertDisplayLayout(e){let t=e,i={};for(let a in t)t.hasOwnProperty(a)&&(i[a]=Pa(t[a]));return{layouts:i}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new F(re.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Me.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{d.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Fe.RETRY)},Me.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Ae=Me;Ae.RECONNECT_DELAY=p.signalingReconnectDelay,Ae.RECONNECT_MAX_DELAY=p.signalingReconnectMaxDelay,Ae.RECONNECT_MAX_COUNT=p.signalingReconnectMaxCount,Ae.WAIT_CONNECTION_DELAY=p.waitConnectionDelay,Ae.WAIT_RESPONSE_DELAY=p.waitResponseDelay,Ae.WAIT_MESSAGE_DELAY=p.waitMessageDelay;var ja=(e=>(e.KING="KING",e.PAWN="PAWN",e))(ja||{}),Ha=ja;var Hi=class{constructor(r){this._queue=new Array(r).fill(null),this._readCursor=this._writeCursor=this._left=0,this._moveReadCursor=!1}get length(){return this._queue.length}get left(){return this._left}toArray(){return Array.from(this._queue)}add(r){this._moveReadCursor&&(this._readCursor=this.nextCursor(this._readCursor)),this._queue[this._writeCursor]===null&&(this._left+=1),this._queue[this._writeCursor]=r,this._writeCursor=this.nextCursor(this._writeCursor),this._moveReadCursor=this._writeCursor===this._readCursor}nextCursor(r){return(r+1)%this._queue.length}next(){let r=this._queue[this._readCursor];return r&&(this._moveReadCursor=!1,this._queue[this._readCursor]=null,this._readCursor=this.nextCursor(this._readCursor),this._left-=1),r}};var Bt,ne,ai=null,As={getCameras:C.getCameras,getMicrophones:C.getMicrophones,getOutput:C.getOutput,getVideoFacingMode:C.getVideoFacingMode,hasCamera:C.hasCamera,hasMicrophone:C.hasMicrophone,getSavedCamera:C.getSavedCamera,getSavedMicrophone:C.getSavedMicrophone,getSavedOutput:C.getSavedOutput,hasCameraPermission:C.hasCameraPermission,hasMicrophonePermission:C.hasMicrophonePermission,hasPermissions:C.hasPermissions,getUserMedia:C.getUserMedia,getUserVideo:C.getUserVideo,getUserAudio:C.getUserAudio,setResolution:C.setResolution,saveDeviceId:C.saveDeviceId,isBrowserSupported:C.isBrowserSupported,isScreenCapturingSupported:C.isScreenCapturingSupported,os:C.os,isMobile:C.isMobile,browserName:C.browserName,browserVersion:C.browserVersion,baseChromeVersion:C.baseChromeVersion,getAudioContext:C.getAudioContext,isAudioShareSupported:C.isAudioShareSupported},Ds={participantMarkerCompare:I.participantMarkerCompare};function Ga(n){ne=n}function Wa(n){Bt=n}function ks(n){ai=n}function Os(n){p.videoEffects=n}function ws(n,r=null){p.vmoji=n,r&&n.setSDK(r)}function xs(n){return c(this,null,function*(){if(p.set(n),C.browserName()==="Sferum"&&(p.platform=`SFERUM:${C.browserVersion()}`),ne||Ga(new Ut),Bt||Wa(()=>new Ae),p.debug&&(Pr.default.disableLog(!1),d.toggle(!0)),d.log(`Calls SDK ${p.sdkVersion}`,n),yield C.init(),!C.isBrowserSupported())throw new F(re.UNSUPPORTED);d.log("UserAgent:",navigator.userAgent),d.log("Screen resolution:",`${window.screen.width}x${window.screen.height}`),d.log("Permissions:",`Camera: ${C.hasCameraPermission()}, Mic: ${C.hasMicrophonePermission()}`),ne.init()})}function Ls(s){return c(this,arguments,function*(n,r=[oe.AUDIO],e="",t=!1,i=!1,a){let o=[],l=[];if(Array.isArray(n)?o=n.length?n:[]:n&&(o=[n]),o.length&&(l=yield ne.getOkIdsByExternalIds(o),!l.length))throw new F(w.CALLEE_IS_OFFLINE);return Ka(l,Be.USER,r,e,t,i,a)})}function Ka(o){return c(this,arguments,function*(n,r=Be.USER,e,t="",i=!1,a=!1,s){if(U.current())throw d.error("There is already active call"),new F(w.FAILED);return new U(ne,Bt(),ai).onStart(n,r,e,t,i,a,s)})}function Ns(n){return c(this,null,function*(){return $a(n)})}function $a(t){return c(this,arguments,function*(n,r=z.USER,e){if(n===U.id())throw new Error("Push has already been processed");return new U(ne,Bt(),ai).onPush(n,r,e)})}function Us(n){return c(this,null,function*(){return n&&(p.authToken=n),ne.authorize()})}function Bs(){return c(this,arguments,function*(n=[oe.AUDIO]){return vt().accept(n)})}function Fs(){return c(this,null,function*(){let n=U.current();if(n)return n.decline()})}function Vs(e){return c(this,arguments,function*(n,r=[oe.AUDIO]){return qa(n,r)})}function qa(n,r,e){return c(this,null,function*(){if(U.current())throw d.error("There is already active call"),new F(w.FAILED);return new U(ne,Bt(),ai).onJoin({conversationId:n,mediaOptions:r,chatId:e})})}function js(a){return c(this,arguments,function*(n,r=[oe.AUDIO],e,t,i){if(U.current())throw d.error("There is already active call"),new F(w.FAILED);return e&&(p.anonymToken=e),new U(ne,Bt(),ai).onJoin({joinLink:n,mediaOptions:r,observedIds:t,payload:i})})}function Hs(){return c(this,null,function*(){let n=U.current();if(n)return n.hangup();U.hangupAfterInit()})}function Gs(n,r){return c(this,null,function*(){let e=yield ne.getOkIdsByExternalIds([n]);if(!e.length)throw new Error("User not found");return Ja(e[0],r)})}function Ja(n,r){return c(this,null,function*(){let e=U.current();e&&(yield e.addParticipant(I.composeUserId(n,z.USER),r))})}function Ws(n,r=!1){return c(this,null,function*(){let e=yield ne.getOkIdsByExternalIds([n]);return za(e[0],r)})}function za(n,r=!1){return c(this,null,function*(){let e=U.current();e&&(yield e.removeParticipant(I.composeUserId(n,z.USER),r))})}function Ks(n,r){return c(this,null,function*(){let e=U.current();return n==="videoinput"&&qe.contains(r)?(p.videoFacingMode=r,e?(C.isMobile()&&e.stopVideoTrack(),e.changeDevice(n)):Promise.reject()):(yield C.saveDeviceId(n,r))&&e?e.changeDevice(n):Promise.reject()})}function $s(n){return c(this,null,function*(){let r=typeof n=="object"?ze(Re({},n),{fastScreenSharing:n.captureScreen&&n.fastScreenSharing,captureAudio:n.captureScreen&&n.captureAudio&&p.audioShare}):{captureScreen:n,fastScreenSharing:!1,captureAudio:!1},e=U.current();return e?e.toggleScreenCapturing(r):Promise.reject()})}function qs(n){let r=U.current();r&&r.toggleAnimojiCapturing(n)}function Js(n,r=!1){return c(this,null,function*(){let e=U.current();e&&(yield e.setVideoStream(n,r))})}function zs(n){return c(this,null,function*(){let r=U.current();r&&(yield r.toggleLocalVideo(n))})}function Ys(n){return c(this,null,function*(){let r=U.current();r&&(yield r.toggleLocalAudio(n))})}function Qs(n){return c(this,null,function*(){let r=U.current();if(r)return r.setLocalResolution(n)})}function Xs(n){return c(this,null,function*(){let r=U.current();r&&(yield r.changePriorities(n))})}function Zs(n){return c(this,null,function*(){let r=U.current();r&&(yield r.changeParticipantState(n))})}function eo(n){return c(this,null,function*(){let r=U.current();r&&(yield r.updateDisplayLayout(n))})}function to(n,r,e=!1){return c(this,null,function*(){let t=yield ne.getOkIdsByExternalIds([n]);return Ya(t[0],r,e)})}function Ya(n,r,e=!1){return c(this,null,function*(){let t=U.current();t&&(yield t.grantRoles(I.composeUserId(n,z.USER),r,e))})}function io(i){return c(this,arguments,function*({externalId:n=null,muteStates:r,requestedMedia:e=[],roomId:t=null}){let a=null;return n&&(a=(yield ne.getOkIdsByExternalIds([n]))[0]),Qa({uid:a,muteStates:r,requestedMedia:e,deviceIdx:pe.getDeviceIdx(n),roomId:t})})}function Qa(a){return c(this,arguments,function*({uid:n=null,muteStates:r,requestedMedia:e=[],deviceIdx:t=0,roomId:i=null}){let s=U.current();if(s){let o=n?I.composeParticipantId(n,z.USER,t):null;yield s.muteParticipant(o,r,e,i)}})}function ro(n,r=!1){return c(this,null,function*(){let e=yield ne.getOkIdsByExternalIds([n]);return Xa(e[0],r,pe.getDeviceIdx(n))})}function Xa(n,r=!1,e=0){return c(this,null,function*(){let t=U.current();t&&(yield t.pinParticipant(I.composeParticipantId(n,z.USER,e),r))})}function ao(n){return c(this,null,function*(){let r=U.current();r&&(yield r.updateMediaModifiers(n))})}function no(n){return c(this,null,function*(){let r=U.current();r&&(yield r.changeOptions(n))})}function so(n,r=null){return c(this,null,function*(){let e=null;return r&&(e=(yield ne.getOkIdsByExternalIds([r]))[0]),Za(n,e)})}function Za(n,r=null){return c(this,null,function*(){let e=U.current();if(e){let t=r?I.composeUserId(r,z.USER):null;yield e.chatMessage(n,t)}})}function oo(n=10){return c(this,null,function*(){let r=U.current();if(r)return r.chatHistory(n)})}function co(n,r=null){return c(this,null,function*(){let e=null;return r&&(e=(yield ne.getOkIdsByExternalIds([r]))[0]),en(n,e,pe.getDeviceIdx(r))})}function en(n,r=null,e=0){return c(this,null,function*(){let t=U.current();if(t){let i=r?I.composeParticipantId(r,z.USER,e):null;yield t.customData(n,i)}})}function lo(){return c(this,arguments,function*(n="",r=!1,{onlyAdminCanShareMovie:e=!1}={}){return(yield ne.createConversation(I.uuid(),n,r,{onlyAdminCanShareMovie:e})).join_link})}function po(){return c(this,null,function*(){let n=U.current();return n?n.createJoinLink():Promise.reject()})}function uo(){return c(this,null,function*(){let n=U.current();return n?n.removeJoinLink():Promise.reject()})}function mo(n,r){return c(this,null,function*(){return ne.getAnonymTokenByLink(n,r)})}function ho(n){let r=U.current();r&&r.setVolume(n)}function _o(n){p.forceRelayPolicy=n}function go(n=!1,r=null,e=null,t="DIRECT_LINK",i=null,a=null){return c(this,null,function*(){let s=U.current();return s?s.startStream(n,r,e,t,i,a):Promise.reject()})}function fo(n=null){return c(this,null,function*(){let r=U.current();return r?r.stopStream(n):Promise.reject()})}function So(n,r,e=null){return c(this,null,function*(){let t=U.current();if(t){let i=yield ne.getOkIdsByExternalIds([n]),a=pe.getDeviceIdx(n);return t.recordSetRole(I.composeParticipantId(i[0],z.USER,a),r,e)}return Promise.reject()})}function vo(){return c(this,null,function*(){let n=U.current();return n?n.getStreamInfo():Promise.reject()})}function Eo(n){return c(this,null,function*(){let r=U.current();return r?r.addMovie(n):Promise.reject()})}function Io(n){return c(this,null,function*(){let r=U.current();return r?r.updateMovie(n):Promise.reject()})}function To(n){return c(this,null,function*(){let r=U.current();return r?r.removeMovie(n):Promise.reject()})}function Ro(n,r){return c(this,null,function*(){let e=U.current();if(e){let t=[];for(let i of n){let a,s;i.addParticipantIds&&(a=(yield ne.getOkIdsByExternalIds(i.addParticipantIds)).map(o=>I.composeUserId(o,z.USER))),i.removeParticipantIds&&(s=(yield ne.getOkIdsByExternalIds(i.removeParticipantIds)).map(o=>I.composeUserId(o,z.USER))),t.push({id:i.id,name:i.name,participantCount:i.participantCount,addParticipantIds:a,removeParticipantIds:s})}return e.updateRooms(t,r)}return Promise.reject()})}function Co(n,r){return c(this,null,function*(){let e=U.current();return e?e.activateRooms(n,r):Promise.reject()})}function Po(n=null,r=null){return c(this,null,function*(){let e=null;if(r){let i=yield ne.getOkIdsByExternalIds([r]);e=I.composeUserId(i[0],z.USER)}let t=U.current();return t?t.switchRoom(n,e):Promise.reject()})}function yo(n){return c(this,null,function*(){let r=U.current();return r?r.removeRooms(n):Promise.reject()})}function bo(n){p.statisticsInterval=n;let r=U.current();if(r)return r.updateStatisticsInterval()}function Mo(n){Pr.default.disableLog(!n),d.toggle(n)}function Ao(n,...r){p.debugLog&&d.send(n,"[external]",...r)}function Do(n){return c(this,null,function*(){let r=U.current();if(r)return r.videoEffect(n)})}function ko(n){return c(this,null,function*(){let r=U.current();r&&(yield r.setAudioStream(n))})}function Oo(n,r=null,e=null){return c(this,null,function*(){let t=U.current();if(!t)return;let i=e!=null?e:r==null?void 0:r.id,a=null;if(r){let o=(yield ne.getOkIdsByExternalIds([r]))[0];if(!o)throw new Error("Could not get user id to set animoji svg");a=I.composeParticipantId(o,z.USER,pe.getDeviceIdx(r))}t.setAnimojiSvg(n,a,i)})}function wo(n=null,r,e=!1){return c(this,null,function*(){return vt().getWaitingHall(n,r,e)})}function xo(n,r=!1){return c(this,null,function*(){let e=vt(),t=yield ne.getOkIdsByExternalIds([n]);return e.promoteParticipant(I.composeUserId(t[0],z.USER),r)})}function Lo(n){return c(this,null,function*(){return vt().getParticipantListChunk(n)})}function No(n){return c(this,null,function*(){return vt().getParticipants(n)})}function Uo(n){return c(this,null,function*(){return vt().feedback(n)})}function Bo(n,r){return c(this,null,function*(){return vt().enableFeatureForRoles(n,r)})}function vt(){let n=U.current();if(!n)throw new Error("Conversation not found");return n}function Fo(n){return c(this,null,function*(){yield ne.removeHistoryRecords(n)})}function Vo(n){return c(this,null,function*(){let r=U.current();r&&(yield r.startAsr(n))})}function jo(){return c(this,null,function*(){let n=U.current();n&&(yield n.stopAsr())})}function Ho(n){return c(this,null,function*(){let r=U.current();r&&(yield r.requestAsr(n))})}function Go(){return p.sdkVersion}
7
+ "use strict";var rn=Object.create;var Ft=Object.defineProperty,an=Object.defineProperties,nn=Object.getOwnPropertyDescriptor,sn=Object.getOwnPropertyDescriptors,on=Object.getOwnPropertyNames,Mr=Object.getOwnPropertySymbols,cn=Object.getPrototypeOf,Dr=Object.prototype.hasOwnProperty,dn=Object.prototype.propertyIsEnumerable;var kr=Math.pow,Ar=(n,r,e)=>r in n?Ft(n,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[r]=e,Ce=(n,r)=>{for(var e in r||(r={}))Dr.call(r,e)&&Ar(n,e,r[e]);if(Mr)for(var e of Mr(r))dn.call(r,e)&&Ar(n,e,r[e]);return n},Ye=(n,r)=>an(n,sn(r));var ln=(n,r)=>{for(var e in r)Ft(n,e,{get:r[e],enumerable:!0})},Or=(n,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of on(r))!Dr.call(n,i)&&i!==e&&Ft(n,i,{get:()=>r[i],enumerable:!(t=nn(r,i))||t.enumerable});return n};var ni=(n,r,e)=>(e=n!=null?rn(cn(n)):{},Or(r||!n||!n.__esModule?Ft(e,"default",{value:n,enumerable:!0}):e,n)),pn=n=>Or(Ft({},"__esModule",{value:!0}),n);var c=(n,r,e)=>new Promise((t,i)=>{var a=p=>{try{o(e.next(p))}catch(u){i(u)}},s=p=>{try{o(e.throw(p))}catch(u){i(u)}},o=p=>p.done?t(p.value):Promise.resolve(p.value).then(a,s);o((e=e.apply(n,r)).next())});var jo={};ln(jo,{Api:()=>Nt,ArrayDequeue:()=>Bi,BaseApi:()=>ot,BaseLogger:()=>ct,BaseSignaling:()=>dt,CallDirection:()=>$e,CallType:()=>Ve,ChatRoomEventType:()=>si,ConversationFeature:()=>oi,ConversationOption:()=>ci,DebugMessageType:()=>_r,ExternalIdType:()=>Pi,FacingMode:()=>Je,FatalError:()=>ae,HangupReason:()=>V,HangupType:()=>w,MediaOption:()=>ce,MediaTrackKind:()=>Ne,MediaType:()=>At,MuteState:()=>ye,ParticipantState:()=>$,ParticipantStatus:()=>Ci,RecordRole:()=>Fa,RoomsEventType:()=>Et,Signaling:()=>De,SignalingCommandType:()=>L,SignalingConnectionType:()=>Fe,SignalingNotification:()=>x,TransportTopology:()=>at,UserRole:()=>qe,UserType:()=>z,acceptCall:()=>Ls,activateRooms:()=>Io,addMovie:()=>fo,addParticipant:()=>Fs,addParticipantInternal:()=>$a,authorize:()=>xs,browser:()=>ys,callInternal:()=>Ga,callTo:()=>Os,captureScreen:()=>Gs,captureVmoji:()=>Ws,changeConversationOptions:()=>io,changeDevice:()=>Hs,changeParticipantState:()=>Ys,changePriorities:()=>zs,changeVideoEffect:()=>bo,chatHistory:()=>ao,chatMessage:()=>ro,chatMessageInternal:()=>Qa,createJoinLink:()=>oo,customData:()=>no,customDataInternal:()=>Xa,debug:()=>Po,debugMessage:()=>yo,declineCall:()=>Ns,enableFeatureForRoles:()=>Lo,feedback:()=>xo,forceRelayPolicy:()=>uo,getAnonymTokenByLink:()=>lo,getParticipantListChunk:()=>Oo,getParticipants:()=>wo,getStreamInfo:()=>go,getWaitingHall:()=>Do,grantRoles:()=>Xs,grantRolesInternal:()=>Ja,hangup:()=>Vs,init:()=>ks,joinCall:()=>Us,joinCallByLink:()=>Bs,joinCallInternal:()=>Ka,muteParticipant:()=>Zs,muteParticipantInternal:()=>za,pinParticipant:()=>eo,pinParticipantInternal:()=>Ya,processPush:()=>ws,processPushInternal:()=>Wa,promoteParticipant:()=>ko,recordSetRole:()=>_o,removeHistoryRecords:()=>No,removeJoinLink:()=>co,removeMovie:()=>vo,removeParticipant:()=>js,removeParticipantInternal:()=>qa,removeRooms:()=>Ro,requestAsr:()=>Vo,setApi:()=>ja,setAudioStream:()=>Mo,setLocalResolution:()=>Js,setLogger:()=>Ms,setMediaModifiers:()=>to,setSignalingFactory:()=>Ha,setStatisticsInterval:()=>Co,setVideoEffects:()=>As,setVideoStream:()=>Ks,setVmoji:()=>Ds,setVmojiSvg:()=>Ao,setVolume:()=>po,startAsr:()=>Uo,startConversation:()=>so,startStream:()=>mo,stopAsr:()=>Bo,stopStream:()=>ho,switchRoom:()=>To,toggleLocalAudio:()=>qs,toggleLocalVideo:()=>$s,updateDisplayLayout:()=>Qs,updateMovie:()=>So,updateRooms:()=>Eo,utils:()=>bs,version:()=>Fo});module.exports=pn(jo);var Rr=ni(require("webrtc-adapter"));var ot=class{createJoinLink(r){return c(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(r){return c(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(r,e){return c(this,null,function*(){return""})}log(r){}prepareUserIds(r){return c(this,null,function*(){})}getCachedOkIdByExternalId(r){return null}cacheExternalId(r,e){}hangupConversation(r){}removeHistoryRecords(r){return c(this,null,function*(){})}cleanup(){}};var ct=class{log(r,e,t=!1){}destroy(){}};var re=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(r,...e){if(this._handlers.hasOwnProperty(r))for(let t of this._handlers[r])t.apply(this,e)}addEventListener(r,e){if(typeof e!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(r)||(this._handlers[r]=[]),this._handlers[r].push(e),{dispose:this.removeEventListener.bind(this,r,e)}}removeEventListener(r,e){if(!this._handlers.hasOwnProperty(r))return;e||delete this._handlers[r];let t=this._handlers[r].indexOf(e);t>=0&&this._handlers[r].splice(t,1)}subscribe(r,e,t){let i=r.addEventListener(e,t);this._listeners.push(i)}unsubscribe(){this._listeners.forEach(r=>{r.dispose()})}};var dt=class extends re{get ready(){return!0}setParticipantIdRegistry(r){}requestRealloc(){}setEndpoint(r){}setConversationId(r){}readyToSend(){}cleanup(){}requestTestMode(r,e){}getNextCommandSequenceNumber(){return 0}};var wr=(t=>(t.INCOMING="INCOMING",t.OUTGOING="OUTGOING",t.JOINING="JOINING",t))(wr||{}),$e=wr;var xr=(t=>(t.USER="USER",t.GROUP="GROUP",t.CHAT="CHAT",t))(xr||{}),Ve=xr;var Lr=(e=>(e.ATTENDEE="ATTENDEE",e.HAND_UP="HAND_UP",e))(Lr||{}),si=Lr;var Nr=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t.MOVIE_SHARE="MOVIE_SHARE",t))(Nr||{}),oi=Nr;var Ur=(a=>(a.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",a.AUDIENCE_MODE="AUDIENCE_MODE",a.WAITING_HALL="WAITING_HALL",a.ASR="ASR",a.FEEDBACK="FEEDBACK",a))(Ur||{}),ci=Ur;function Br(n,r){if(n.length!==r.length)return!1;for(let e of n)if(!r.includes(e))return!1;return!0}function Vr(n,r){let e=new Set(n);for(let[t,i]of Object.entries(r))i?e.add(t):e.delete(t);return Array.from(e)}var Fr=(A=>(A.CAMERA_PERMISSION="camera",A.MIC_PERMISSION="mic",A.CAMERA_ACCESS="cameralock",A.MIC_ACCESS="miclock",A.MIC_NOT_FOUND="nomic",A.SCREEN_PERMISSION="screenpermission",A.SCREEN_ACCESS="screenlock",A.CONNECTION="connection",A.NETWORK="network",A.UNKNOWN="unknown",A.UNSUPPORTED="unsupported",A.SIGNALING_FAILED="signalingfailed",A.API="api",A.AUTH="auth",A))(Fr||{}),ae=Fr;var jr=(X=>(X.CANCELED="CANCELED",X.REJECTED="REJECTED",X.REMOVED="REMOVED",X.HUNGUP="HUNGUP",X.MISSED="MISSED",X.BUSY="BUSY",X.FAILED="FAILED",X.NETWORK_ERROR="NETWORK_ERROR",X.KILLED="KILLED",X.BANNED="BANNED",X.HAS_ACTIVE_CALL="HAS_ACTIVE_CALL",X.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",X.NOT_FRIENDS="NOT_FRIENDS",X.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",X.CALLER_IS_REJECTED="CALLER_IS_REJECTED",X.UNKNOWN_ERROR="UNKNOWN_ERROR",X.UNSUPPORTED="UNSUPPORTED",X.OLD_VERSION="OLD_VERSION",X.SERVICE_DISABLED="SERVICE_DISABLED",X.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",X.SOCKET_CLOSED="SOCKET_CLOSED",X.ENDED="ENDED",X.KILLED_WITHOUT_DELETE="KILLED_WITHOUT_DELETE",X.ANOTHER_DEVICE="ANOTHER_DEVICE",X))(jr||{}),w=jr;var Hr=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SCREEN_SHARING="SCREEN_SHARING",s.MOVIE_SHARING="MOVIE_SHARING",s.AUDIO_SHARING="AUDIO_SHARING",s.ANIMOJI="ANIMOJI",s))(Hr||{}),ce=Hr;var Gr=(t=>(t.UNMUTE="UNMUTE",t.MUTE="MUTE",t.MUTE_PERMANENT="MUTE_PERMANENT",t))(Gr||{}),ye=Gr;var Wr=(i=>(i.CALLED="CALLED",i.ACCEPTED="ACCEPTED",i.REJECTED="REJECTED",i.HUNGUP="HUNGUP",i))(Wr||{}),$=Wr;var Kr=(t=>(t.UPDATE="UPDATE",t.REMOVE="REMOVE",t.ACTIVATE="ACTIVATE",t))(Kr||{}),Et=Kr;var $r=(i=>(i.START="start",i.ACCEPT="accept",i.JOIN="join",i.RETRY="retry",i))($r||{}),Fe=$r;var qr=(t=>(t.NOTIFICATION="NOTIFICATION",t.FAILED="FAILED",t.RECONNECT="RECONNECT",t))(qr||{}),Ie=qr;var Jr=(B=>(B.TRANSMITTED_DATA="transmitted-data",B.ACCEPTED_CALL="accepted-call",B.HUNGUP="hungup",B.PARTICIPANT_ADDED="participant-added",B.PARTICIPANT_JOINED="participant-joined",B.CLOSED_CONVERSATION="closed-conversation",B.MEDIA_SETTINGS_CHANGED="media-settings-changed",B.PARTICIPANT_STATE_CHANGED="participant-state-changed",B.RATE_CALL_DATA="rate-call-data",B.FEATURE_SET_CHANGED="feature-set-changed",B.TOPOLOGY_CHANGED="topology-changed",B.PRODUCER_UPDATED="producer-updated",B.CONSUMER_ANSWERED="consumer-answered",B.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",B.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",B.SETTINGS_UPDATE="settings-update",B.VIDEO_QUALITY_UPDATE="video-quality-update",B.REGISTERED_PEER="registered-peer",B.SWITCH_MICRO="switch-micro",B.RECORD_STARTED="record-started",B.RECORD_STOPPED="record-stopped",B.REALLOC_CON="realloc-con",B.AUDIO_ACTIVITY="audio-activity",B.SPEAKER_CHANGED="speaker-changed",B.STALLED_ACTIVITY="stalled-activity",B.CHAT_MESSAGE="chat-message",B.CUSTOM_DATA="custom-data",B.ROLES_CHANGED="roles-changed",B.MUTE_PARTICIPANT="mute-participant",B.PIN_PARTICIPANT="pin-participant",B.OPTIONS_CHANGED="options-changed",B.NETWORK_STATUS="network-status",B.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",B.PROMOTE_PARTICIPANT="promote-participant",B.CHAT_ROOM_UPDATED="chat-room-updated",B.PROMOTION_APPROVED="promotion-approved",B.JOIN_LINK_CHANGED="join-link-changed",B.FEEDBACK="feedback",B.MOVIE_UPDATE_NOTIFICATION="movie-update-notification",B.MOVIE_SHARE_INFO="movie-share-info",B.MOVIE_SHARE_STARTED="movie-share-started",B.MOVIE_SHARE_STOPPED="movie-share-stopped",B.ROOM_UPDATED="room-updated",B.ROOMS_UPDATED="rooms-updated",B.ROOM_PARTICIPANTS_UPDATED="room-participants-updated",B.FEATURES_PER_ROLE_CHANGED="features-per-role-changed",B.PARTICIPANT_ANIMOJI_CHANGED="participant-animoji-changed",B.ASR_STARTED="asr-started",B.ASR_STOPPED="asr-stopped",B))(Jr||{}),x=Jr;var zr=(Q=>(Q.ERROR="callError",Q.DEVICES="callDevices",Q.CALL_SPEC_ERROR="callSpecError",Q.ICE_CONNECTION_STATE="callIceConnectionState",Q.ICE_CONNECTION_TYPE="callIceConnectionType",Q.ICE_RESTART="callIceRestart",Q.PUSH="callPush",Q.OUTGOING_CALL="callStart",Q.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",Q.JOIN_CONVERSATION="callJoinConversation",Q.ACCEPTED_OUTGOING="callAcceptedOutgoing",Q.ACCEPT_INCOMING="callAcceptIncoming",Q.DECLINE_INCOMING="callDeclineIncoming",Q.ACCEPT_CONCURRENT="callAcceptConcurrent",Q.HANGUP="callHangup",Q.MEDIA_STATUS="callMediaStatus",Q.DEVICE_CHANGED="callDeviceChanged",Q.SOCKET_ACTION="callSocketAction",Q.ADD_PARTICIPANT="callAddParticipant",Q.REMOVE_PARTICIPANT="callRemoveParticipant",Q.POOR_CONNECTION="callPoorConnection",Q.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",Q.RELAY_POLICY="callForceRelay",Q.PAT_ALLOCATED="patAllocate",Q.PAT_DEALLOCATED="patDeallocate",Q.PAT_ERROR="patError",Q.PAT_WAITING_TIME_ERROR="patWaitingTimeError",Q.PAT_OUTDATED_RESPONSE="patOutdatedResponse",Q))(zr||{}),T=zr;var Yr=(e=>(e.AUDIO_MIX="audio-mix",e.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",e))(Yr||{}),xe=Yr;var Qr=(e=>(e.NO_AVAILABLE_TRACKS="no-available-tracks",e.UNKNOWN_ERROR="unknown-error",e))(Qr||{}),Xr=Qr;function Zr(n){switch(n){case 1:return"no-available-tracks";default:return"unknown-error"}}var ea=(e=>(e.CREATOR="CREATOR",e.ADMIN="ADMIN",e))(ea||{}),qe=ea;function jt(n,r){if(n.length!==r.length)return!1;for(let e of n)if(!r.includes(e))return!1;return!0}var ta=(e=>(e.USER="USER",e.GROUP="GROUP",e))(ta||{}),z=ta;var di=class{constructor(){this._items=[]}get length(){return this._items.length}push(r){this._items.push(r)}shift(){return this._items.shift()||null}bisect(){let r=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(r)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(r,e)=>e instanceof Error?String(e):e):""}};var ia=2*1024*1024,un=512*1024,Ht=100*1024,mn=5,Ki="_okcls_logs_session_",hn=3e4,$i=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=ia;try{let r=window.localStorage;for(let e of Object.keys(r)){if(e.indexOf(Ki)!==0)continue;let t=r.getItem(e);if(!t){ra(e);continue}let i=na(t);this.add(e,i)}}catch(r){console.error("Storage is blocked",r),this._storageSize=0}this._items.sort((r,e)=>r.date-e.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(r){this._storageSize=r}add(r,e){let t=parseInt(r.replace(Ki,""),10);this._itemsSize+=e,this._items.push({key:r,size:e,date:t})}deleteOldestItem(){let r=this._items.shift();r&&(ra(r.key),this._itemsSize-=r.size)}cleanup(r){for(;this.length&&(this.size>ia||this.length>mn-1||this.size+r>this.available);)this.deleteOldestItem()}};function aa(){return`${Ki}${Date.now()}`}function na(n){return new Blob([n]).size}function ra(n){try{window.localStorage.removeItem(n)}catch(r){console.error("Failed to remove log from storage",r)}}function qi(){let n=lt.toString();if(!Re.available||!n)return;let r=na(n);Re.cleanup(r);try{window.localStorage.setItem(li,n)}catch(e){if(console.warn("Failed to write log to storage",e),Re.storageSize=Re.size+r,Re.cleanup(Ht+r),Re.available>=Ht+r){qi();return}if(r>Ht){lt.bisect(),qi();return}Re.storageSize=0;return}r>un&&(Re.add(li,r),li=aa(),lt.clear(),Re.cleanup(Ht))}function Ji(){!Re.available||!lt.length||qi()}function _n(n=!1){let r=[];try{let i=window.localStorage;for(let s of Re.items){let o=i.getItem(s.key);r.push(o)}let a=lt.toString();a&&r.push(a)}catch(i){console.error("Storage is blocked",i)}let e=`[${r.join(",")}]`;if(n)return e;let t=`logs_${Date.now()}.json`;return gn(e,t),t}function gn(n,r){let e=document.createElement("a"),t=new Blob([n],{type:"text/json"});e.href=URL.createObjectURL(t),e.download=r,e.click()}function sa(n,r){if(!Re.available)return;let e=new Date;lt.push({t:e.getTime(),l:n,d:r,h:e.toLocaleString("ru-RU",{dateStyle:"short",timeStyle:"long"})}),Wi||(Wi=window.setTimeout(()=>{Wi=null,Ji()},hn))}function zi(){Re||(Re=new $i,lt=new di,li=aa(),window.addEventListener("beforeunload",Ji))}var Re,lt,li,Wi=null;window.__VKCallsSDKLogs__=(n=!1)=>(Re||zi(),Ji(),_n(n));var Yi=ni(require("@vkontakte/libvpx"));var S=class extends ct{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 a={};typeof t!="undefined"&&(a.param=t),this._logInternal(e,a,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let a={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(a),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){S._instance||(S._instance=new S(e,t))}static log(e,t,i=!1){S._instance&&S._instance.log(e,t,i)}static logCustom(e,t,i=!1){S._instance&&S._instance.logCustom(e,t,i)}static destroy(){S._instance&&S._instance.destroy(),S._instance=null}};var Le=class{constructor(){this._worker=null}_createWorker(s,o){return c(this,arguments,function*(r,e,t=[],i={},a=[]){return new Promise((p,u)=>{let h=t.join(","),I=new Blob([r,`exports.default(${h});`],{type:"application/javascript; charset=utf-8"}),b=window.URL.createObjectURL(I);this._worker=new Worker(b),this._worker.onmessage=D=>{switch(D.data.type){case"ready":p();break;case"error":u(D.data.error);break;case"frame":e(D.data);break;case"debug":d.debug(D.data.message);break;case"log_error":S.log(T.ERROR,D.data.message);break}},this._sendToWorker("init",i,a)})})}_removeWorker(){var r;(r=this._worker)==null||r.terminate(),this._worker=null}_sendToWorker(r,e={},t=[]){var i;(i=this._worker)==null||i.postMessage(Object.assign({type:r},e),t)}static isBrowserSupported(){throw new Error("Not implemented")}};var pt=class extends Le{init(r){return c(this,null,function*(){d.debug("LibVPxDecoder started"),yield this._createWorker('"use strict";var exports=(()=>{var u=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var h=(a,t)=>{for(var e in t)u(a,e,{get:t[e],enumerable:!0})},D=(a,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of x(t))!M.call(a,s)&&s!==e&&u(a,s,{get:()=>t[s],enumerable:!(o=R(t,s))||o.enumerable});return a};var V=a=>D(u({},"__esModule",{value:!0}),a);var F={};h(F,{default:()=>A});var A=(a,t)=>{let e=null,o=null,s=!0;function m(){return a({locateFile:t}).then(r=>o=r)}function b(r,g,l,y,E){if(!o){self.postMessage({type:"log_error",message:"decoder-init-fail-libvpx"}),self.postMessage({type:"frame",error:"Fatal initialization error"});return}if(s!==l&&(s=l,e&&(e=null,self.postMessage({type:"debug",message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:"debug",message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new o.VpxDecoder,e.debug(E),!e.init(l?o.VpxType.VP9:o.VpxType.VP8))){e=null,self.postMessage({type:"frame",error:"Decoder failed to create"});return}try{e.allocateBuffer(g.byteLength).set(new Uint8Array(g))}catch(n){self.postMessage({type:"debug",message:n}),e=null,self.postMessage({type:"frame",error:String(n)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:"frame",error:"Decode failed"});return}let p=e.getImageBuffer();if(!p){self.postMessage({type:"frame",error:"No decoded data"});return}let d=e.getImageWidth(),c=e.getImageHeight();e.nextImage()&&(self.postMessage({type:"debug",message:"LibVPxDecoder dropped frame"}),self.postMessage({type:"log_error",message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(p.byteLength);if(i.set(p),y){let n=new ImageData(i,d,c);createImageBitmap(n,0,0,d,c).then(f=>{self.postMessage({type:"frame",data:f},[f]),f.close()})}else self.postMessage({type:"frame",data:i.buffer,width:d,height:c},[i.buffer])}m().then(()=>{self.onmessage=r=>{switch(r.data.type){case"frame":b(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:"ready"})}).catch(r=>{self.postMessage({type:"error",error:String(r)})})};return V(F);})();\n',e=>{if(e.error)d.warn("LibVPxDecoder",e.error);else if(e.data instanceof ArrayBuffer){let t=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);r(t)}else r(e.data)},[Yi.default,Yi.default.getUrl])})}decodeFrame(r,e,t,i){let a="ImageBitmap"in window;this._sendToWorker("frame",{timestamp:r,data:e.buffer,isVP9:t,keyFrame:i,useImageBitmap:a,debug:d.enabled()},[e.buffer])}destroy(){this._removeWorker(),d.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var oa=typeof Object.fromEntries=="function"?Object.fromEntries:function(n){if(!n||!n[Symbol.iterator])throw new Error("Object.fromEntries() requires a single iterable argument");let r={};for(let[e,t]of n)r[e]=t;return r};function ca(n){return c(this,null,function*(){return new Promise((r,e)=>{let t=new FileReader;t.onload=i=>{r(i.target.result)},t.onerror=e,t.readAsArrayBuffer(n)})})}var It=":",ui="d",Sn=533,Qi="a=fmtp:",vn="sps-pps-idr-in-keyframe=1",Xi;(ji=>{function n(v,R,M,O,_,k=!1,G=!1){let J=/[\r\n]+/,le=`\r
8
+ `;if(!R&&!M&&!O&&!G&&!k&&!_)return v;function he(q){let _e=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],Ee="a=rtcp-fb:111",ie=q.findIndex(Z=>Z.startsWith(Ee));return~ie&&(q[ie]=q[ie]+le+_e.join(le)),q}function Ue(q,_e,Ee){let ie=q.split(" "),Z=ie.slice(0,3),oe;for(oe=3;oe<ie.length;oe++)Ee.includes(ie[oe])&&Z.push(ie[oe]);for(oe=3;oe<ie.length;oe++)!Ee.includes(ie[oe])&&!_e.includes(ie[oe])&&Z.push(ie[oe]);return Z.join(" ")}function ke(q,_e){let Ee=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),ie,Z=[];for(ie=0;ie<q.length;++ie){let oe=q[ie].match(Ee);oe&&oe.length===3&&oe[2]===_e&&Z.push(oe[1])}return Z}function Oe(q,_e,Ee,ie){let Z,oe="m="+_e;for(Z=0;Z<q.length;++Z)if(q[Z].startsWith(oe)){q[Z]=Ue(q[Z],Ee,ie);break}}function we(q,_e){let Ee=new RegExp(Qi+"(\\d+)");for(let ie=0;ie<q.length;++ie){let Z=q[ie].match(Ee);if(Z&&Z.length===2&&_e.includes(Z[1])){let oe=q[ie].trim()===Qi+Z[1]?" ":";";q[ie]+=oe+vn}}}function Be(q){let _e=ke(q,"H264");if(M){let Ee=_e.slice(0),ie=new RegExp(Qi+"(\\d+) apt=(\\d+)"),Z;for(Z=0;Z<q.length;++Z){let We=q[Z].match(ie);We&&We.length===3&&Ee.includes(We[2])&&Ee.push(We[1])}let oe=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(Z=q.length;Z--;){let We=q[Z].match(oe);We&&We.length===3&&Ee.includes(We[2])&&q.splice(Z,1)}Oe(q,"video",Ee,[])}else R&&Oe(q,"video",[],_e),_&&we(q,_e)}function N(q){let _e=ke(q,"VP9");O&&Oe(q,"video",[],_e)}function Bt(q){let _e=ke(q,"red");_e.length>0&&Oe(q,"audio",[],_e)}let B=v.split(J);return(M||R||_)&&Be(B),O&&N(B),G&&Bt(B),k&&he(B),B.join(le)}ji.patchLocalSDP=n;function r(v){return C.browserName()==="Firefox"&&Number(C.browserVersion())<60&&(v=v.replace("m=application 9 UDP/DTLS/SCTP webrtc-datachannel","m=application 9 DTLS/SCTP 5000").replace("a=sctp-port:5000","a=sctpmap:5000 webrtc-datachannel 256")),v}ji.patchRemoteSDP=r;function e(v){return v?`${v.type||"WEB_SOCKET"}_${v.id}`:"_"}ji.getPeerIdString=e;function t(v,R){return v&&v.id===R.id&&(v.type||"WEB_SOCKET")===(R.type||"WEB_SOCKET")}ji.comparePeerId=t;function i(v){return c(this,null,function*(){return!v||!v.getStats?Promise.resolve(null):v.getStats(null).then(R=>{let M=null,O=null;if(R.forEach(_=>{_.type==="transport"&&_.selectedCandidatePairId?O=R.get(_.selectedCandidatePairId):_.type==="candidate-pair"&&_.state==="succeeded"&&!O&&(!_.hasOwnProperty("selected")||_.selected)&&(O=_)}),O&&O.localCandidateId){let _=R.get(O.localCandidateId);_&&(M={type:_.candidateType,ip:_.ip||_.ipAddress,port:_.port||_.portNumber})}return M}).catch(()=>null)})}ji.getPeerConnectionHostInfo=i;let a=/^[0-9]+$/,s=/^([gu])([0-9]+)$/;function o(v,R){let M=String(v);return s.test(M)?(d.warn(`Already composite id [${v}] type supplied [${R}]`),M):R===z.GROUP?"g"+M:R===z.USER?"u"+M:(d.warn(`Unknown type [${R}] for id [${v}]`),M.match(a)?"u"+M:M)}ji.composeUserId=o;function p(v,R,M){let O=o(v,R);return u(O,M)}ji.composeParticipantId=p;function u(v,R){return R?v+It+ui+R:v}ji.compose=u;function h(v){return p(v.id,v.idType||z.USER,v.deviceIdx||0)}ji.composeId=h;function I(v){return v.participant?h(v.participant):p(v.participantId,v.participantType||z.USER,v.deviceIdx||0)}ji.composeMessageId=I;function b(v){let R=String(v),M=R.match(s);return M?{id:Number(M[2]),type:M[1]==="g"?z.GROUP:z.USER}:(d.warn(`Unsupported compositeId [${v}]`),{id:Number(R),type:z.USER})}ji.decomposeId=b;function D(v){let R=v.split(It+ui);return{compositeUserId:R[0],deviceIdx:R.length>1?parseInt(R[1],10):0}}ji.decomposeParticipantId=D;function A(){var G,J;let v=(J=(G=window.crypto)==null?void 0:G.randomUUID)==null?void 0:J.call(G);if(v)return v;let R="0123456789abcdefghijklmnopqrstuvwxyz".split(""),M=new Array(36),O=0,_,k;for(k=0;k<36;k++)k===8||k===13||k===18||k===23?M[k]="-":k===14?M[k]="4":(O<=2&&(O=33554432+Math.random()*16777216|0),_=O&15,O=O>>4,M[k]=R[k===19?_&3|8:_]);return M.join("")}ji.uuid=A;function Y(v,R){let M;function O(){let _=this,k=arguments;M&&window.clearTimeout(M),M=window.setTimeout(()=>{v.apply(_,k)},R)}return O}ji.throttle=Y;function H(v){if(!window.BigInt)return null;let R="",M=v.split(`
9
+ `);for(let k of M)if(k.startsWith("a=fingerprint")){let G=k.split(" ");if(G.length===2){R=G[1];break}}if(!R)return BigInt(-1);let O=R.split(":"),_=BigInt(0);for(let k=Math.min(7,O.length-1);k>=0;k--){let G=BigInt(parseInt(O[k],16));_<<=BigInt(8),_|=G}return BigInt.asIntN(64,_)}ji.sdpFingerprint=H;function fe(v){return c(this,null,function*(){return new Promise(R=>window.setTimeout(R,v))})}ji.delay=fe;function W(v,R,M){let O=[];return v.getSenders().forEach(_=>te(R,_,_.track,M,O)),O}ji.applySettings=W;function te(v,R,M,O,_){var k;if(v&&M&&M.kind==="video"){let G=M.getSettings();if(G){let J=v.maxBitrateK?v.maxBitrateK*1024:null,le=G.width,he=G.height,Ue=le&&he&&v.maxDimension?Math.max(1,Math.max(le,he)/v.maxDimension):null,ke=v.maxFramerate?v.maxFramerate:null;if(le&&he&&v.maxDimension&&v.maxDimension>Math.max(le,he)){let N=Math.round(le*he/256),Bt=(Math.round(N*Sn/1e4)+1)*1e4;J=J===null?Bt:Math.min(Bt,J)}let Oe=v.degradationPreference?v.degradationPreference:"balanced",we=O[M.id];if(we&&we.bitrate===J&&we.scaleResolutionDownBy===Ue&&we.maxFramerate===ke&&we.degradationPreference===Oe){_[M.id]=we;return}_[M.id]={bitrate:J,scaleResolutionDownBy:Ue,maxFramerate:ke,degradationPreference:Oe};let Be=R.getParameters();Be.encodings||(Be.encodings=[{}]),Be.encodings.forEach(N=>{J?N.maxBitrate=J:delete N.maxBitrate,Ue?N.scaleResolutionDownBy=Ue:delete N.scaleResolutionDownBy,ke?N.maxFramerate=ke:delete N.maxFramerate}),Be.degradationPreference=Oe,(k=R.setParameters)==null||k.call(R,Be)}}}ji.applyVideoTrackSettings=te;function me(v,R){Array.isArray(R)||(R=[R]);for(let M of R)if(v.includes(M))return!0;return!1}ji.includesOneOf=me;function ve(v){var R;return Object.entries(((R=v.participantState)==null?void 0:R.state)||{}).reduce((M,[O,_])=>(v.participantState&&(M[O]={ts:v.participantState.stateUpdateTs[O],state:_}),M),{})}ji.mapParticipantState=ve;function st(v){let R=v.map(M=>({uid:M.externalId,mediaSettings:M.mediaSettings,status:M.status,muteStates:M.muteStates,unmuteOptions:M.unmuteOptions,participantState:M.participantState,markers:M.markers,movieShareInfos:M.movieShareInfos}));return l.filterObservers?R.filter(M=>!M.uid.observer):R}ji.mapSharedParticipants=st;function ai(v,R){let M=Object.keys(v),O=Object.keys(R);if(M.length!==O.length)return!1;for(let _ of M)if(!O.hasOwnProperty(_)||v[_].state!==R[_].state||v[_].ts!==R[_].ts)return!1;return!0}ji.isEqualParticipantState=ai;function X(v,R){let M=Object.keys(v),O=Object.keys(R);if(M.length!==O.length)return!1;for(let _ of M)if(!R.hasOwnProperty(_)||v[_]!==R[_])return!1;return!0}ji.isObjectsEquals=X;function Cr(v,R){if(v.length!==R.length)return!1;for(let M of v)if(R.indexOf(M)<0)return!1;return!0}ji.isArraysEquals=Cr;function Pr(v){return!Object.keys(v).length}ji.isEmptyObject=Pr;function yr(v,R){if(!v&&!R)return 0;if(!v||!R)return v?-1:1;return O(R.rank,v.rank)||O(v.ts,R.ts)||M(v,R);function M(_,k){let G={[z.USER]:0,[z.GROUP]:1},{compositeUserId:J,deviceIdx:le}=D(_.id),{compositeUserId:he,deviceIdx:Ue}=D(k.id),{id:ke,type:Oe}=b(J),{id:we,type:Be}=b(he);return O(G[Oe],G[Be])||O(ke,we)||O(le,Ue)}function O(_,k){return _<k?-1:_===k?0:1}}ji.participantMarkerCompare=yr;function Q(v,R){let M=Object.entries(v).filter(([,O])=>Array.isArray(R)?!R.includes(O):O!==R);return oa(M)}ji.objectFilterOutValues=Q;function Vi(v,R,M){let O=M;for(let _ in v)v.hasOwnProperty(_)&&(O=R(O,v[_],_));return O}ji.objectReduce=Vi,ji.setImmediate=(()=>{let v=1,R={},M=null;return typeof MessageChannel!="undefined"&&(M=new MessageChannel,M.port1.onmessage=O=>{let _=O.data;R[_]&&(R[_](),delete R[_])}),function(O){if(M&&document.visibilityState==="hidden"){let k=v;return v=v>=Number.MAX_SAFE_INTEGER?1:v+1,R[k]=O,M.port2.postMessage(k),()=>{R[k]&&delete R[k]}}let _=setTimeout(O,0);return()=>clearTimeout(_)}})()})(Xi||(Xi={}));var E=Xi;function da(n,r){if(n.isAudioEnabled!==r.isAudioEnabled||n.isVideoEnabled!==r.isVideoEnabled||n.isScreenSharingEnabled!==r.isScreenSharingEnabled||n.isFastScreenSharingEnabled!==r.isFastScreenSharingEnabled||n.isAudioSharingEnabled!==r.isAudioSharingEnabled||n.isAnimojiEnabled!==r.isAnimojiEnabled||n.videoStreams.length!==r.videoStreams.length)return!1;for(let e of n.videoStreams)if(!r.videoStreams.find(t=>t.id===e.id&&t.source===e.source))return!1;return!0}function ge(n){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,isFastScreenSharingEnabled:!1,isAudioSharingEnabled:!1,isAnimojiEnabled:!1,videoStreams:[]},n||{})}var la=n=>n.stop(),pa=n=>n.getTracks().forEach(la),Zi=n=>n.getVideoTracks().forEach(la),ua=n=>n.getVideoTracks()[0].clone();function Tt(n,{width:r,height:e}){return n.applyConstraints({width:{max:r,ideal:r},height:{max:e,ideal:e}})}var V=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(w).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,V)}};var Ne=(i=>(i.audio="audio",i.video="video",i.screen="screen",i.audioshare="audioshare",i))(Ne||{}),mi=class extends re{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._audioShareTrack=null;this._sendVideoTrack=null;this._mediaSettings=ge();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._sourceBusy=!1;this._animojiEnabled=!1;this._initDeviceChangeListener(),l.audioShare&&(this._audioShareTrack=this.getSilentAudioShareTrack())}request(){return c(this,arguments,function*(e=[ce.AUDIO],t=!0){if(this._stream)return;let i=e.includes(ce.VIDEO),a=e.includes(ce.AUDIO),s=e.includes(ce.ANIMOJI);if(!C.isBrowserSupported())throw new V(ae.UNSUPPORTED);try{this._stream=yield C.getUserMedia(i,a,t),this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(o=>o.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=a&&this._stream.getAudioTracks().filter(o=>o.enabled).length>0||!1,this._mediaSettings.isAnimojiEnabled=s&&!this._mediaSettings.isVideoEnabled||!1,this._animojiEnabled=s}catch(o){throw new V(o)}})}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}get isAnimojiRequested(){return this._animojiEnabled&&!this._mediaSettings.isVideoEnabled}addTrackToPeerConnection(e,t,i,a){let s=this.getStream(),o=this._getSendAudioTrack(),p=this.getSendVideoTrack(i);if(!s||!o&&!p&&!t)throw new Error("No local stream found");if(o&&!t){if(a){let{codecs:u}=RTCRtpSender.getCapabilities("audio"),h="audio/red",I=48e3,b=u.findIndex(D=>D.mimeType===h&&D.clockRate===I);if(b>=0){let D=[];D.push(u[b]);for(let A=0;A<u.length;A++)A!==b&&D.push(u[A]);e.getTransceivers().forEach(A=>A.setCodecPreferences(D))}}e.addTrack(o,s)}p&&!t&&e.addTrack(p,s)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return c(this,null,function*(){switch(e){case"videoinput":if(this._mediaSettings.isVideoEnabled)return this._stopAndRemoveTrackVideoStreamBackup(),this._changeVideoInput();break;case"audioinput":if(this._mediaSettings.isAudioEnabled)return this._changeAudioInput();break;default:return Promise.reject(ae.UNKNOWN)}})}stopVideoTrack(){return c(this,null,function*(){var t,i;if(!this._mediaSettings.isVideoEnabled)return;let e=(i=(t=this._stream)==null?void 0:t.getVideoTracks())==null?void 0:i[0];if(e&&l.videoEffects)try{yield l.videoEffects.setEffect(null,e)}catch(a){}this._stopAndRemoveTrackVideoStreamBackup(),this._stopLocalTrack("video")})}setVideoStream(e,t){return c(this,null,function*(){return t?this._changeScreen(!1,!1,e):(this._stopAndRemoveTrackVideoStreamBackup(),this._changeVideoInput(e))})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=E.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);this._onDeviceChange=()=>c(this,null,function*(){if(!this._stream)return;let a=C.getSavedMicrophone(),s=C.getSavedCamera(),o=a==null?void 0:a.deviceId,p=s==null?void 0:s.deviceId;if(!o&&!p)return;let u=yield navigator.mediaDevices.enumerateDevices();!e&&o&&(e=!u.find(h=>h.deviceId===o)),!t&&p&&(t=!u.find(h=>h.deviceId===p)),i()}),navigator.mediaDevices.addEventListener("devicechange",this._onDeviceChange)}_destroyDeviceChangeListener(){this._onDeviceChange&&navigator.mediaDevices.removeEventListener("devicechange",this._onDeviceChange)}_changeVideoInput(e=null,t){return c(this,null,function*(){this._busy();try{let i=e?"stream":"video",a=e||(yield C._getUserVideo(!!this._effect));if(!this._stream)a.getTracks().forEach(s=>s.stop());else{l.consumerScreenTrack||(yield this._disableScreenCapture());let s=this._getVideoEffectTrack(a),o=yield this._videoEffect(this._effect,s);t&&(yield Tt(o,t)),this._stopLocalTrack("video"),S.log(T.DEVICE_CHANGED,i),d.log("Video stream changed"),yield this._replaceLocalTrack(o),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(i){throw S.log(T.ERROR,"change_video"),d.warn("Camera change failed",i),i}finally{this._free()}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=ua(e)),t=this._trackVideoStreamBackup.clone(),Zi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),Zi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return c(this,null,function*(){return this._changeAudioInput(e)})}_busy(){if(this._sourceBusy)throw S.log(T.ERROR,"change_device"),d.warn("Device change failed: MediaSource is busy"),new Error("MediaSource is busy");this._sourceBusy=!0}_free(){this._sourceBusy=!1}_changeAudioInput(e=null){return c(this,null,function*(){this._busy();try{if(e=e||(yield C.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),S.log(T.DEVICE_CHANGED,"audio"),d.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw S.log(T.ERROR,"change_audio"),d.error("Microphone change failed",t),t}finally{this._free()}})}_changeScreen(e,t,i){return c(this,null,function*(){this._busy();try{if(i=i||(yield C.getScreenMedia(e,t)),i.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.disableScreenCapturing()},!1),!this._stream)i.getTracks().forEach(a=>a.stop());else{let a=i.getVideoTracks()[0],s=l.consumerScreenTrack?a:yield this._videoEffect(null,a);if(S.log(T.DEVICE_CHANGED,"screen"),d.log("Screen capturing started"),this._screenTrack=s,this._mediaSettings.isScreenSharingEnabled=!0,this._mediaSettings.isFastScreenSharingEnabled=e,l.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=l.consumerScreenDataChannel?C.getBlackMediaTrack(l.videoMinWidth,l.videoMinHeight):s,yield this._replaceLocalTrack(s,this._sendVideoTrack)),i.getAudioTracks().length>0){let o=i.getAudioTracks()[0];o.contentHint="music",this._audioShareTrack=o,this._stopLocalTrack("audioshare"),yield this._replaceLocalTrack(o),this._mediaSettings.isAudioSharingEnabled=!0}t&&!this._mediaSettings.isAudioSharingEnabled&&d.debug("Audio share requested but not captured"),this._triggerEvent("SCREEN_STATUS",{track:s,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(a){throw S.log(T.ERROR,"screen"),d.warn("Screen capturing failed",a),a}finally{this._free()}})}_disableScreenCapture(){return c(this,null,function*(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),yield this.stopAudioShareTrack(),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._mediaSettings.isFastScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))})}disableAudioShare(){return c(this,null,function*(){yield this.stopAudioShareTrack(),this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"audioshare",mediaSettings:this._mediaSettings})})}stopAudioShareTrack(){return c(this,null,function*(){if(this._audioShareTrack){this._audioShareTrack.stop();let e=this.getSilentAudioShareTrack();this._stopLocalTrack("audioshare"),yield this._replaceLocalTrack(e),this._mediaSettings.isAudioSharingEnabled=!1}})}getSilentAudioShareTrack(){let e=C.getSilentMediaTrack();return e.contentHint="music",e.stop(),e}_replaceLocalTrack(e,t){return c(this,null,function*(){if(!this._stream)return;let i=!1;this._stream.getTracks().forEach(a=>{var s,o;a.kind===e.kind&&a.contentHint===e.contentHint&&((s=this._stream)==null||s.removeTrack(a),(o=this._stream)==null||o.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t),i=!0)}),i||(this._stream.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})}_stopLocalTrack(e){var t;if(this._stream){if(e==="audioshare")return(t=this._stream.getTracks().find(i=>i.contentHint==="music"))==null?void 0:t.stop();this._stream.getTracks().forEach(i=>{i.kind===e&&i.contentHint!=="music"&&i.stop()})}}_videoEffect(e,t){return c(this,null,function*(){if(!l.videoEffects)return t;try{return S.log(T.DEVICE_CHANGED,`effect_${(e==null?void 0:e.effect)||"none"}`),l.videoEffects.setEffect(e,t)}catch(i){return d.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){this._destroyDeviceChangeListener(),l.videoEffects&&(this._effect=null,l.videoEffects.destroy()),this._stream&&(pa(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return c(this,null,function*(){if(e.captureScreen){yield this._changeScreen(e.fastScreenSharing,e.captureAudio);return}return l.consumerScreenTrack?this._disableScreenCapture():(e.captureAudio||(yield this.disableAudioShare()),this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1))})}disableScreenCapturing(){return c(this,null,function*(){return this.toggleScreenCapturing({captureScreen:!1,fastScreenSharing:!1,captureAudio:!1})})}toggleVideo(e){return c(this,null,function*(){if(!this._stream)return;l.consumerScreenTrack||(yield this._disableScreenCapture());let t;if(e){let i=yield C._getUserVideo(!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=C.getBlackMediaTrack(l.videoMinWidth,l.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();if(this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._animojiEnabled){this._triggerEvent("ANIMOJI_STATUS",!e);return}this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return c(this,null,function*(){if(!this._stream)return;let t;e?t=(yield C.getUserAudio()).getAudioTracks()[0]:t=C.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}toggleAnimojiCapturing(e){this._animojiEnabled=e,this._mediaSettings.isVideoEnabled||this._triggerEvent("ANIMOJI_STATUS",e)}onAnimojiSender(e){this._mediaSettings.isAnimojiEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}_setEffectResolution(e){return c(this,null,function*(){var a;if(!l.videoEffects)return;let t=this._trackVideoStreamBackup||((a=this._stream)==null?void 0:a.getVideoTracks()[0]);yield l.videoEffects.setEffect(null,t),yield Tt(t,e);let i=yield l.videoEffects.setEffect(this._effect,t.clone());yield this._replaceLocalTrack(i)})}setResolution(i){return c(this,arguments,function*({video:e,effect:t}){if(!l.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let a=this._stream.getVideoTracks()[0];if(!a)throw new Error("Local video track not found");if(a.enabled){if(!this._effect)return Tt(a,e);if(t)return this._setEffectResolution(t)}})}updateNoiseSuppression(){return c(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks().find(t=>!t.contentHint);if(!e)throw new Error("Local audio track not found");if(e.enabled)return e.applyConstraints({noiseSuppression:l.noiseSuppression})})}videoEffect(e){return c(this,null,function*(){if(!l.videoEffects)throw new Error("Video Effects library is not set");if(!l.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,e?this._changeVideoInput(this._stream,{width:l.videoEffectMaxWidth,height:l.videoEffectMaxHeight}):this._changeVideoInput(this._stream)})}getAudioShareTrack(){return this._audioShareTrack}};var tr="_okcls_",Rt=(()=>{try{let n=Date.now().toString(),r=window.localStorage,e=!1;return r.setItem(n,n),e=r.getItem(n)===n,r.removeItem(n),e?r:null}catch(n){return null}})();function En(n){let r=Rt?Rt.getItem(tr+n):null;if(r===null)return null;try{return JSON.parse(r)}catch(e){return null}}function In(n,r){try{Rt&&Rt.setItem(tr+n,JSON.stringify(r))}catch(e){}}function Tn(n){Rt&&Rt.removeItem(tr+n)}var er;(t=>{function n(i){return En(i)||null}t.get=n;function r(i,a){In(i,a)}t.set=r;function e(i){Tn(i)}t.remove=e})(er||(er={}));var Qe=er;var Pt=null,ir=null,vi=[],Ei=[],Si=[],Xe=null,Ze=null,sr=null,ma=null,or=!1,Ii=!1,hi,Ct,_i,rr=null,ar="",gi=[],nr=null,ha=navigator.appVersion,Rn=navigator.appName,Pe=navigator.userAgent,Je=(e=>(e.USER="user",e.ENVIRONMENT="environment",e))(Je||{});(r=>{function n(e){return Object.values(r).includes(e)}r.contains=n})(Je||(Je={}));var ut=class{constructor(r,e=!1,t=l.videoMaxWidth,i=l.videoMaxHeight){let a=!1;if(r){a={noiseSuppression:l.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let o;Ze&&(o=Ze.deviceId),typeof r=="string"&&(o=r),o&&(a.deviceId={exact:o})}let s=!1;if(e){s={width:{min:l.videoMinWidth,max:t,ideal:t},height:{min:l.videoMinHeight,max:i,ideal:i},aspectRatio:{ideal:l.videoAspectRatio},frameRate:{ideal:l.videoFrameRate}};let o;Xe&&(o=Xe.deviceId),typeof e=="string"&&(o=e),o&&(s.deviceId={exact:o}),l.videoFacingMode&&(s.facingMode={ideal:l.videoFacingMode},delete s.deviceId)}this.audio=a,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let r=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||r)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},cr=class extends ut{constructor(e,t,i,a){super(!1,!0);this.captureController="CaptureController"in window?new CaptureController:null,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=i,this.video.displaySurface=l.displaySurface,je.browserName()==="Safari"&&Number(je.browserVersion())===16&&(delete this.video.width,delete this.video.height),a&&(this.audio={noiseSuppression:!1,echoCancellation:!1,autoGainControl:!1})}getNative(){return Object.assign(super.getNative(),{systemAudio:"exclude",controller:this.captureController})}};function _a(){return c(this,null,function*(){Ii=!1,Pt=null,yield dr(),g.onDeviceChange()})}function dr(){return c(this,null,function*(){return Pt||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!ir&&navigator.mediaDevices.addEventListener&&(ir=E.throttle(_a,1e3),navigator.mediaDevices.addEventListener("devicechange",ir)),Pt=navigator.mediaDevices.enumerateDevices().then(n=>{vi=n.filter(i=>i.kind==="videoinput"?(i.label&&(or=!0),!0):!1),Ei=n.filter(i=>i.kind==="audioinput"?(i.label?Ii=!0:je.isMobile()&&je.browserName()==="Firefox"&&(Ii=or),!0):!1),Si=n.filter(i=>i.kind==="audiooutput");let r=Qe.get("videoinput"),e=Qe.get("audioinput"),t=Qe.get("audiooutput");return Xe=vi.find(i=>i.deviceId===r)||null,Ze=Ei.find(i=>i.deviceId===e)||null,sr=Si.find(i=>i.deviceId===t)||Si[0]||null,Pt=Promise.resolve(n),n}).catch(()=>(Pt=null,[]))))})}function Cn(n){if(Xe&&Ze)return;let r=(e,t)=>{var a;let i=(a=t.getSettings())==null?void 0:a.deviceId;return e.find(s=>s.deviceId===i||s.label===t.label)||null};n==null||n.getTracks().forEach(e=>{var t;if(!Ze&&e.kind==="audio")Ze=r(je.getMicrophones(),e);else if(e.kind==="video"){Xe||(Xe=r(je.getCameras(),e));let i=(t=e.getSettings())==null?void 0:t.facingMode;Je.contains(i)&&(ma=i)}})}function Gt(n,r){return c(this,null,function*(){d.debug("Try to get media",JSON.parse(JSON.stringify(n.getNative())));let e=je.hasPermissions(n.isVideo());!e&&!r&&g.onPermissionsRequested();try{let t=yield navigator.mediaDevices.getUserMedia(n.getNative());return e||(yield _a()),Cn(t),t}catch(t){switch(d.error("getUserMedia error",t),t.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":r=n.isVideo()?ae.CAMERA_PERMISSION:ae.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":r=ae.UNKNOWN;break;case"AbortError":case"NotReadableError":r=n.isVideo()?ae.CAMERA_ACCESS:ae.MIC_ACCESS;break}if(n.canSimplify())return Gt(n.simplify(),r);let i=r||ae.UNKNOWN;throw g.onPermissionsError(i,t),i}})}function Pn(n){return c(this,null,function*(){var r;d.debug("Try to get screen",n.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(n.getNative()),t=e==null?void 0:e.getVideoTracks()[0];if(t&&(d.debug("Got display media track",t.id),t.contentHint="text",n.captureController)){let i=(r=t.getSettings())==null?void 0:r.displaySurface;(i==="browser"||i==="window")&&n.captureController.setFocusBehavior("no-focus-change")}return e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw ae.SCREEN_PERMISSION;default:throw ae.SCREEN_ACCESS}}})}function fi(){return gi.length||(gi=(()=>{let n,r=!1,e=0,t="0",i=Pe.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return n=/\brv[ :]+(\d+)/g.exec(Pe),["IE",n&&n[1]||"Unknown",r,e,t];if(i[1]==="Safari"){if(n=Pe.match(/\bEdge\/(\d+)/),n)return["Edge",n[1]||"Unknown",r,e,t];if(n=Pe.match(/\bCriOS\/(\d+)/),n)return["Chrome",n[1],!0,Number(n[1]),t];if(n=Pe.match(/\bFxiOS\/(\d+)/),n)return["Firefox",n[1],!1,e,t];if(n=Pe.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1],!1,e,t];if(n=Pe.match(/\bOPT\/(\d+)/),n)return["Opera",n[1],!1,e,t]}if(i[1]==="Chrome"){if(r=!0,e=Number(i[2]),n=Pe.match(/\bOPR\/(\d+)/),n)return["Opera",n[1]||"Unknown",r,e,t];if(n=Pe.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1]||"Unknown",r,e,t];if(n=Pe.match(/\bSferum\/((\d+)(?:\.\d+)*)/),n)return["Sferum",n[1]||"Unknown",r,e,t];if(n=Pe.match(/\bEdge?\/(\d+)/),n)return["Edge",n[1]||"Unknown",r,e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",r,e,t]}return n=Pe.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),n&&n[2]!==void 0&&(t=n[2]),[i[2]?i[1]:Rn,n&&n[1]||i[2]||ha,r,e,t]})()),gi}var je;(O=>{function n(){return c(this,null,function*(){let _=()=>{me(),document.removeEventListener("click",_),document.removeEventListener("touchstart",_)};return document.addEventListener("click",_),document.addEventListener("touchstart",_),dr()})}O.init=n;function r(){return vi}O.getCameras=r;function e(){return Ei}O.getMicrophones=e;function t(){return Si}O.getOutput=t;function i(){return vi.length>0}O.hasCamera=i;function a(){return Ei.length>0}O.hasMicrophone=a;function s(){return Xe}O.getSavedCamera=s;function o(){return Ze}O.getSavedMicrophone=o;function p(){return sr}O.getSavedOutput=p;function u(){return ma||l.videoFacingMode||null}O.getVideoFacingMode=u;function h(){return or}O.hasCameraPermission=h;function I(){return Ii}O.hasMicrophonePermission=I;function b(_=!1){return I()?i()&&_?h():!0:!1}O.hasPermissions=b;function D(_=!1,k=!0,G=!0){return c(this,null,function*(){let J=a()&&k,le=i()&&_,he;if(!J&&!le)he=new MediaStream;else try{he=yield Gt(new ut(J,le))}catch(Ue){he=new MediaStream}return!he.getVideoTracks().length&&G&&he.addTrack(ve()),!he.getAudioTracks().length&&G&&he.addTrack(me()),he})}O.getUserMedia=D;function A(_,k){return c(this,null,function*(){let G=_?l.fastScreenShareWidth:window.screen.width,J=_?l.fastScreenShareHeight:window.screen.height,le=l.getScreenFrameRate(_);return Pn(new cr(G,J,le,k))})}O.getScreenMedia=A;function Y(_=!1){return c(this,null,function*(){let k=_?l.videoEffectMaxWidth:l.videoMaxWidth,G=_?l.videoEffectMaxHeight:l.videoMaxHeight;return Gt(new ut(!1,!0,k,G))})}O._getUserVideo=Y;function H(_,k){return c(this,null,function*(){let G=(k==null?void 0:k.width)||l.videoMaxWidth,J=(k==null?void 0:k.height)||l.videoMaxHeight;return Gt(new ut(!1,_||!0,G,J))})}O.getUserVideo=H;function fe(_){return c(this,null,function*(){return Gt(new ut(_||!0,!1))})}O.getUserAudio=fe;function W(_,k){return c(this,null,function*(){let[G]=_.getVideoTracks();if(!G)throw new Error("Video track not found in stream");return Tt(G,k)})}O.setResolution=W;function te(_,k){return c(this,null,function*(){let J=(yield dr()).find(le=>le.kind===_&&le.deviceId===k);return J?(_==="videoinput"?Xe=J:_==="audioinput"?Ze=J:_==="audiooutput"&&(sr=J),Qe.set(_,k),J):null})}O.saveDeviceId=te;function me(){if(!_i||_i.readyState==="ended"){let _=v(),k=_.createMediaStreamDestination(),G=_.createGain();G.gain.value=1e-5,G.connect(k),G.connect(_.destination);let J=_.createOscillator();J.type="sine",J.frequency.value=0,J.connect(G),J.start(),_i=k.stream.getAudioTracks()[0]}return Object.assign(_i.clone(),{enabled:!1})}O.getSilentMediaTrack=me;function ve(_=l.videoMinWidth,k=l.videoMinHeight){Ct||(Ct=document.createElement("canvas")),Ct.width=_,Ct.height=k;let G=Ct.getContext("2d");return G.rect(0,0,_,k),G.fillStyle="black",G.fill(),(!hi||hi.readyState==="ended")&&(hi=Ct.captureStream(l.videoFrameRate).getVideoTracks()[0]),Object.assign(hi.clone(),{enabled:!1})}O.getBlackMediaTrack=ve;function st(){if(Vi()==="Edge"&&Number(Fi())<70)return!1;try{let _=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&_.RTCPeerConnection&&_.RTCIceCandidate&&_.RTCSessionDescription&&_.HTMLCanvasElement&&_.HTMLCanvasElement.prototype.captureStream&&_.RTCRtpSender&&_.RTCRtpSender.prototype.replaceTrack&&_.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(_){return!1}}O.isBrowserSupported=st;function ai(){return!!navigator.mediaDevices.getDisplayMedia}O.isScreenCapturingSupported=ai;function X(){let _=O.browserName()==="Safari"&&O.browserVersion()==="15"&&O.browserSubVersion()==="1",k=O.browserName()==="Opera"&&O.os()==="Windows";return _||k}O.isBrokenH264=X;function Cr(){return!(O.baseChromeVersion()&&O.isMobile())}O.canPreferH264=Cr;function Pr(){var _;return((_=window.RTCRtpTransceiver)==null?void 0:_.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}O.canPreferRed=Pr;function yr(){return ar||(ar=(()=>{let _={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let k in _)if(_.hasOwnProperty(k)&&_[k].test(Pe))return k;return"Unknown"})()),ar}O.os=yr;function Q(){return rr===null&&(rr=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(ha)),rr}O.isMobile=Q;function Vi(){return fi()[0]}O.browserName=Vi;function Fi(){return fi()[1]}O.browserVersion=Fi;function ji(){return fi()[3]}O.baseChromeVersion=ji;function v(){return nr||(nr=new(window.AudioContext||window.webkitAudioContext)),nr}O.getAudioContext=v;function R(){return fi()[4]}O.browserSubVersion=R;function M(){return O.baseChromeVersion()>=105&&!O.isMobile()}O.isAudioShareSupported=M})(je||(je={}));var C=je;var He=class extends Le{init(r){return c(this,null,function*(){d.debug("WebCodecsDecoder started"),yield this._createWorker('"use strict";var exports=(()=>{var s=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var E=(o,e)=>{for(var t in e)s(o,t,{get:e[t],enumerable:!0})},g=(o,e,t,c)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of m(e))!b.call(o,r)&&r!==t&&s(o,r,{get:()=>e[r],enumerable:!(c=f(e,r))||c.enumerable});return o};var D=o=>g(s({},"__esModule",{value:!0}),o);var V={};E(V,{default:()=>R});var R=o=>{let e=null,t=!0;function c(){self.postMessage({type:"ready"})}function r(d,l,a,i=!1){if(!e||t!==a){if(!i){self.postMessage({type:"debug",message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}t=a,e?self.postMessage({type:"debug",message:`WebCodecsDecoder codec changed to ${a?"VP9":"VP8"}`}):(self.postMessage({type:"debug",message:`WebCodecsDecoder codec ${a?"VP9":"VP8"}`}),e=new VideoDecoder({output:n=>{let u=o?[n]:[];self.postMessage({type:"frame",data:n},u),n.close()},error:n=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:"frame",error:"WebCodecsDecoder failed, reinitialize: "+String(n)})}})),e.configure({codec:a?"vp09.00.50.08":"vp8"})}let p=new EncodedVideoChunk({type:i?"key":"delta",timestamp:d,data:l});e.decode(p)}self.onmessage=d=>{switch(d.data.type){case"init":c();break;case"frame":r(d.data.timestamp,d.data.data,d.data.isVP9,d.data.keyFrame);break}}};return D(V);})();\n',e=>{e.error?d.warn("WebCodecsDecoder",e.error):r(e.data)},[C.baseChromeVersion()>=92])})}decodeFrame(r,e,t,i=!1){this._sendToWorker("frame",{timestamp:r,data:e.buffer,isVP9:t,keyFrame:i},[e.buffer])}destroy(){this._removeWorker(),d.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window}};var ga=require("bit-buffer");var yn=65536,et=class{constructor(r,e){this._chunks=[];this._participantId=r,this._onStream=e}appendChunk(r){let e=this._chunks.length;if(r.start)e&&(d.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!e||(this._chunks[e-1].sequence+1)%yn!==r.sequence){d.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(r),r.end){let t=this._processFrameData(),{width:i,height:a}=et.getFrameSize(t);this._processFrame({timestamp:r.timestamp,frameData:t,isVP9:r.isVP9,keyframe:r.keyframe,width:i,height:a})}}destroy(){this._chunks=[]}_processFrameData(){let r=this._chunks;this._chunks=[];let e=r.reduce((a,s)=>a+s.data.byteLength,0),t=new Uint8Array(e),i=0;for(let a of r)t.set(new Uint8Array(a.data),i),i+=a.data.byteLength;return t}static getFrameSize(r){let e={width:0,height:0},t=new ga.BitStream(r.buffer);t.bigEndian=!0,t.index+=2;let i=t.readBits(1),s=t.readBits(1)<<1|i;return s===3&&t.index++,t.readBits(1)===1||t.readBits(1)!==0||(t.index++,t.index++,t.index+=24,s>=2&&t.index++,t.readBits(3)!==7?(t.index++,(s===1||s===3)&&(t.index+=3)):(s===1||s===3)&&t.index++,e.width=t.readBits(16)+1,e.height=t.readBits(16)+1),e}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var mt=class{constructor(r){this._onStream=r}drawFrame(r){return c(this,null,function*(){throw new Error("Method `drawFrame` is not supported by this implementation")})}drawImage(r){throw new Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var yt=class extends mt{constructor(e){super(e);this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;d.debug("CanvasRenderer started"),this._useImageBitmap="ImageBitmap"in window}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}drawFrame(e){return c(this,null,function*(){let t="createImageBitmap"in e?yield e.createImageBitmap():yield createImageBitmap(e);this.drawImage(t),t.close()})}drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}destroy(){this._removeStream(),d.debug("CanvasRenderer destroyed")}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(C.browserName()==="Safari"&&Number(C.browserVersion())===15)&&!(C.browserName()==="Firefox"&&Number(C.browserVersion())<60)}};var ht=class extends mt{constructor(e){super(e);d.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:"video"}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}drawFrame(e){return c(this,null,function*(){yield this._writer.write(e)})}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),d.debug("TrackGeneratorRenderer destroyed")}static isBrowserSupported(){return"VideoFrame"in window&&"MediaStreamTrackGenerator"in window&&He.isBrowserSupported()}};var bt=class extends et{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];d.debug(`StreamBuilder started for participant [${e}]`),ht.isBrowserSupported()?this._renderer=new ht(t):this._renderer=new yt(t),He.isBrowserSupported()?this._decoder=new He:this._decoder=new pt;let i=a=>c(this,null,function*(){"VideoFrame"in window&&a instanceof VideoFrame?yield this._renderer.drawFrame(a):this._renderer.drawImage(a)});this._decoder.init(i).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._renderer.destroy(),d.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return yt.isBrowserSupported()||ht.isBrowserSupported()}};function fa(n,r,e,t,i,a,s){let o=0;r&&(o|=1),e&&(o|=2),t&&(o|=4),s||(o|=8);let p=new ArrayBuffer(11),u=new DataView(p);if(u.setUint8(0,1),u.setUint16(1,i),u.setUint32(3,n),u.setUint8(7,a?1:0),u.setUint16(8,0),u.setUint8(10,o),!s)return p;let h=new Uint8Array(p.byteLength+s.byteLength);return h.set(new Uint8Array(p),0),h.set(new Uint8Array(s),p.byteLength),h.buffer}function Sa(n){let r=new DataView(n),e=r.getUint8(0),t=r.getUint16(1),i=r.getUint32(3),a=r.getUint8(7)===1,s=r.getUint16(8),o=r.getUint8(10),p=!!(o&1),u=!!(o&2),h=!!(o&4),I=!!(o&8);if(e!==1)throw new Error(`Unexpected protocol version. Got ${e}, expected 1`);return{timestamp:i,start:p,end:u,keyframe:h,sequence:t,isVP9:a,ssrc:s,eos:I,data:n.slice(11)}}function va(n){if(!n||!n.byteLength||n.byteLength!==4)return!1;let r=new DataView(n);return!(r.getUint8(0)!==1||r.getUint8(1)!==1||r.getUint16(2)!==0)}function Ea(n){if(!n||!n.byteLength||n.byteLength!==10)return null;let r=new DataView(n);if(r.getUint8(0)!==1||r.getUint8(1)!==2||r.getUint16(2)!==0)return null;let a=r.getUint16(4),s=r.getUint32(6);return{seq:a,ts2:s}}var P=ni(require("simple-ebml-builder"));var bn=kr(2,15)-1,lr=1,Mn=5,An=5;var Wt=class{constructor(r){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=r;let e=()=>{this._mediaSource.removeEventListener("sourceopen",e),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",e,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let t=this._sourceBuffer.buffered.start(0);t<this._clearBufferTill&&(this._sourceBuffer.remove(t,this._clearBufferTill),d.debug(`[WebmBuilder] SourceBuffer cleanup from ${t} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let r=this._queue;this._queue=[];let e=Wt._buildQueue(r);this._sourceBuffer.appendBuffer(e)}static _buildQueue(r){if(r.length){if(r.length===1)return P.build(r[0])}else return new Uint8Array;let e=r.reduce((a,s)=>a+s.countSize(),0),t=new Uint8Array(e),i=0;for(let a of r){let s=P.build(a);t.set(s,i),i+=s.byteLength}return t}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(r){var e;return this._codec=r,(e=this._sourceBuffer)==null?void 0:e.changeType(r)}append(r,e=!1){this._queue.push(r),e&&this._handleQueue()}cleanup(){var a,s,o;((a=this._mediaSource)==null?void 0:a.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let r=(o=this._sourceBuffer)==null?void 0:o.buffered,e=r==null?void 0:r.length;if(!e)return;let t=r.start(0),i=Math.max(0,r.end(e-1)-Mn);i-t>An&&(this._clearBufferTill=i)}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 r;return(r=this._sourceBuffer)==null?void 0:r.buffered}},be=class extends et{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;d.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return P.element(P.ID.EBML,[P.element(P.ID.EBMLVersion,P.number(1)),P.element(P.ID.EBMLReadVersion,P.number(1)),P.element(P.ID.EBMLMaxIDLength,P.number(4)),P.element(P.ID.EBMLMaxSizeLength,P.number(8)),P.element(P.ID.DocType,P.string("webm")),P.element(P.ID.DocTypeVersion,P.number(2)),P.element(P.ID.DocTypeReadVersion,P.number(2))])}static _genSegmentHeader(e,t,i){let a=P.element(P.ID.Info,[P.element(P.ID.TimecodeScale,P.number(1e6)),P.element(P.ID.MuxingApp,P.string("vk-webm-builder")),P.element(P.ID.WritingApp,P.string("vk-webm-builder"))]),s=[P.element(P.ID.PixelWidth,P.number(e)),P.element(P.ID.PixelHeight,P.number(t))],o=P.element(P.ID.Tracks,P.element(P.ID.TrackEntry,[P.element(P.ID.TrackNumber,P.number(lr)),P.element(P.ID.TrackUID,P.number(lr)),P.element(P.ID.TrackType,P.number(1)),P.element(P.ID.FlagLacing,P.number(0)),P.element(P.ID.DefaultDuration,P.number(1e9)),P.element(P.ID.CodecID,P.string(`V_${i.toUpperCase()}`)),P.element(P.ID.Video,s)]));return P.unknownSizeElement(P.ID.Segment,[a,o])}static _genClusterHeader(e){return P.unknownSizeElement(P.ID.Cluster,[P.element(P.ID.Timecode,P.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new Wt(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){d.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=()=>d.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,d.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),d.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let o=be._genWebmHeader();this._mediaBuffer.append(o);let p=be._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(p)}let a=Math.round(i-this._clusterStartTime);if(a>bn&&(this._clusterStartTime=i,a=0),a===0){d.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let o=be._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(o)}let s=P.element(P.ID.SimpleBlock,[P.vintEncodedNumber(lr),P.bytes(be._intToU16BE(a)),P.number((e.keyframe?1:0)<<7),P.bytes(e.frameData)]);this._mediaBuffer.append(s,!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),d.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var _t=class{constructor(r,e,t,i){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};d.debug("ScreenCaptureReceiver started"),this._datachannel=r,this._participantIdRegistry=e,this._onStream=t,this._onEos=i,this._datachannel.onmessage=a=>this._onDataChannelMessage(a.data)}_onDataChannelMessage(r){var a,s;let e=Sa(r),t=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(e.ssrc))==null?void 0:s.participantId;if(!t){d.warn(`Participant id for ssrc ${e.ssrc} not found in registry`);return}if(e.eos){this.close(t),this._onEos(t);return}let i=this._streamBuilders[t];if(!i){let o=p=>this._onStream(t,p);l.screenShareWebmBuilder&&be.isBrowserSupported()?i=new be(t,o):i=new bt(t,o),this._streamBuilders[t]=i}i.appendChunk(e)}close(r){let e=this._streamBuilders[r];e&&(e.destroy(),delete this._streamBuilders[r])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(r=>r.destroy()),this._streamBuilders={},this._participantIdRegistry=null,d.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(He.isBrowserSupported()||pt.isBrowserSupported())&&(bt.isBrowserSupported()||be.isBrowserSupported())}};var pr=ni(require("@vkontakte/libvpx"));var Dn=1e3,Mt=class extends Le{constructor(e,t,i,a){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._useCongestionControl=i,this._maxBitrate=a,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return c(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let a=this._video;a.srcObject=new MediaStream([e]),a.onloadeddata=p=>t(),a.onerror=()=>i(new Error("Video element error"));let s=a.play(),o=()=>i(new Error("Autoplay is disabled"));s?s.catch(o):o()}})})}_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");this._video.paused&&this._video.play();let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return c(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var a;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(),(a=this._canvasCtx)==null?void 0:a.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return c(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;d.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`"use strict";var exports=(()=>{var b=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var V=(a,r)=>{for(var s in r)b(a,s,{get:r[s],enumerable:!0})},h=(a,r,s,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of x(r))!y.call(a,e)&&e!==s&&b(a,e,{get:()=>r[e],enumerable:!(i=R(r,e))||i.enumerable});return a};var M=a=>h(b({},"__esModule",{value:!0}),a);var F={};V(F,{default:()=>A});var A=(a,r,s,i)=>{let e;function m(t,o){return a({locateFile:r}).then(n=>{if(e=new n.VpxEncoder,e.debug(o),!e.init(t?n.VpxType.VP9:n.VpxType.VP8))throw self.postMessage({type:"log_error",message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");if(s){let d=Math.round(i/1e3);e.setTargetBitrate(d)}else e.setMaxQuantizer(10),e.setTargetBitrate(1024)})}function E(t,o,n,p){let d=e.allocateImage(t,o);if(!d){self.postMessage({type:"frame",error:"No buffer data"});return}d.set(new Uint8Array(n));let f=Math.round(performance.now()),u=150;if(!e.encode(f,u,p)){self.postMessage({type:"frame",error:"Encode failed"});return}let c=e.readFrame();if(!c){self.postMessage({type:"frame",error:"No encoded data"});return}e.readFrame()&&(self.postMessage({type:"debug",message:"LibVPxEncoder dropped frame"}),self.postMessage({type:"log_error",message:"LibVPxEncoder-drop"}));let l=new Uint8Array(c.byteLength);l.set(c),self.postMessage({type:"frame",frameType:p?"key":"delta",timestamp:f,duration:u,width:t,height:o,data:l.buffer},[l.buffer])}function g(t,o){let n=Math.round(t/1e3);e.setTargetBitrate(n)}self.onmessage=t=>{switch(t.data.type){case"init":m(t.data.isVP9,t.data.debug).then(()=>self.postMessage({type:"ready"})).catch(o=>self.postMessage({type:"error",error:String(o)}));break;case"frame":E(t.data.width,t.data.height,t.data.imageData,t.data.keyFrame);break;case"set_bitrate":g(t.data.bitrate,t.data.useCbr);break}}};return M(F);})();
10
+ `,i=>{var a;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(a=i.data)==null?void 0:a.byteLength,width:i.width,height:i.height})},[pr.default,pr.default.getUrl,this._useCongestionControl,this._maxBitrate],{isVP9:this.isVP9(),debug:d.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker("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)},Dn),this._getFrameBitmap().then(t=>{var a;window.clearTimeout(this._frameReadTimeout),(a=this._lastFrame)==null||a.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)}setBitrate(e,t=!1){this._sendToWorker("set_bitrate",{bitrate:e,useCbr:t})}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),d.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var gt=class extends Le{constructor(e,t,i,a,s,o){super();this._sourceTrack=e,this._onFrame=t,this._useCongestionControl=i,this._maxBitrate=a,this._useCbr=s,this._frameRate=o,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return c(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;d.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`"use strict";var exports=(()=>{var b=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var _=(a,t)=>{for(var n in t)b(a,n,{get:t[n],enumerable:!0})},x=(a,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of T(t))!B.call(a,r)&&r!==n&&b(a,r,{get:()=>t[r],enumerable:!(i=C(t,r))||i.enumerable});return a};var I=a=>x(b({},"__esModule",{value:!0}),a);var O={};_(O,{default:()=>M});var M=()=>{let t,n,i,r,R,E,l=null,p=0,s=!1,d=0,g,V,c=!1;function h(e){t=e.readable,n=t.getReader(),i=e.width,r=e.height,R=e.isVP9,E=e.framerate,g=e.useCongestionControl,V=e.maxBitrate,g&&(d=V,c=e.useCbr),u(),self.postMessage({type:"ready"})}function y(e){p=self.setTimeout(()=>{l&&A(l,e)},1e3),!s&&(s=!0,n.read().finally(()=>{s=!1,self.clearTimeout(p)}).then(({done:o,value:m})=>{if(l==null||l.close(),l=null,!(o||!m)){if(!f){n.releaseLock(),t.cancel();return}l=m,A(m,e)}}))}function A(e,o){(e.codedWidth!==i||e.codedHeight!==r)&&(i=e.codedWidth,r=e.codedHeight,u()),f.encode(e,{keyFrame:o})}function u(){let e={framerate:E,codec:R?"vp09.00.50.08":"vp8",width:i,height:r,latencyMode:"realtime",bitrateMode:c?"constant":"variable"};d>0&&(e.bitrate=d),f.configure(e)}function F(e,o=!1){d=e,c=o,u()}let f=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:"frame",frameType:e.type,timestamp:e.timestamp,duration:e.duration,width:i,height:r,data:o},[o])},error:e=>{self.postMessage({type:"frame",error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case"init":h(e.data);break;case"frame":y(e.data.keyFrame);break;case"set_bitrate":F(e.data.bitrate,e.data.useCbr);break}}};return I(O);})();
11
+ `,a=>{var s;a.error?this._onFrame(null,a.error):this._onFrame({type:a.frameType,timestamp:a.timestamp,duration:a.duration,data:a.data,byteLength:(s=a.data)==null?void 0:s.byteLength,width:a.width,height:a.height})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:this._frameRate,useCongestionControl:this._useCongestionControl,maxBitrate:this._maxBitrate,useCbr:this._useCbr},[i])})}requestFrame(e=!1){this._sendToWorker("frame",{keyFrame:e})}setBitrate(e,t){this._sendToWorker("set_bitrate",{bitrate:e,useCbr:t})}isVP9(){return!0}destroy(){this._removeWorker(),d.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var kn=1.2,Ia=.8,On=2e3,wn=8e3,ur=8e3,xn=16e3,Ln=4,Nn=2e3,Ti=(t=>(t[t.NONE=0]="NONE",t[t.UP=1]="UP",t[t.DOWN=2]="DOWN",t))(Ti||{}),Kt=class{constructor(r,e,t,i,a){this._upPenalty=0;this._delayAvgShort=-1;this._delayAvgLong=-1;this._minDelay=Number.MAX_VALUE;this._maxDelay=0;this._largeDelayDuration=0;this._onCongestion=r,this._ccEnabled=i,this._minBitrate=e,this._maxBitrate=t,this._fastSharing=a,this._targetBitrate=this._maxBitrate,this._probing=!1;let s=Date.now();this._lastDown=0,this._lastUp=s,this._lastProbing=s,this._lastCheckDelay=0}checkDelay(r,e,t){let i=Date.now();if(this._calcDelay(e,i),this._delayAvgShort<=0||this._delayAvgLong<=0||!this._ccEnabled)return;let a=0,s=this._delayAvgShort-this._delayAvgLong,o=Math.round(Math.abs(s)*100/this._delayAvgLong),p=this._fastSharing?200:700,u=s>40&&o>30&&this._delayAvgShort>p,h=this._delayAvgShort>2e3;u||h?a=2:Math.abs(s)<40&&o<10&&this._delayAvgShort<2e3&&(a=1);let I=Math.round(this._targetBitrate/1e3),b=t;r%10===0&&d.debug(`#${r}: cc: delay=${e} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${o} -> ${Ti[a]} tr=${I} br=${t}`);let D=i-this._lastDown;if(a===2&&D>On){this._probing&&(this._upPenalty=Math.min(++this._upPenalty,Ln),this._probing=!1);let W=Ia*b*1e3;if(W>=this._targetBitrate&&(W=this._targetBitrate*Ia),W=Math.max(W,this._minBitrate),W<this._targetBitrate){let te=Math.round(W/1e3),me=Math.round(this._upPenalty*ur/1e3);d.log(`#${r}: cc: delay=${e} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${o} -> ${Ti[a]}`),d.log(`#${r}: cc: DOWN delay=${e} bitrate=${b} target=${I} -> newBitrate=${te} penalty=${me}s`),this._setBitrate(W,!0),this._targetBitrate=W}this._lastDown=i}let A=i-this._lastUp,Y=wn+this._upPenalty*ur;if(a===1&&A>Y&&D>Y){let W=Math.min(this._targetBitrate*kn,this._maxBitrate);if(W>this._targetBitrate){let te=Math.round(W/1e3),me=Math.round(this._targetBitrate/1e3),ve=Math.round(this._upPenalty*ur/1e3);d.log(`#${r}: cc: delay=${e} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${o} -> ${Ti[a]}`),d.log(`#${r}: cc: UP bitrate=${b} target=${me} -> newBitrate=${te} penalty=${ve}s`),this._setBitrate(W,!1),this._targetBitrate=W,this._probing=!0,this._lastProbing=i,this._lastUp=i}}let H=i-this._lastProbing;this._probing&&H>xn&&(this._probing=!1);let fe=i-this._lastDown;this._upPenalty>0&&fe>3*Y&&(d.log(`#${r}: cc: UP reset penalty: oldPenalty=${this._upPenalty}`),this._upPenalty=0)}_setBitrate(r,e){this._fastSharing&&(e=!0),this._onCongestion(r,e)}_calcDelay(r,e){if(!(r<=0)){if(this._delayAvgShort===-1&&(this._delayAvgShort=r,this._delayAvgLong=r),this._delayAvgShort=Math.round((this._delayAvgShort*3+r)/4),this._delayAvgLong=Math.round((this._delayAvgLong*23+r)/24),r>0&&r<this._minDelay?this._minDelay=r:r>this._maxDelay&&(this._maxDelay=r),this._lastCheckDelay===0&&(this._lastCheckDelay=e),r>Nn){let t=e-this._lastCheckDelay;this._largeDelayDuration+=t}this._lastCheckDelay=e}}reconfigure(r,e){this._minBitrate=r,this._maxBitrate=e}getStat(){if(this._minDelay===Number.MAX_VALUE||this._maxDelay===0||this._delayAvgLong<=0)return null;let r={minDelay:this._minDelay,maxDelay:this._maxDelay,avgDelay:this._delayAvgLong,largeDelayDuration:this._largeDelayDuration};return this._minDelay=Number.MAX_VALUE,this._maxDelay=0,this._largeDelayDuration=0,r}};var $t=class{constructor(r){this._size=0;this._head=0;this._tail=0;this._maxSize=r,this._buffer=new Array(r)}add(r,e,t,i,a){this._tail===this._head&&this._size>0&&(this._head=++this._head%this._maxSize);let s=this._tail;return this._buffer[this._tail]={seq:r,ts:e,size:t,sent:Date.now(),start:i,end:a,ts2:-1,recv:-1},this._tail=++this._tail%this._maxSize,this._size++,s}update(r,e){let t=this.get(r);return t===null?null:(t.ts2=e,t.recv=Date.now(),t)}get(r){let e=this._head;for(let t=0;t<this._maxSize;t++){if(r===this._buffer[e].seq)return this._buffer[e];if(e=++e%this._maxSize,e===this._tail)break}return null}getServerBitrateK(r){let e=0,t=0,i=-1,a=-1,s=this._tail;for(let o=0;o<this._maxSize;o++){s>0?--s:s=this._maxSize-1;let p=this._buffer[s];if(p===null||(a===-1&&(a=p.ts2,t=0),a>=0&&(t+=p.size),i=p.ts2,a-i>=r)||s===this._head)break}if(i>=0&&a>=0){let o=a-i;e=Math.round(o>0?t*8/o:0)}return e}getCurrentDelay(){let r=this._tail;for(let e=0;e<this._maxSize;e++){r>0?--r:r=this._maxSize-1;let t=this._buffer[r];if(t===null)break;if(t.recv>=0&&t.sent>=0)return t.recv-t.sent;if(r===this._head)break}return 0}getMaxBandwidth(){let r=0,e=0,t=-1,i=-1,a=this._tail;for(let s=0;s<this._maxSize;s++){if(a>0?--a:a=this._maxSize-1,i===-1&&this._buffer[a].end&&!this._buffer[a].start&&(i=this._buffer[a].ts2,e=0),t===-1&&i>=0&&this._buffer[a].start&&!this._buffer[a].end&&(t=this._buffer[a].ts2),t>=0&&i>=0){let o=i-t;r=o>0?e*8/o:0;break}if(i>=0&&(e+=this._buffer[a].size),a===this._head)break}return Math.round(r)}};var Bn=65536,Vn=50,Fn=400,jn=1e6,Hn=3e4,Ri=0,ft=class{constructor(r,e,t,i){this._destroyed=!1;this._needKeyframe=!0;this._frameNum=0;this._feedback=new $t(1024);this._lastSharingStat=Date.now();this._congestionControlEnabled=!1;d.debug("ScreenCaptureSender started"),this.DATA_SIZE=l.consumerScreenDataChannelPacketSize-11,this._datachannel=e,this._signaling=t,this._fastSharing=i,this._congestionControlEnabled=l.screenShareCongestionControl||this._fastSharing,this._width=r.getSettings().width,this._height=r.getSettings().height;let{minBitrate:a,maxBitrate:s}=this._calcMinMaxBitrate(this._width,this._height),o=this._onCongestionCallback.bind(this);d.log(`ScreenCaptureSender: CongestionControl: enabled=${this._congestionControlEnabled} minBitrate=${Math.round(a/1e3)}k maxBitrate=${Math.round(s/1e3)}k`),this._congestionControl=new Kt(o,a,s,this._congestionControlEnabled,this._fastSharing);let p=(u,h)=>{if(!this._destroyed){if(!u){d.warn("requestFrame failed, keyFrame: "+this._needKeyframe,h),this._needKeyframe=!0,this._requestFrame();return}(u.width!==this._width||u.height!==this._height)&&(this._width=u.width,this._height=u.height,this._onResize(this._width,this._height)),this._send(u).catch(I=>{d.warn("sendFrame failed",I),this._needKeyframe=!0}).finally(()=>{this._frameNum++,u.type==="key"&&d.debug(`#${this._frameNum}: sharing: send keyframe size=${Math.round(u.byteLength/1e3)}k`);let I=this._feedback.getCurrentDelay(),b=this._feedback.getServerBitrateK(2e3);I>0&&this._congestionControl.checkDelay(this._frameNum,I,b),this._requestFrame()}),this._sendSharingStat()}};if(gt.isBrowserSupported()){let u=this._fastSharing,h=l.getScreenFrameRate(this._fastSharing);this._encoder=new gt(r,p,this._congestionControlEnabled,s,u,h)}else this._encoder=new Mt(r,p,this._congestionControlEnabled,s);this._datachannel.onmessage=u=>{va(u.data)&&(d.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0);let h=Ea(u.data);h!==null&&this._checkCcFeedback(h)},this._encoder.init().then(()=>this._requestFrame()).catch(u=>d.warn("ScreenCaptureSender init failed",u))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(r,e,t,i,a){let s=fa(r,e,t,i,Ri,this._encoder.isVP9(),a);return Ri=(Ri+1)%Bn,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(r){return c(this,null,function*(){return new Promise((e,t)=>{this._sendChunk(r,0,e,t)})})}_sendChunk(r,e,t,i){if(!this._datachannel||this._datachannel.readyState!=="open"){i();return}let a=r.data.slice(e,e+this.DATA_SIZE),s=r.data.byteLength<=e+a.byteLength;this._feedback.add(Ri,r.timestamp,a.byteLength,!e,s);let o=this._wrapHeader(r.timestamp,!e,s,r.type==="key",a);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&t()}:null;try{this._datachannel.send(o)}catch(p){d.warn("Error send data to DataChannel",p),i();return}s||E.setImmediate(()=>this._sendChunk(r,e+this.DATA_SIZE,t,i))}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),d.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return gt.isBrowserSupported()||Mt.isBrowserSupported()}_onCongestionCallback(r,e){this._encoder.setBitrate(r,e)}_onResize(r,e){let{minBitrate:t,maxBitrate:i}=this._calcMinMaxBitrate(r,e),a=Math.round(t/1e3),s=Math.round(i/1e3);d.log(`cc: resize to ${r}x${e}, minBitrate=${a} maxBitrate=${s}`),this._congestionControl.reconfigure(t,i)}_calcMinMaxBitrate(r,e){(r===void 0||r<640)&&(r=640),(e===void 0||e<360)&&(e=360);let t=r*e/256,i=Math.min(jn,Math.round(t*Vn)),a=Math.round(t*Fn);return{minBitrate:i,maxBitrate:a}}_checkCcFeedback(r){this._feedback.update(r.seq,r.ts2)===null&&d.debug(`cc: update failed, seq=${r.seq}`)}_sendSharingStat(){let r=Date.now();if(r-this._lastSharingStat>Hn){let t=this._congestionControl.getStat();t!==null&&(d.debug(`cc: send stats: ${JSON.stringify(t)}`),this._signaling.reportSharingStat(t)),this._lastSharingStat=r}}};var ne=class{static get sessionKey(){return ne._sessionKey}static set sessionKey(r){ne._sessionKey=r}static get sessionSecretKey(){return ne._sessionSecretKey}static set sessionSecretKey(r){ne._sessionSecretKey=r}static get accessToken(){return ne._accessToken}static set accessToken(r){ne._accessToken=r}static isEmpty(){return!ne._sessionKey||!ne._sessionSecretKey}};var f=class{static set(r){r.hasOwnProperty("voiceParams")&&(Object.assign(f._params.voiceParams,r.voiceParams),delete r.voiceParams),r.hasOwnProperty("specListenerParams")&&(Object.assign(f._params.specListenerParams,r.specListenerParams),delete r.specListenerParams),r.hasOwnProperty("apiAuth")&&(ne.accessToken=r.apiAuth.accessToken,ne.sessionKey=r.apiAuth.sessionKey,ne.sessionSecretKey=r.apiAuth.sessionSecretKey),r.hasOwnProperty("api")&&(Object.assign(f._params.api,r.api),delete r.api),Object.assign(f._params,E.objectFilterOutValues(r,void 0))}static get(r){return f._params[r]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.7.2-dev.d37e896.0"}static get debug(){}static get protocolVersion(){return f._params.joinFromMultipleDevices?6:5}static get platform(){return f._params.platform}static set platform(r){f._params.platform=r}static get clientType(){return f._params.clientType}static set clientType(r){f._params.clientType=r}static get externalUserType(){return f._params.externalUserType}static set externalUserType(r){f._params.externalUserType=r}static get device(){return f._params.device}static get apiKey(){return f._params.apiKey}static get apiEnv(){return f._params.apiEnv}static get apiEndpoint(){switch(f.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return f._params.apiEnv}}static get authToken(){return f._params.authToken}static set authToken(r){f._params.authToken=r}static get anonymToken(){return f._params.anonymToken}static set anonymToken(r){f._params.anonymToken=r}static get domain(){return f._params.domain}static get externalDomain(){return f._params.externalDomain}static get iceServers(){return f._params.iceServers}static set iceServers(r){f._params.iceServers=r}static get wssBase(){return f._params.wssBase}static set wssBase(r){f._params.wssBase=r}static get wssToken(){return f._params.wssToken}static set wssToken(r){f._params.wssToken=r}static get signalingReconnectDelay(){return f._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return f._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return f._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return f._params.waitConnectionDelay}static get waitResponseDelay(){return f._params.waitResponseDelay}static get waitMessageDelay(){return f._params.waitMessageDelay}static get waitAnotherTabDelay(){return f._params.waitAnotherTabDelay}static get debugLog(){return f._params.debugLog}static get forceRelayPolicy(){return f._params.forceRelayPolicy}static set forceRelayPolicy(r){f._params.forceRelayPolicy=r}static get videoMinWidth(){return f._params.videoMinWidth}static get videoMaxWidth(){return f._params.videoMaxWidth}static set videoMaxWidth(r){f._params.videoMaxWidth=r}static get videoMinHeight(){return f._params.videoMinHeight}static get videoMaxHeight(){return f._params.videoMaxHeight}static set videoMaxHeight(r){f._params.videoMaxHeight=r}static get videoAspectRatio(){return f._params.videoAspectRatio}static get videoFrameRate(){return f._params.videoFrameRate}static get videoFacingMode(){return f._params.videoFacingMode||(C.isMobile()?"user":null)}static set videoFacingMode(r){f._params.videoFacingMode=r}static get displaySurface(){return f._params.displaySurface}static get videoEffects(){return f._params.videoEffects}static set videoEffects(r){f._params.videoEffects=r}static get videoEffectMaxWidth(){return f._params.videoEffectMaxWidth}static set videoEffectMaxWidth(r){f._params.videoEffectMaxWidth=r}static get videoEffectMaxHeight(){return f._params.videoEffectMaxHeight}static set videoEffectMaxHeight(r){f._params.videoEffectMaxHeight=r}static get useVmoji(){var r;return((r=f._params.vmoji)==null?void 0:r.isBrowserSupported())||!1}static get vmoji(){return f._params.vmoji}static set vmoji(r){f._params.vmoji=r}static get voiceParams(){return f._params.voiceParams}static get specListenerParams(){return f._params.specListenerParams}static get iceRestartWaitTime(){return f._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return f._params.transportConnectionWaitTime}static get statisticsInterval(){return f._params.statisticsInterval}static set statisticsInterval(r){f._params.statisticsInterval=r}static get networkStatisticsInterval(){return f._params.networkStatisticsInterval}static get perfStatReportEnabled(){return f._params.perfStatReportEnabled}static get callStatReportEnabled(){return f._params.callStatReportEnabled}static get producerNotificationDataChannel(){return f._params.producerNotificationDataChannel}static get producerCommandDataChannel(){return f._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return f._params.consumerScreenDataChannel&&ft.isBrowserSupported()}static get producerScreenDataChannel(){return f._params.producerScreenDataChannel&&f.producerNotificationDataChannel&&_t.isBrowserSupported()}static get asrDataChannel(){return f._params.asrDataChannel&&f.producerNotificationDataChannel}static get consumerScreenDataChannelPacketSize(){return f._params.consumerScreenDataChannelPacketSize}static get screenShareWebmBuilder(){return f._params.screenShareWebmBuilder}static get noiseSuppression(){return f._params.noiseSuppression}static set noiseSuppression(r){f._params.noiseSuppression=r}static get preferH264(){return f._params.preferH264}static get preferVP9(){return f._params.preferVP9}static get audioNack(){return f._params.audioNack}static get consumerScreenTrack(){return f._params.consumerScreenTrack&&f.consumerScreenDataChannel}static get producerScreenTrack(){return f._params.producerScreenTrack}static get movieShare(){return f._params.movieShare&&f.videoTracksCount>0}static get videoTracksCount(){return f.producerNotificationDataChannel?f._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return f._params.breakVideoPayloadTypes}static get filteredMessages(){return f._params.filteredMessages}static get useParticipantListChunk(){return f._params.useParticipantListChunk&&f._params.videoTracksCount>0}static get useRooms(){return f._params.useRooms}static get participantListChunkInitIndex(){var r;return(r=f._params.participantListChunkInitIndex)!=null?r:0}static get participantListChunkInitCount(){var r;return(r=f._params.participantListChunkInitCount)!=null?r:null}static get serverAudioRed(){return f._params.serverAudioRed&&C.canPreferRed()}static get p2pAudioRed(){return f._params.p2pAudioRed&&C.canPreferRed()}static get h264spsPpsIdrInKeyframe(){return f._params.h264spsPpsIdrInKeyframe}static get batchParticipantsOnStart(){return f._params.batchParticipantsOnStart}static get filterObservers(){return f._params.filterObservers}static get muteMode(){return f._params.muteMode}static get preserveAudioTracks(){return f._params.preserveAudioTracks}static get audioShare(){return C.isAudioShareSupported()&&f._params.audioShare}static get fastScreenShare(){return f._params.fastScreenShare}static get screenShareCongestionControl(){return f._params.screenShareCongestionControl}static get api(){return f._params.api}static get fastScreenShareWidth(){return f._params.fastScreenShareWidth}static get fastScreenShareHeight(){return f._params.fastScreenShareHeight}static getScreenFrameRate(r){return r?f._params.fastScreenShareFrameRate:f._params.screenFrameRate}},l=f;l._params={platform:"WEB",clientType:"PORTAL",externalUserType:"",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",externalDomain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoFacingMode:null,displaySurface:"monitor",videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,vmoji:null,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,asrDataChannel:!1,consumerScreenDataChannelPacketSize:64*1024,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,useParticipantListChunk:!1,useRooms:!1,participantListChunkInitIndex:0,participantListChunkInitCount:null,serverAudioRed:!1,p2pAudioRed:!1,h264spsPpsIdrInKeyframe:!0,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1,audioShare:!1,fastScreenShare:!1,screenShareCongestionControl:!1,api:{userIdsByOkBatchedTimeout:1e3},fastScreenShareFrameRate:24,fastScreenShareWidth:1280,fastScreenShareHeight:720};var Ci=(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",p))(Ci||{});function F(n,...r){let e=l.get(n);e&&setTimeout(e,0,...r)}function de(n,r,...e){if(l.filterObservers){if(Array.isArray(r)){if(r=r.filter(t=>!t.observer),!r.length)return}else if(r.observer)return}F(n,r,...e)}function Te(n){return Object.assign({},n)}function St(n){return n.slice()}var mr;(tc=>{function n(m,y){F("onLocalStream",m,Te(y))}tc.onLocalStream=n;function r(m,y){F("onScreenStream",m,Te(y))}tc.onScreenStream=r;function e(m,y){F("onVmojiStream",m,Te(y))}tc.onVmojiStream=e;function t(m,y){F("onLocalStreamUpdate",Te(m),y)}tc.onLocalStreamUpdate=t;function i(m){F("onLocalStatus",m)}tc.onLocalStatus=i;function a(m,y){de("onRemoteStream",m,y)}tc.onRemoteStream=a;function s(m,y){de("onRemoteLive",m,y)}tc.onRemoteLive=s;function o(m,y){de("onLocalLive",m,y)}tc.onLocalLive=o;function p(m,y){de("onRemoteLiveUpdate",m,y)}tc.onRemoteLiveUpdate=p;function u(m,y){de("onLocalLiveUpdate",m,y)}tc.onLocalLiveUpdate=u;function h(m,y){de("onRemoteScreenStream",m,y)}tc.onRemoteScreenStream=h;function I(m,y){de("onRemoteVmojiStream",m,y)}tc.onRemoteVmojiStream=I;function b(m,y,ee,Ke,Vt){de("onConversation",m,Te(y),Te(ee),Ke,Vt)}tc.onConversation=b;function D(m){m&&F("onConversationParticipantListChunk",m)}tc.onConversationParticipantListChunk=D;function A(m,y,ee){de("onRemoteMediaSettings",m,Te(y),ee)}tc.onRemoteMediaSettings=A;function Y(m,y){de("onLocalMediaSettings",m,Te(y))}tc.onLocalMediaSettings=Y;function H(m,y){de("onRemoteSharedMovieInfo",m,Te(y))}tc.onRemoteSharedMovieInfo=H;function fe(m,y){de("onRemoteSharedMovieStoppedInfo",m,Te(y))}tc.onRemoteSharedMovieStoppedInfo=fe;function W(m,y){de("onLocalSharedMovieInfo",m,Te(y))}tc.onLocalSharedMovieInfo=W;function te(m,y){de("onLocalSharedMovieStoppedInfo",m,Te(y))}tc.onLocalSharedMovieStoppedInfo=te;function me(m,y){de("onParticipantAdded",m,y)}tc.onParticipantAdded=me;function ve(m,y){de("onParticipantJoined",m,y)}tc.onParticipantJoined=ve;function st(m,y,ee){de("onRemoteParticipantState",m,Te(y),ee)}tc.onRemoteParticipantState=st;function ai(m,y,ee=null){de("onRemoteStatus",m,y,ee)}tc.onRemoteStatus=ai;function X(m,y,ee=null){de("onParticipantStatus",m,y,ee)}tc.onParticipantStatus=X;function Cr(){F("onPermissionsRequested")}tc.onPermissionsRequested=Cr;function Pr(m,y){F("onPermissionsError",m,y)}tc.onPermissionsError=Pr;function yr(m,y){de("onRemoteRemoved",m,y)}tc.onRemoteRemoved=yr;function Q(m,y,ee){F("onCallState",m,y,Te(ee))}tc.onCallState=Q;function Vi(m,y){F("onDeviceSwitched",m,y)}tc.onDeviceSwitched=Vi;function Fi(m,y,ee,Ke=!1,Vt=!1,Hi=null,Gi=null,Za,br,en=null){let tn=br?St(br):void 0;F("onMuteStates",Te(m),St(y),St(ee),Ke,Vt,Hi,Gi,Za,tn,en)}tc.onMuteStates=Fi;function ji(m,y){de("onRolesChanged",m,St(y))}tc.onRolesChanged=ji;function v(m){F("onLocalRolesChanged",St(m))}tc.onLocalRolesChanged=v;function R(m,y,ee){de("onPinnedParticipant",m,y,ee)}tc.onPinnedParticipant=R;function M(m){F("onLocalPin",m)}tc.onLocalPin=M;function O(m){F("onOptionsChanged",St(m))}tc.onOptionsChanged=O;function _(){F("onCallAccepted")}tc.onCallAccepted=_;function k(){F("onRateNeeded")}tc.onRateNeeded=k;function G(m){de("onSpeakerChanged",m)}tc.onSpeakerChanged=G;function J(m){F("onVolumesDetected",St(m))}tc.onVolumesDetected=J;function le(m,y){F("onLocalVolume",m,y)}tc.onLocalVolume=le;function he(m,y){F("onJoinStatus",m,y)}tc.onJoinStatus=he;function Ue(m,y){F("onHangup",m,y)}tc.onHangup=Ue;function ke(m){F("onMultipartyChatCreated",Te(m))}tc.onMultipartyChatCreated=ke;function Oe(){F("onDeviceChange")}tc.onDeviceChange=Oe;function we(m){F("onFingerprintChange",m)}tc.onFingerprintChange=we;function Be(){F("onTokenExpired")}tc.onTokenExpired=Be;function N(m,y,ee=!1){F("onChatMessage",m,y,ee)}tc.onChatMessage=N;function Bt(m,y,ee=!1){F("onCustomData",m,y,ee)}tc.onCustomData=Bt;function B(m,y,ee,Ke,Vt,Hi,Gi=null){F("onRecordStarted",m,y,ee,Ke,Vt,Hi,Gi)}tc.onRecordStarted=B;function q(m=null){F("onRecordStopped",m)}tc.onRecordStopped=q;function _e(m){F("onLocalNetworkStatusChanged",m)}tc.onLocalNetworkStatusChanged=_e;function Ee(m){F("onNetworkStatusChanged",m)}tc.onNetworkStatusChanged=Ee;function ie(m,...y){F("onDebugMessage",m,...y)}tc.onDebugMessage=ie;function Z(m,y){let ee=Object.assign({},m,{memory:y});F("onStatistics",ee)}tc.onStatistics=Z;function oe(){F("onAutoplayError")}tc.onAutoplayError=oe;function We(m,y,ee){F("onChatRoomUpdated",m,y,ee)}tc.onChatRoomUpdated=We;function Ho(m){F("onRemoteMixedAudioStream",m)}tc.onRemoteMixedAudioStream=Ho;function Go(m){F("onJoinLinkChanged",m)}tc.onJoinLinkChanged=Go;function Wo(m){F("onRoomsUpdated",m)}tc.onRoomsUpdated=Wo;function Ko(m,y,ee,Ke){F("onRoomUpdated",m,y,ee,Ke)}tc.onRoomUpdated=Ko;function $o(m){F("onRoomParticipantsUpdated",m)}tc.onRoomParticipantsUpdated=$o;function qo(m){F("onRoomSwitched",m)}tc.onRoomSwitched=qo;function Jo(m){F("onRoomStart",m)}tc.onRoomStart=Jo;function zo(m,y=null){F("onFeedback",m,y)}tc.onFeedback=zo;function Yo(m){F("onFeaturesPerRoleChanged",m)}tc.onFeaturesPerRoleChanged=Yo;function Qo(m){F("onVmojiSvgUpdate",m)}tc.onParticipantVmojiUpdate=Qo;function Xo(m,y){F("onAsrStarted",m,y)}tc.onAsrStarted=Xo;function Zo(){F("onAsrStopped")}tc.onAsrStopped=Zo;function ec(m,y,ee,Ke){F("onAsrTranscription",m,y,ee,Ke)}tc.onAsrTranscription=ec})(mr||(mr={}));var g=mr;var _r=(i=>(i.DEBUG="DEBUG",i.LOG="LOG",i.WARN="WARN",i.ERROR="ERROR",i))(_r||{}),hr;(te=>{let n="📞",r=(me,...ve)=>{g.onDebugMessage(me,...ve)},e=!1,t=(me,ve)=>(...st)=>{me(...st),sa(ve,st)},i=console.debug.bind(console,n),a=console.log.bind(console,n),s=console.warn.bind(console,n),o=console.error.bind(console,n),p=r.bind(null,"DEBUG"),u=r.bind(null,"LOG"),h=r.bind(null,"WARN"),I=r.bind(null,"ERROR");te.debug=p,te.log=u,te.warn=h,te.error=I;function H(){return e}te.enabled=H;function fe(me){e=me,l.debugLog&&zi(),me?(te.debug=l.debugLog?t(i,"DEBUG"):i,te.log=l.debugLog?t(a,"LOG"):a,te.warn=l.debugLog?t(s,"WARN"):s,te.error=l.debugLog?t(o,"ERROR"):o):(te.debug=l.debugLog?t(p,"DEBUG"):p,te.log=l.debugLog?t(u,"LOG"):u,te.warn=l.debugLog?t(h,"WARN"):h,te.error=l.debugLog?t(I,"ERROR"):I)}te.toggle=fe;function W(me,...ve){switch(me){case"DEBUG":(0,te.debug)(...ve);break;case"LOG":(0,te.log)(...ve);break;case"WARN":(0,te.warn)(...ve);break;case"ERROR":(0,te.error)(...ve);break}}te.send=W})(hr||(hr={}));var d=hr;var Pi=(t=>(t.USER="USER",t.ANONYM="ANONYM",t.GROUP="GROUP",t))(Pi||{}),Se;(o=>{function n(p){return p.length?typeof p[0]=="object"?p:p.map(u=>r(u)):[]}o.fromIds=n;function r(p,u="USER"){return{id:p,type:u}}o.fromId=r;function e(p){return{id:p.id,type:p.type==="ANONYM"?"ANONYM":"USER"}}o.fromSignaling=e;function t(p){return`{"id":"${p.id}","type":"${p.type}"}`}o.toString=t;function i(p,u="USER"){return t(r(p,u))}o.fromIdToString=i;function a(p){try{return JSON.parse(p)}catch(u){throw new Error(`Failed to parse ExternalId from string '${p}'`)}}o.fromString=a;function s(p,u){return p.id===u.id&&p.type===u.type}o.compare=s})(Se||(Se={}));var pe;(i=>{function n(a,s="USER",o=0){return{id:a,type:s,deviceIdx:o}}i.fromId=n;function r(a){return`{"id":"${a.id}","type":"${a.type}","deviceIdx":"${a.deviceIdx}"}`}i.toString=r;function e(a,s){return Object.assign({deviceIdx:s},Se.fromSignaling(a))}i.fromSignaling=e;function t(a){return a&&typeof a=="object"?a.deviceIdx:0}i.getDeviceIdx=t})(pe||(pe={}));var Gn="kf";function qt(n){return n.stopStream}function gr(n){return n.keyFrameRequested}function Ta(n){if(qt(n))return"ss";if(gr(n))return Gn;let r="";return n.priority!==void 0&&(r+="p="+n.priority),n.width!==void 0&&n.height!==void 0&&(r!==""&&(r+=":"),r+="sz="+Math.round(n.width)+"x"+Math.round(n.height)),n.fit!==void 0&&(r!==""&&(r+=":"),r+="fit="+n.fit),r}var At=(s=>(s.CAMERA="CAMERA",s.SCREEN="SCREEN",s.STREAM="STREAM",s.MOVIE="MOVIE",s.AUDIOSHARE="AUDIOSHARE",s.ANIMOJI="ANIMOJI",s))(At||{}),Ra="s",Ca="m";function Ge(n){return n.participantId+(n.mediaType?It+Ra+n.mediaType:"")+(n.streamName?It+Ca+n.streamName:"")}function Jt(n){let r=n.split(It),e=r.shift();if(!e)throw new Error("Illegal stream description: "+n);let t=null,i,a=0;for(let o of r)switch(o.charAt(0)){case Ra:t=Wn(o.slice(1));break;case Ca:i=o.slice(1);break;case ui:a=Number.parseInt(o.slice(1),10);break;default:throw new Error("Unexpected parameter type "+o.charAt(0)+" in stream description "+n)}return{participantId:E.compose(e,a),mediaType:t,streamName:i}}function Wn(n){for(let r of Object.keys(At))if(r===n)return At[r];return null}function fr(n,r){return n===null||r===null?n===null&&r===null:!(n.maxDimension!==r.maxDimension||n.maxBitrateK!==r.maxBitrateK||n.maxFramerate!==r.maxFramerate||n.degradationPreference!==r.degradationPreference)}function yi(n,r){return!(!fr(n.camera,r.camera)||!fr(n.screenSharing,r.screenSharing))}function Sr(n,r){return{camera:Object.assign({},n.camera,r.camera),screenSharing:Object.assign({},n.screenSharing,r.screenSharing)}}function Pa(n){try{return btoa(JSON.stringify(n))}catch(r){d.warn("WaitingParticipant: failed convert to string",n,r)}return null}function ya(n){try{return JSON.parse(atob(n))}catch(r){d.warn("WaitingParticipant: failed convert from string",n,r)}return null}var Dt=(n,r)=>E.objectReduce(n,(e,t,i)=>(t===r&&e.push(i),e),[]);var kt=class{constructor(r){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=r}_fixAudioDeviceNoPackets(r){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,S.log(T.ERROR,`audio_device_recover_${r.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!r.bandwidth&&(this._fixNoPacketsApplied=!0,S.log(T.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(r){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let e=75,t=Date.now();if(!this._lastPacketsSentTime)r.packetsSent>0&&(this._lastPacketsSentTime=t,this._lastPacketsSent=r.packetsSent);else if(t-this._lastPacketsSentTime>500){let i=(r.packetsSent-this._lastPacketsSent)*1e3/(t-this._lastPacketsSentTime);this._lastPacketsSentTime=t,this._lastPacketsSent=r.packetsSent,this._fixTooManyPacketsApplied?i>e?(d.log("Failed to fix RV"),S.log(T.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):t-this._fixTooManyPacketsTime>6e4&&(d.log("Fixed RV"),S.log(T.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):i>e&&(this._fixTooManyPacketsApplied=!0,d.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=t)}}fix(r){if(!this._mediaSource)return;let e=r.find(t=>t.kind==="audio");e&&(this._fixAudioDeviceNoPackets(e),this._fixAudioDeviceTooManyPackets(e))}};var zt=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(r){this.destroy(),this._output={},this._output.audioTrack=r,this._initAudioElement()}remove(r){!this._output||this._output.audioTrack!==r||this.destroy()}get volume(){return this._volume}set volume(r){this._volume=Math.max(0,Math.min(1,r)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(l.muteMode||!((s=this._output)!=null&&s.audioTrack))return;let r=C.browserName()!=="Safari"||C.isMobile(),e=document.createElement(r?"audio":"video");e.muted=!1,e.volume=this._volume,e.preload="auto";let t=()=>{d.warn("Error on play audio"),g.onAutoplayError()},i=o=>{e.srcObject=new MediaStream([o]),e.load();let p=e.play();p&&p.catch(t)},a=()=>{var p;d.debug("Recover audio playback");let o=(p=this._output)==null?void 0:p.audioTrack;o?i(o):d.warn("Broken audio track")};e.onpause=a,e.onstalled=a,e.onerror=a,i(this._output.audioTrack),this._output.audioElement=e}_stopAudioElement(){var r,e,t;(r=this._output)!=null&&r.audioElement&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(t=(e=this._output)==null?void 0:e.audioTrack)==null||t.stop()}destroy(){this._output&&(this._stopAudioElement(),this._output=null)}changeOutput(){return c(this,null,function*(){var r,e,t;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((r=this._output)!=null&&r.audioElement))throw new Error("Audio Element is not initialized");let i=C.getSavedOutput();i&&(yield(t=(e=this._output.audioElement).setSinkId)==null?void 0:t.call(e,i.deviceId))}catch(i){throw S.log(T.ERROR,"change_output"),d.error("Output change failed",i),i}})}};var Kn=90,$n=3,Yt=class extends re{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let a=typeof i.userId=="string"&&t[i.userId]||null;i.userId=a==null?void 0:a.externalId}),g.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var a;let e=(a=window==null?void 0:window.performance)==null?void 0:a.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>Kn?d.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=$n)&&(d.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var qn=44100,Ot=class{constructor(r,e){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=r,this._stream=e;try{let t=C.getAudioContext();this._gainNode=t.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(t.destination),this._analyser=t.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=t.createMediaStreamSource(e),this._mediaStreamSource.connect(this._analyser)}catch(t){}}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 r=qn/this._fftBins.length,e=Math.ceil(l.voiceParams.minFreq/r),t=Math.floor(l.voiceParams.maxFreq/r);return this._fftBins.subarray(e,t)}getLevel(){let r=this._getBins(),t=r.reduce((a,s)=>a+s,0)/r.length/255,i=this._lastSmoothedLevel*l.voiceParams.smoothing+t*(1-l.voiceParams.smoothing);return this._lastSmoothedLevel=i,{real:t,smoothed:i}}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 Qt=class extends re{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&g.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,l.voiceParams.interval)};this._interval=window.setTimeout(t,l.voiceParams.interval);let i=()=>{let a=e.getStream();a&&this.init(a)};this.subscribe(e,"SOURCE_CHANGED",a=>{a.kind==="audio"&&a.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks().find(i=>!i.contentHint);t&&(this._track=t.clone(),this._detector=new Ot("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 ba=(s=>(s.producerNotification="producerNotification",s.producerCommand="producerCommand",s.consumerScreenShare="consumerScreenShare",s.producerScreenShare="producerScreenShare",s.asr="asr",s.animoji="animoji",s))(ba||{}),ze=ba;var Ma="videochat-epi",Jn=5e3,zn=3e4,tt=class extends re{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,"REMOTE_DATA_STATS",this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Ma)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return c(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&l.perfStatReportEnabled&&this._previousTimestamp+Jn<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),l.callStatReportEnabled&&this._previousCallStatReportTimestamp+zn<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return c(this,null,function*(){let t=e.inbound.rtps.reduce((i,a)=>(a.kind==="video"&&(i.framesDecoded+=a.framesDecoded||0,i.framesReceived+=a.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(Ma,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((a,s)=>(s.kind==="video"?(s.framesReceived&&(a.jitter_video=a.jitter_video*a.inbound_video_count/(a.inbound_video_count+1)+s.jitter*1e3/(a.inbound_video_count+1),a.interframe_delay_variance=a.interframe_delay_variance*a.inbound_video_count/(a.inbound_video_count+1)+s.interframeDelayVariance*1e6/(a.inbound_video_count+1),a.inbound_video_count++),a.frames_dropped+=s.framesDropped,a.nack_sent+=s.nackCount,a.pli_sent+=s.pliCount,a.fir_sent+=s.firCount):(s.totalSamplesReceived&&(a.jitter_audio=a.jitter_audio*a.inbound_audio_count/(a.inbound_audio_count+1)+s.jitter*1e3/(a.inbound_audio_count+1),a.total_audio_energy=a.total_audio_energy*a.inbound_audio_count/(a.inbound_audio_count+1)+s.totalAudioEnergy/(a.inbound_audio_count+1),a.inbound_audio_count++),a.total_audio_samples_received+=s.totalSamplesReceived,a.inserted_audio_samples_for_deceleration+=s.insertedSamplesForDeceleration,a.removed_audio_samples_for_acceleration+=s.removedSamplesForAcceleration,a.concealed_audio_samples+=s.concealedSamples,a.silent_concealed_audio_samples+=s.silentConcealedSamples,a.audio_concealment_events+=s.concealmentEvents),a),t),e.outbound.rtps.reduce((a,s)=>(s.kind==="video"&&(a.nack_received+=s.nackCount,a.pli_received+=s.pliCount,a.fir_received+=s.firCount),a),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let a=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,s=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,o=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,p=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,u=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,h=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=s/a*1e3,i.removed_audio_samples_for_acceleration=o/a*1e3,i.concealed_audio_samples=p/a*1e3,i.concealed_silent_audio_samples=u/a*1e3,i.concealment_audio_avg_size=p/h,i.total_audio_energy=t.total_audio_energy}S.logCustom("callStat",i),d.log("Sent call stats",i),this._previousCallStatReport=t}};var Yn=1e3;function ue(n,r,e=0){return r in n&&n[r]?n[r]:e}function Aa(...n){return r=>{for(let e of n)if(e(r))return!0;return!1}}function it(n,r){return e=>e[n]===r}function Qn(n){return(r,e)=>r[n]-e[n]}function bi(n,r){return r.reduce((e,t)=>(e[t[n]]=t,e),{})}function Xn(n){let r={},e=[];for(let t of n)r[t.id]||(r[t.id]=!0,e.push(t));return e}function Zn(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Er(n){return Object.keys(n).filter(r=>n[r]!==void 0).map(r=>[r,n[r]]).reduce((r,e)=>(r[e[0]]=Zn(e[1])?Er(e[1]):e[1],r),{})}function es(n){let r=[];for(let e of n)e.forEach(t=>r.push(t));return r}function ts(n){return c(this,null,function*(){let r=[];return RTCRtpReceiver.prototype.getStats?(r.push(...n.getReceivers().map(e=>e.getStats())),r.push(...n.getSenders().map(e=>e.getStats()))):r.push(n.getStats()),Promise.all(r).then(es).then(Xn)})}function is(n){let r=n.filter(it("type","candidate-pair")).sort(Qn("priority")).find(Aa(it("nominated",!0),it("selected",!0)));if(!r)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let e={totalRoundTripTime:r.totalRoundTripTime||0,currentRoundTripTime:r.currentRoundTripTime||0,bytesSent:r.bytesSent,bytesReceived:r.bytesReceived},t=n.find(it("id",r.remoteCandidateId));t&&(e=Object.assign({},e,{remote:{type:t.candidateType,address:t.ip||t.address,port:t.port,protocol:t.protocol}}));let i=n.find(it("id",r.localCandidateId));return i&&(e=Object.assign({},e,{local:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol,relayProtocol:i.relayProtocol,networkType:i.networkType}})),Er(e)}function rs(n,r){let e=bi("id",n),t=n.filter(Aa(it("type","inbound-rtp"),it("type","outbound-rtp")));C.browserName()==="Firefox"&&(t=Object.values(t.reduce((a,s)=>{if(!a[s.ssrc])a[s.ssrc]=s;else{let o=Object.assign({},a[s.ssrc],s),p=a[s.ssrc].isRemote?s:a[s.ssrc];o.id=p.id,o.type=p.type,delete o.isRemote,delete o.remoteId,a[o.ssrc]=o}return a},{})));let i={};if(C.browserName()==="Safari"){let a=n.filter(it("type","track"));i=bi("trackIdentifier",a)}return t.map(a=>{let s=Number(a.ssrc),o=a.mediaType||a.kind,p=a.trackId,u=a.type,h=a.codecId;if(C.browserName()==="Safari"){let b=/^.+_([\d]+)$/.exec(a.id);if(b&&(s=parseInt(b[1],10)),o=a.id.indexOf("Audio")>0?"audio":"video",r[s]){let D=o+"-"+r[s];i[D]&&(p=i[D].id)}}if(!u||!s||!o)return null;let I={ssrc:s,type:u,kind:o,bytesReceived:ue(a,"bytesReceived"),bytesSent:ue(a,"bytesSent"),jitter:ue(a,"jitter"),packetsLost:ue(a,"packetsLost"),packetsReceived:ue(a,"packetsReceived"),packetsSent:ue(a,"packetsSent"),fractionLost:ue(a,"fractionLost"),pliCount:ue(a,"pliCount"),firCount:ue(a,"firCount"),nackCount:ue(a,"nackCount"),userId:r[s]};if(o==="video"){let b=ue(a,"framesDecoded"),D=ue(a,"totalInterFrameDelay"),A=ue(a,"totalSquaredInterFrameDelay");I.interframeDelayVariance=(A-D*D/b)/b}if(o==="audio"&&(I.totalSamplesReceived=ue(a,"totalSamplesReceived"),I.concealedSamples=ue(a,"concealedSamples"),I.insertedSamplesForDeceleration=ue(a,"insertedSamplesForDeceleration"),I.removedSamplesForAcceleration=ue(a,"removedSamplesForAcceleration"),I.silentConcealedSamples=ue(a,"silentConcealedSamples"),I.concealmentEvents=ue(a,"concealmentEvents"),I.totalAudioEnergy=ue(a,"totalAudioEnergy")),h&&e[h]){let b=e[h];I.clockRate=b.clockRate,I.mimeType=b.mimeType}if(p&&e[p]){let b=e[p];I.frameHeight=b.frameHeight,I.frameWidth=b.frameWidth,I.framesDecoded=b.framesDecoded,I.framesReceived=b.framesReceived,I.framesDropped=b.framesDropped}return Er(I)}).filter(a=>!!a)}function as(n,r){if(!r||!r.rtps||!n.rtps)return n;let e=bi("ssrc",n.rtps),t=bi("ssrc",r.rtps),i=(n.timestamp-r.timestamp)/1e3;return!e||!t||Object.keys(e).forEach(a=>{let s=e[a],o=t[a];if(!(!s||!o)){if(s.bytesReceived&&s.bytesReceived>o.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-o.bytesReceived)/i)),s.bytesSent&&s.bytesSent>o.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-o.bytesSent)/i)),s.packetsReceived)if(s.packetsReceived>o.packetsReceived||s.packetsLost>o.packetsLost){let p=s.packetsLost-o.packetsLost,u=s.packetsReceived-o.packetsReceived;s.packetLoss=parseFloat((100*p/(p+u)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&o.framesDropped&&s.framesDropped>o.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-o.framesDropped)/i).toFixed(0)))}}),n}function Xt(t,i){return c(this,arguments,function*(n,r,e={}){let a=yield ts(n),s={timestamp:Date.now(),transport:is(a),rtps:rs(a,e)};return r?as(s,r):(yield E.delay(Yn),Xt(n,s,e))})}var Mi=.8,rt=class extends re{constructor(e,t,i,a,s,o={}){super();this._remoteSDP={};this._remoteCandidates={};this._state="IDLE";this._animojiDataChannel=null;this._animojiReceiver=null;this._animojiSender=null;this._animojiSvgDataByParticipantId={};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=a,this._participantId=e,this._isMaster=t,this._serverSettings=s,this._animojiSvgDataByParticipantId=o,this._perfStatReporter=new tt(this,i,!0),this.subscribe(this._signaling,Ie.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,"TRACK_REPLACED",this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,"SOURCE_CHANGED",this._applySettings.bind(this)),this.subscribe(this._mediaSource,"ANIMOJI_STATUS",this._onAnimojiStatus.bind(this)),this._pc=new RTCPeerConnection({iceServers:l.iceServers,iceTransportPolicy:l.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={},l.useVmoji&&this._createDataChannel(this._pc,ze.animoji,p=>{this._animojiDataChannel=p,this._animojiDataChannel.binaryType="arraybuffer",this._createAnimojiReceiver(),this._mediaSource.isAnimojiRequested&&this._createAnimojiSender()}),this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,l.p2pAudioRed),this._applySettings()}catch(p){S.log(T.ERROR,"addTrack-direct"),d.error("Unable to add media source tracks",p,{participantId:this._participantId}),this._failedOnCreate=p;return}this._createOffer(!1).catch(p=>{this._state==="IDLE"?this._failedOnCreate=p:this.close(p)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!=="IDLE"&&e!=="CLOSED"&&e!=="FAILED"&&this._startStatInterval()}open(e=null){return c(this,null,function*(){if(this._isOpen){d.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(d.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,l.p2pAudioRed),this._applySettings()}catch(i){S.log(T.ERROR,"addTrack-direct"),d.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState("OPENED");let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={}})}updateSettings(e){yi(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._removeAnimojiReceiver(),this._removeAnimojiSender(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent("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?(d.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState("FAILED")):(d.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState("CLOSED")),this._triggerEvent("PEER_CONNECTION_CLOSED")}setAnimojiSvg(e,t){var i;(i=this._animojiReceiver)==null||i.setParticipantSvg(e,t)}_setState(e){this._state!==e&&(d.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent("STATE_CHANGED",e))}_onSignalingNotification(e){var t,i,a,s;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=((a=e.data.sdk)==null?void 0:a.rtt)||0,this._remoteNetworkStat.loss=((s=e.data.sdk)==null?void 0:s.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=E.getPeerIdString(e.peerId);E.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){d.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw S.log(T.ERROR,"addIceCandidate-direct"),d.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else d.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return c(this,null,function*(){if(!this._remoteCandidates[e]){d.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(a){}})}_setRemoteDescription(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){d.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 S.log(T.ERROR,"setRemoteDescription-direct"),d.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){d.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("REMOTE_TRACK_REMOVED",this._remoteStream,t.track)}),this._triggerEvent("REMOTE_TRACK_ADDED",this._remoteStream,e.track)}_handleIceCandidate(e){return c(this,null,function*(){e.candidate&&this._signaling.ready&&(d.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(d.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>c(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(d.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e==="IDLE"||e==="OPENED"?this._setState("CONNECTING"):this._setState("RECONNECTING");break}}_onConnectionStateChange(){switch(d.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),S.log(T.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState("CONNECTED"),this._stopReconnection(),E.getPeerConnectionHostInfo(this._pc).then(e=>{e&&S.log(T.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState("RECONNECTING"),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(d.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},l.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(d.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology("SERVER"))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(S.log(T.ICE_RESTART),d.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):d.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,d.error("Ice restart failed",{participantId:this._participantId}),S.log(T.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},l.iceRestartWaitTime)}_createOffer(e){return c(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return d.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw d.error("Unable to create offer",i,{participantId:this._participantId}),S.log(T.ERROR,"createOffer-direct"),i}).then(i=>c(this,null,function*(){return d.debug("Created offer",{participantId:this._participantId,offer:i}),i=rt._patchDescription(i),d.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw d.error("Unable to set local description",i,{participantId:this._participantId}),S.log(T.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return c(this,null,function*(){return d.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw d.error("Unable to create answer",e,{participantId:this._participantId}),S.log(T.ERROR,"createAnswer-direct"),e}).then(e=>c(this,null,function*(){return d.debug("Created answer",{participantId:this._participantId,answer:e}),e=rt._patchDescription(e),d.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw d.error("Unable to set local description",e,{participantId:this._participantId}),S.log(T.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!C.baseChromeVersion();return e.sdp=E.patchLocalSDP(e.sdp,l.preferH264&&C.canPreferH264(),C.isBrokenH264(),l.preferVP9,l.h264spsPpsIdrInKeyframe,t&&l.audioNack,l.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&t.track.contentHint===e.contentHint&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{d.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),S.log(T.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_onAnimojiStatus(e){e?this._createAnimojiSender():this._removeAnimojiSender(),this._mediaSource.onAnimojiSender(e)}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Xt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:"DIRECT",transport:t.transport,rtps:t.rtps.filter(a=>a.type==="inbound-rtp"?(a.userId=this._participantId,!0):!1)},outbound:{topology:"DIRECT",transport:t.transport,rtps:t.rtps.filter(a=>a.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent("REMOTE_DATA_STATS",i),this._statInterval=window.setTimeout(e,l.statisticsInterval)})};this._statInterval=window.setTimeout(e,l.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=W=>W.rtt<=this._networkLimits.goodNet.rtt&&W.loss<=this._networkLimits.goodNet.loss,i=W=>W.rtt>=this._networkLimits.badNet.rtt||W.loss>=this._networkLimits.badNet.loss,a=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,s=e.inbound.rtps.reduce((W,te)=>Math.max(W,te.packetLoss||0),0),o={rtt:this._lastNetworkStat.rtt*(1-Mi)+a*Mi,loss:this._lastNetworkStat.loss*(1-Mi)+s*Mi},p=i(o),u=t(o),h=i(this._remoteNetworkStat),I=t(this._remoteNetworkStat),b=i(this._lastNetworkStat),D=t(this._lastNetworkStat),H=p||h?.2:u&&I?1:0,fe=Date.now();if((b!==p||D!==u||fe-this._lastNetworkStat.date>l.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},o)},null).catch(W=>{d.warn("Unable to send [bad-net]",W)})),H){let W={};W[this._participantId]=W[""]=H,this._triggerEvent("NETWORK_STATUS",W)}this._lastNetworkStat.rtt=o.rtt,this._lastNetworkStat.loss=o.loss}_startSettingsInterval(){if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,2e3)};this._settingsInterval=window.setTimeout(t,2e3)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=E.sdpFingerprint(e);if(t===null){d.warn("Fingerprint calculation is unsupported");return}this._fingerprint===null?this._fingerprint=t:(g.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=E.applySettings(this._pc,e,this._prevConsumerSettings)),this._animojiSender){let i=this._mediaSource.getStream();i&&this._animojiSender.setStream(i)}}_createDataChannel(e,t,i){d.debug(`[${t}] data channel opening`);let a=e.createDataChannel(t,{negotiated:!0,id:1});a.onopen=()=>{let s=a.readyState;s==="open"?(d.debug(`[${t}] data channel opened`),a.onerror=o=>{d.error(`[${t}] data channel error`,o)},i(a)):d.error(`[${t}] data channel open failed, state [${s}]`)}}_createAnimojiReceiver(){!l.useVmoji||!this._animojiDataChannel||!this._participantId||(this._animojiReceiver&&this._removeAnimojiReceiver(),this._animojiReceiver=new l.vmoji.AnimojiReceiver(this._animojiDataChannel,this._participantId,(e,t)=>{this._triggerEvent("ANIMOJI_STREAM",e,t)},e=>{this._triggerEvent("ANIMOJI_STREAM",e,null)}),Object.entries(this._animojiSvgDataByParticipantId).forEach(([e,t])=>{this._animojiReceiver.setParticipantSvg(e,t)}))}_removeAnimojiReceiver(){var e;(e=this._animojiReceiver)==null||e.destroy(),this._animojiReceiver=null}_createAnimojiSender(){if(!l.useVmoji||!this._animojiDataChannel)return;let e=this._mediaSource.getStream();e&&(this._animojiSender&&this._removeAnimojiSender(),this._animojiSender=new l.vmoji.AnimojiSender(this._animojiDataChannel,e))}_removeAnimojiSender(){var e;(e=this._animojiSender)==null||e.destroy(),this._animojiSender=null}};var ns=16,xt=class{constructor(r,e,t){d.debug("AsrReceiver started"),this._datachannel=r,this._participantIdRegistry=e,this._asrCallback=t,this._textDecoder=new TextDecoder,this._datachannel.onmessage=i=>this._onDataChannelMessage(i.data)}static parse(r){let e=new DataView(r),t=e.getUint8(0),i=e.getUint8(1);if(i!==0)throw new Error(`Unsupported message type. Message type: ${i}`);let a=e.getUint16(2),s=e.getUint32(4),o=e.getUint32(8),p=e.getUint32(12);if(t!==1)throw new Error(`Unexpected protocol version. Got ${t}, expected 1`);return{sequence:a,ssrc:s,timestamp:o,duration:p,data:r.slice(ns)}}_onDataChannelMessage(r){var a,s;let e=xt.parse(r),t=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(e.ssrc))==null?void 0:s.participantId;if(!t){d.warn(`Participant id for ssrc ${e.ssrc} not found in registry`);return}let i={participantId:t,text:this._textDecoder.decode(e.data),timestamp:e.timestamp,duration:e.duration};this._asrCallback(i)}destroy(){this._datachannel.onmessage=null}};var nt=require("messagepack");var Ai=class{constructor(){this.streamDescriptionByCompactId=new Map;this.compactIdByStreamDescription=new Map}getStreamDescription(r){return this.streamDescriptionByCompactId.get(r)}getCompactId(r){return this.compactIdByStreamDescription.get(r)}handleMessage(r){var a,s;let e=new Uint8Array(r),t=e[0],i=e.subarray(1);switch(t){case 1:let o=(0,nt.decode)(i);return Object.entries(o).forEach(([A,Y])=>{let H=Jt(A);this.streamDescriptionByCompactId.set(Y,H),this.compactIdByStreamDescription.set(A,Y)}),null;case 2:case 4:let p=(0,nt.decode)(i),u=[];for(let A of p){let Y=this.getStreamDescription(A);Y&&u.push(Y.participantId)}return t===2?{type:"notification",notification:x.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:x.STALLED_ACTIVITY,stalledParticipants:u};case 3:let h=(0,nt.decode)(i);return{type:"notification",notification:x.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(h))==null?void 0:a.participantId};case 5:let I=(0,nt.decode)(i);return{type:"notification",notification:x.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:I[0],maxDimension:I[1]}};case 6:let b=(0,nt.decode)(i),D={};for(let[A,Y]of Object.entries(b)){let H=(s=this.getStreamDescription(Number(A)))==null?void 0:s.participantId;H&&(D[H]=Y/100)}return{type:"notification",notification:x.NETWORK_STATUS,statuses:D};case 7:return this._createParticipantSourcesUpdateNotification(i);case 8:{let Y=(0,nt.decode)(i).map(H=>{var X;let[fe,W,te,me,ve,st,ai]=H;return{participantId:(X=this.getStreamDescription(fe))==null?void 0:X.participantId,gain:W,pause:te,offset:me,mute:ve,liveStatus:st,startTimeMs:ai}});return{type:"notification",notification:x.MOVIE_UPDATE_NOTIFICATION,data:Y}}default:return d.debug("unsupported message type: "+t),null}}_createParticipantSourcesUpdateNotification(r){let e=(0,nt.decode)(r),t=[];for(let[i,a]of Object.entries(e)){let s=a[0],o=a[1],p=a[2],u;if(s!==null){if(u=this.getStreamDescription(s),!u){d.error(`could not uncompress participant ID ${s}`);continue}}else u=null;if(p===null){d.error("unexpected null sequenceNumber",i,a);continue}let h=xe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+i,I=o?o>>>0:null;t.push({participantStreamDescription:u,streamId:h,rtpTimestamp:I,sequenceNumber:p})}return{type:"notification",notification:x.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:t}}};var ss=90,os=4294967295,Me=class extends re{constructor(e,t,i,a={}){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._asr=null;this._animojiDataChannel=null;this._animojiReceiver=null;this._animojiSender=null;this._animojiSvgDataByParticipantId={};this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state="IDLE";this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._asrTrack=null;this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._newAudioShareTrack=null;this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,Ie.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,"TRACK_REPLACED",this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,"SOURCE_CHANGED",this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,"SCREEN_STATUS",this._onScreenSharingStatus.bind(this)),this.subscribe(this._mediaSource,"ANIMOJI_STATUS",this._onAnimojiStatus.bind(this)),this._perfStatReporter=new tt(this,e),this._serverSettings=i,this._animojiSvgDataByParticipantId=a,d.debug("ServerTransport: Created")}getState(){return this._state||"IDLE"}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!=="IDLE"&&e!=="CLOSED"&&e!=="FAILED"&&this._startStatInterval()}open(e=!1){if(this._isOpen){d.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(d.error("ServerTransport: Closed",e),this._setState("FAILED")):(d.debug("ServerTransport: Closed"),this._setState("CLOSED"))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){yi(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}setAnimojiSvg(e,t){var i;(i=this._animojiReceiver)==null||i.setParticipantSvg(e,t)}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeAsrTrack(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._removeAnimojiReceiver(),this._removeAnimojiSender(),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,Me._closeDataChannel(this._producerNotification),Me._closeDataChannel(this._producerCommand),Me._closeDataChannel(this._producerScreen),Me._closeDataChannel(this._consumerScreen),Me._closeDataChannel(this._asr),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent("PEER_CONNECTION_CLOSED")}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){d.debug(`[${t}] data channel opening`);let a=e.createDataChannel(t,{ordered:!0});a.onopen=()=>{let s=a.readyState;s==="open"?(d.debug(`[${t}] data channel opened`),i(a)):d.error(`[${t}] data channel open failed, state [${s}]`)},a.onerror=s=>{let o=s.error;d.error(`[${t}] data channel error`,o==null?void 0:o.errorDetail,o==null?void 0:o.message)}}_openConnection(e=!1){d.debug("ServerTransport: Open single connection"),this._pc=new RTCPeerConnection({},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=E.throttle(t=>{this._pc&&this._onConnectionStateChange(this._pc,t)},500),this._pc.onsignalingstatechange=Me._onSignalingStateChange.bind(this,this._pc),this._participantIdRegistry=new Ai,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),l.producerNotificationDataChannel&&this._createDataChannel(this._pc,ze.producerNotification,t=>{this._producerNotification=t,this._producerNotification.binaryType="arraybuffer",this._signaling.setProducerNotificationDataChannel(t)}),l.producerCommandDataChannel&&(this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,ze.producerCommand,t=>{this._producerCommand=t,this._signaling.setProducerCommandDataChannel(t)})),l.producerScreenDataChannel&&this._createDataChannel(this._pc,ze.producerScreenShare,t=>{this._producerScreen=t,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()}),l.asrDataChannel&&this._createDataChannel(this._pc,ze.asr,t=>{this._asr=t,this._asr.binaryType="arraybuffer",this._removeAsrTrack(),this._asrTrack=new xt(t,this._participantIdRegistry,i=>{this._onAsrTranscription(i)}),this._signaling.setAsrDataChannel(t)}),l.useVmoji&&this._createDataChannel(this._pc,ze.animoji,t=>{this._animojiDataChannel=t,this._animojiDataChannel.binaryType="arraybuffer",this._createAnimojiReceiver(),this._mediaSource.isAnimojiRequested&&this._createAnimojiSender()}),this._newAudioShareTrack=this._mediaSource.getAudioShareTrack();try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,l.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(t){d.error("ServerTransport: Unable to add media source tracks",t),S.log(T.ERROR,"addTrack-single"),this.close(t);return}l.consumerScreenDataChannel&&this._createDataChannel(this._pc,ze.consumerScreenShare,t=>{this._consumerScreen=t,this._consumerScreen.binaryType="arraybuffer";let i=this._mediaSource.getScreenTrack();i&&this._createCaptureSender(i)}),e||this._allocateConsumer(),this._setState("OPENED"),this._startStatInterval(),this._startSettingsInterval()}_removeAsrTrack(){var e;(e=this._asrTrack)==null||e.destroy(),this._asrTrack=null}_reconnect(){this.getState()!=="OPENED"&&(this._setState("RECONNECTING"),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_signalStalledParticipants(e){this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_signalSpeakerChanged(e){this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_signalNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
+ `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${xe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,a=new RegExp(i).exec(t);a&&(this._ssrcMap[a[1]]=a[3])})}_createCaptureSender(e){let t=this._mediaSource.getMediaSettings();!e||!l.consumerScreenDataChannel||!this._consumerScreen||!t.isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new ft(e,this._consumerScreen,this._signaling,t.isFastScreenSharingEnabled))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!l.producerScreenDataChannel||!this._producerScreen||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new _t(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent("REMOTE_STREAM_SECOND",e,t)},e=>{this._triggerEvent("REMOTE_STREAM_SECOND",e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_createAnimojiSender(){if(!l.useVmoji||!this._animojiDataChannel)return;let e=this._mediaSource.getStream();e&&(this._animojiSender&&this._removeAnimojiSender(),this._animojiSender=new l.vmoji.AnimojiSender(this._animojiDataChannel,e))}_removeAnimojiSender(){var e;(e=this._animojiSender)==null||e.destroy(),this._animojiSender=null}_createAnimojiReceiver(){!l.useVmoji||!this._animojiDataChannel||!this._participantIdRegistry||(this._animojiReceiver&&this._removeAnimojiReceiver(),this._animojiReceiver=new l.vmoji.AnimojiReceiver(this._animojiDataChannel,this._participantIdRegistry,(e,t)=>{this._triggerEvent("ANIMOJI_STREAM",e,t)},e=>{this._triggerEvent("ANIMOJI_STREAM",e,null)}),Object.entries(this._animojiSvgDataByParticipantId).forEach(([e,t])=>{this._animojiReceiver.setParticipantSvg(e,t)}))}_removeAnimojiReceiver(){var e;(e=this._animojiReceiver)==null||e.destroy(),this._animojiReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!l.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 a=!this._disabledSenders.has(i),s=e.maxDimension!==0;if(a&&!s){d.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(C.getBlackMediaTrack()).catch(p=>{d.error("Could not disable video upload",p)});return}let o=this._mediaSource.getSendVideoTrack();if(!a&&s&&o){d.log("Enabling video upload"),this._disabledSenders.delete(i);let p=i.track;p.enabled=o.enabled,i.replaceTrack(o).then(()=>p.stop()).catch(u=>{d.error("Could not enable video upload",u)})}E.applyVideoTrackSettings(e,i,o!=null?o:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}if(this._animojiSender){let t=this._mediaSource.getStream();t&&this._animojiSender.setStream(t)}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_onAnimojiStatus(e){e?this._createAnimojiSender():this._removeAnimojiSender(),this._mediaSource.onAnimojiSender(e)}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent("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,l.statisticsInterval)};this._statInterval=window.setTimeout(e,l.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,2e3)};this._settingsInterval=window.setTimeout(t,2e3)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return c(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Xt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent("REMOTE_DATA_STATS",{inbound:{topology:"SERVER",transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:"SERVER",transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(o=>o.type==="inbound-rtp"&&o.kind==="audio"&&this._ssrcMap[o.ssrc]==="mix");if(!t)return;let i=xe.AUDIO_MIX,a=this._statBytes[i],s=!1;if(a){let o=t.bytesReceived-a.bytesReceived;o>=0&&o<=5&&(s=!0),a.stalled!==s&&this._triggerEvent("REMOTE_ALL_STALL",s)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:s}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:tt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:l.producerNotificationDataChannel?7:0,producerCommandDataChannelVersion:l.producerCommandDataChannel?3:0,consumerScreenDataChannelVersion:l.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:l.producerScreenDataChannel?1:0,asrDataChannelVersion:l.asrDataChannel?1:0,animojiDataChannelVersion:l.useVmoji?1:0,onDemandTracks:!0,unifiedPlan:!0,singleSession:!0,videoTracksCount:l.videoTracksCount,red:l.serverAudioRed,audioShare:l.audioShare,fastScreenShare:l.fastScreenShare};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return c(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,d.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:E.patchRemoteSDP(e)});if(d.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw d.error("[single] unable to set remote offer",i),S.log(T.ERROR,"setRemoteDescription-single"),i}).then(()=>c(this,null,function*(){if(d.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this.handleTracks(),this._pc.createAnswer()})).catch(i=>{throw d.error("[single] unable to create answer",i),S.log(T.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=E.patchLocalSDP(i.sdp,!1,C.isBrokenH264(),!1,l.h264spsPpsIdrInKeyframe),i)).then(i=>c(this,null,function*(){if(d.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw d.error("[single] unable to set local answer",i),S.log(T.ERROR,"setLocalDescription-single"),i}).then(i=>c(this,null,function*(){d.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),d.debug("[single] remote offer has been processed")})).catch(i=>{d.warn("[single] unable to send local answer",i),S.log(T.ERROR,"acceptProducer")}).then(()=>c(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){d.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))})}handleTracks(){this._newAudioShareTrack&&(this._pc.getTransceivers().forEach(e=>{e.mid.endsWith("s")&&(e.sender.track!==null&&d.warn("Unexpected track assigned to audioshare"),e.direction="sendonly",e.sender.replaceTrack(this._newAudioShareTrack).catch(t=>{d.error("ServerTransport: Unable to replace track",t),S.log(T.ERROR,"replaceTrack-single")}),this._newAudioShareTrack=null)}),this._newAudioShareTrack&&d.warn("Cannot find audioshare transceiver"))}_onSignalingNotification(e){return c(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}})}_onAsrTranscription(e){this._triggerEvent("ASR_TRANSCRIPTION",e)}_onProducerUpdated(e){return c(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),l.breakVideoPayloadTypes&&(d.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes",null)),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){d.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=s=>{this._triggerEvent("REMOTE_TRACK_REMOVED",i.id,i,s.track)}),i.getTracks().find(s=>s.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent("REMOTE_TRACK_ADDED",i.id,i,t.track)):d.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){d.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(d.debug("[single] connection state changed",{state:e.connectionState},t),S.log(T.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==="IDLE"||i==="OPENED"?this._setState("CONNECTING"):e.iceConnectionState==="checking"&&this._setState("RECONNECTING");break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState("RECONNECTING");break;case"connected":this._setState("CONNECTED"),E.getPeerConnectionHostInfo(e).then(a=>{a&&S.log(T.ICE_CONNECTION_TYPE,a.type)});break}}_onReplacedTrack(e,t){if(this._pc){l.consumerScreenDataChannel&&t&&(e=t);let i=!1;this._pc.getSenders().forEach(a=>{a.track&&a.track.kind===e.kind&&!this._disabledSenders.has(a)&&a.track.contentHint===e.contentHint&&(a.track.enabled=e.enabled,a.replaceTrack(e).catch(s=>{d.error("ServerTransport: Unable to replace track",s),S.log(T.ERROR,"replaceTrack-single")}),i=!0)}),!i&&e.kind==="audio"&&e.contentHint==="music"&&(this._newAudioShareTrack=e)}this._applyConsumerSettings()}getStreamWaitingTimeMs(e,t){if(!this._pc)return S.log(T.PAT_WAITING_TIME_ERROR,"noConnection"),d.error("Cannot get stream waiting time, peer connection is not initialized"),0;if(!RTCRtpReceiver.prototype.getSynchronizationSources)return S.log(T.PAT_WAITING_TIME_ERROR,"oldBrowser"),d.error("Cannot get stream waiting time, RTCRtpReceiver.getSynchronizationSources is not supported"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return S.log(T.PAT_WAITING_TIME_ERROR,"noReceiver"),d.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let a=i.getSynchronizationSources();if(!a||!a.length)return d.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let o=a[0].rtpTimestamp;if(!Number.isInteger(o))return S.log(T.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),d.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${o}`),0;let p=t-o&os,u=Math.ceil(p/ss);return Math.min(100,Math.max(0,u))}};var at=(e=>(e.DIRECT="DIRECT",e.SERVER="SERVER",e))(at||{}),Di=class extends re{constructor(e,t,i,a){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._animojiSvgDataByParticipantId={};this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=a,this.subscribe(this._signaling,Ie.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){d.log("Update transport settings",e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(d.log(`Trying allocate participant [${e}]`),this._allocated.indexOf(e)!==-1){d.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,i=!1,a=!1){d.log("Trying open participant",{participantIds:e});let s=a;for(let o of e){if(this._opened.indexOf(o)!==-1){d.warn(`The participant [${o}] has already had opened transport`);continue}if(this._allocated.indexOf(o)===-1){d.warn(`The participant [${o}] has no allocated transport`);continue}this._opened.push(o),s=!0}s&&(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),d.debug("The transport has been opened",e))}close(e){var a;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&d.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((a=this._serverTransport)==null||a.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}getState(){var e,t;return this._topology==="SERVER"?(e=this._serverTransport)==null?void 0:e.getState():(t=this._directTransport)==null?void 0:t.getState()}setAnimojiSvg(e,t){this._animojiSvgDataByParticipantId[e]=t,(!(t.svg instanceof ArrayBuffer)||t.svg.byteLength!==0)&&(this._topology==="DIRECT"&&this._directTransport?this._directTransport.setAnimojiSvg(e,t):this._topology==="SERVER"&&this._serverTransport&&this._serverTransport.setAnimojiSvg(e,t))}_setStates(e,t){let i=e.filter(a=>this._states[a]!==t?(this._states[a]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===x.TOPOLOGY_CHANGED)return this._onTopologyChanged(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(d.log(`Topology changed ${this._topology} -> ${e.topology}`),S.log(T.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],a=e.offerToTypes||[],s=e.offerToDeviceIdxs||[],o=i.length&&a.length?E.composeParticipantId(i[0],a[0],s[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){d.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&d.warn("Topology changed to DIRECT, but the allocated participants count more then one");let p=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let u=o===p;this._directTransport=this._createDirectTransport(p,u)}this._opened.indexOf(p)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_createDirectTransport(e,t=!1){let i=new rt(e,t,this._signaling,this._mediaSource,this._serverSettings,this._animojiSvgDataByParticipantId);return this._dtListeners&&this._dtListeners.length>0&&d.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT")),i.addEventListener("ANIMOJI_STREAM",this._onAnimojiStream.bind(this))),i}_createServerTransport(){let e=new Me(this._signaling,this._mediaSource,this._serverSettings,this._animojiSvgDataByParticipantId);return this._stListeners&&this._stListeners.length>0&&d.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER")),e.addEventListener("ASR_TRANSCRIPTION",this._onAsrTranscription.bind(this)),e.addEventListener("ANIMOJI_STREAM",this._onAnimojiStream.bind(this))),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;l.noiseSuppression!==e&&(l.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let a=this._allocated.indexOf(e);a>=0&&this._allocated.splice(a,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onAsrTranscription(e){this._triggerEvent("ASR_TRANSCRIPTION",e)}_onAnimojiStream(e,t){this._triggerEvent("ANIMOJI_STREAM",e,t)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(S.log(T.PAT_WAITING_TIME_ERROR,"wrongTopology"),d.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(S.log(T.PAT_WAITING_TIME_ERROR,"noTransport"),d.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var ki=class extends re{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,"REMOTE_TRACK_ADDED",this._onRemoteTrackAdded.bind(this)),this.subscribe(e,"REMOTE_TRACK_REMOVED",this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,"SIGNALLED_ACTIVE_PARTICIPANTS",this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,"TOPOLOGY_CHANGED",this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var a;if(i.kind==="audio"&&((a=this._detector)==null||a.destroy(),this._detector=new Ot(e,t),!this._interval)){let s=()=>{this._collectVolumes(),this._interval=window.setTimeout(s,l.voiceParams.interval)};this._interval=window.setTimeout(s,l.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===xe.AUDIO_MIX){if(this._activeParticipants)for(let a of this._activeParticipants)e[a]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e==="DIRECT"&&(this._activeParticipants=null)}};var Oi=class extends re{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i==="SERVER",this.subscribe(e,"VOLUMES_DETECTED",this._onVolumesDetected.bind(this)),this.subscribe(t,"SIGNALLED_SPEAKER_CHANGED",this._onServerSpeakerChanged.bind(this)),this.subscribe(t,"TOPOLOGY_CHANGED",this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(a=>{let s=e[a].smoothed;s>t&&s>l.voiceParams.threshold&&(t=s,i=a)}),i&&i!==this._speakerId){let a=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>a*l.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent("SPEAKER_CHANGED",e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e==="SERVER"}};var Zt=class extends re{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,"STATE_CHANGED",this._onTransportStateChanged.bind(this)),this.subscribe(t,"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==="OPENED"&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),l.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),l.specListenerParams.volumeTimeout))),t==="FAILED"&&this._connectionTimeout&&(d.warn("Transport failed, send callSpecError"),S.log(T.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!=="CONNECTED";(()=>Object.values(this._states).filter(e).length>0)()&&(d.warn("There is not connected transport, send callSpecError"),S.log(T.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",a=this._participants[t];a&&a.platform&&(i=a.platform),e.indexOf(i)<0&&(e.push(i),S.log(T.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&d.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var cs=1e3,ds=1e4;var ls=15,K=class extends re{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._myLastRequestedLayouts={};this._state="IDLE";this._participantState=$.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;S.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),S.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new zt,l.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),cs))}static current(){return K._current}static hangupAfterInit(){K._activationMutex&&!K._current&&(K._delayedHangup=!0)}static id(){var e,t;return((t=(e=K._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,a="",s=!1,o=!1,p){return c(this,null,function*(){if(K._activationMutex)throw S.log(T.ERROR,"startCall"),d.warn("Conversation: there is already running activation"),new V(w.FAILED);K._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let u=this._mediaSource.getMediaSettings();t===Ve.CHAT||e.length>1?this._logWithMediaSettings(T.OUTGOING_MULTIPARTY_CALL,u):this._logWithMediaSettings(T.OUTGOING_CALL,u);let h=yield this._startConversation(e,t,$e.OUTGOING,i,a,s,o,p);if(!this._conversation)throw new V(w.UNKNOWN_ERROR);if(this._participantState=$.ACCEPTED,this._signaling.changeMediaSettings(u),yield this._processConnection(h),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),K._delayedHangup)throw new V(w.CANCELED);d.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let I=Object.values(this._participants),b;return l.batchParticipantsOnStart&&(b=E.mapSharedParticipants(I)),yield this._processConnectionSharedMovieInfo(h),g.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),b),this._onConversationParticipantListChunk(h),g.onLocalStatus("WAITING"),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),K._current=this,this._conversation.concurrent?yield this._acceptConcurrent():l.batchParticipantsOnStart||this._setParticipantsStatus(I,"WAITING"),this._conversation}catch(u){throw this._close(u,"Unable to start conversation"),u}finally{K._activationMutex=!1}})}onJoin(e){return c(this,null,function*(){var t;if(K._activationMutex)throw S.log(T.ERROR,"joinCall"),d.warn("Conversation: there is already running activation"),new V(w.FAILED);K._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)!=null&&t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let a=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.JOIN_CONVERSATION,a);let s=yield this._joinConversation(e);if(!this._conversation)throw new V(w.UNKNOWN_ERROR);return this._conversation.observer=i,g.onLocalStream(this._mediaSource.getStream(),a),this._conversation.waitingHall?(d.log("In waiting hall"),K._current=this,K._activationMutex=!1,this._signaling.readyToSend(),g.onLocalStatus("WAITING_HALL"),this._conversation):this._onJoinPart2(s)}catch(i){throw K._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return c(this,null,function*(){var t,i,a,s,o,p,u;d.debug("Join conversation part 2"),K._activationMutex=!0;try{if(this._participantState=$.ACCEPTED,!this._conversation||!this._mediaSource)throw new V(w.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._processConnection(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),K._delayedHangup)throw new V(w.CANCELED);let h=Object.values(this._participants),I;l.batchParticipantsOnStart&&(I=E.mapSharedParticipants(h.filter(A=>!A.isInRoom)));let b=[];if((i=(t=e==null?void 0:e.rooms)==null?void 0:t.rooms)!=null&&i.length)for(let A of e.rooms.rooms)b.push({id:A.id,name:A.name,participantCount:A.participantCount,participantIds:yield Promise.all(((s=(a=A==null?void 0:A.participantIds)==null?void 0:a.map)==null?void 0:s.call(a,this._getExternalIdByParticipantId.bind(this)))||[]),participants:(o=A==null?void 0:A.participants)!=null&&o.participants?this._participantListChunkToExternalChunk(A.participants):void 0,active:A.active,muteStates:A.muteStates});let D=(u=(p=e==null?void 0:e.rooms)==null?void 0:p.roomId)!=null?u:null;return yield this._processConnectionSharedMovieInfo(e),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),I,{rooms:b,roomId:D}),this._onConversationParticipantListChunk(e),g.onLocalStatus("WAITING"),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),K._current=this,l.batchParticipantsOnStart||this._setParticipantsStatus(h,"WAITING"),this._openTransport(h,!1),this._conversation}catch(h){throw this._close(h,"Unable to join conversation"),h}finally{K._activationMutex=!1}})}onPush(a){return c(this,arguments,function*(e,t=z.USER,i){if(K._activationMutex)throw d.warn("Conversation: there is already running activation"),new V(w.REJECTED);K._activationMutex=!0;try{let s=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new V(w.UNKNOWN_ERROR);if(!s.conversation.participants.find(p=>{var u;return p.state===$.CALLED&&p.id===((u=this._conversation)==null?void 0:u.userId)}))throw d.log("Push rejected (there is an active call)"),S.log(T.PUSH,"rejected"),new V(w.REJECTED);if(yield this._processConnection(s),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),S.log(T.PUSH,"accepted"),K._current=this,K._delayedHangup)throw new V(w.CANCELED);K._activationMutex=!1}catch(s){throw K._activationMutex=!1,this._close(s,"Unable to handle inbound call push"),s}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(ci.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>E.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return c(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new V(w.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.ACCEPT_CONCURRENT,e),d.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),g.onCallAccepted(),this._state="ACTIVE",this._participantState=$.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return c(this,null,function*(){var t;if(this._state!=="IDLE")throw S.log(T.ERROR,"acceptIncoming"),d.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new V(w.UNKNOWN_ERROR);this._state="PROCESSING",d.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let i=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.ACCEPT_INCOMING,i),this._signaling.changeMediaSettings(i),yield this._signaling.acceptCall(i),this._participantState=$.ACCEPTED;let a=Object.values(this._participants),s;if(l.batchParticipantsOnStart&&(s=E.mapSharedParticipants(a)),g.onCallAccepted(),g.onLocalStream(this._mediaSource.getStream(),i),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),s),l.useParticipantListChunk){let u=yield this._getInitialParticiapntListChunk();(t=u==null?void 0:u.participants)==null||t.forEach(h=>{let I=E.composeId(h),b=this._participants[I];b&&(b.movieShareInfos=h.movieShareInfos)}),this._onConversationParticipantListChunk({participants:u})}g.onLocalStatus("WAITING"),this._toggleJoinAvailability(),this._changeNeedRate();let o=Dt(this._getMuteStatesForCurrentRoom(),ye.MUTE),p=Dt(this._getMuteStatesForCurrentRoom(),ye.MUTE_PERMANENT);for(let u of[o,p])u.length&&(yield this._processMuteState({mediaOptions:u,stateUpdated:!0}));return this._state="ACTIVE",this._changeFeatureSet(),l.batchParticipantsOnStart||this._setParticipantsStatus(a,"WAITING"),this._openTransport(a,!0),this._conversation}catch(i){throw this._close(i,"Unable to accept call"),i}})}decline(){return c(this,null,function*(){var e;if(this._state!=="IDLE")throw S.log(T.ERROR,"declineIncoming"),d.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",d.debug("Decline incoming call"),this._logWithMediaSettings(T.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=$.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(w.REJECTED)),this._close(new V(w.REJECTED))})}hangup(){return c(this,null,function*(){d.debug("Hangup");let e=this._state==="ACTIVE"?w.HUNGUP:w.CANCELED;S.log(T.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new V(e))):g.onHangup(new V(w.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return c(this,null,function*(){if(!this._signaling.ready){this._close(new V(w.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),a=null;i.type==="error"&&(i.error==="call-unfeasible"?a=i.status:a=w.UNKNOWN_ERROR);let s=i.participant;yield this._onAddParticipant(E.composeId(s),s,a)})}removeParticipant(e,t=!1){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var a;if(!this._transport)return;let i=[];for(let s of e)(s.state===$.CALLED||s.state===$.ACCEPTED)&&(this._transport.isAllocated(s.id)||this._transport.allocate(s.id,t)),s.state===$.ACCEPTED&&i.push(s.id);i.length&&this._transport.open(i,null,!!((a=this._conversation)!=null&&a.observer))}_close(e,t){t&&d.error(t,e),d.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(w.FAILED):S.log(T.ERROR,e.hangup),K._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([w.CANCELED,w.NOT_FRIENDS,w.CALLEE_IS_OFFLINE,w.CALLER_IS_BLOCKED,w.CALLER_IS_REJECTED].indexOf(e.hangup)!==-1||e.hangup===w.REJECTED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===w.HUNGUP&&(!e.remote||this._participantState===$.CALLED)){g.onHangup(e,i),this.destroy();return}if(e.hangup===w.MISSED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===w.SOCKET_CLOSED&&K._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===w.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=$.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),S.destroy(),this._conversation=null,this._myLastRequestedLayouts={},K._current=null,K._delayedHangup=!1,g.onHangup(e||new V(w.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;d.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),S.destroy(),this._conversation=null,this._myLastRequestedLayouts={},K._current=null,K._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return c(this,null,function*(){let t=yield this._api.getConversationParams(e);d.debug("Api.getConversationParams",t);let i=[],{turn_server:a,stun_server:s}=t;if(s&&i.push(s),a){let o=a.urls.filter((p,u,h)=>h.indexOf(p)===u);o.push(`${o[o.length-1]}?transport=tcp`),i.push({urls:o,username:a.username,credential:a.credential})}return l.iceServers=i,l.wssBase=t.endpoint,l.wssToken=t.token,t.client_type&&(l.clientType=t.client_type),l.externalUserType=t.external_user_type,t})}_addGeoParamsToEndpoint(e,t){return t.isp_as_no&&(e+=`&ispAsNo=${t.isp_as_no}`),t.isp_as_org&&(e+=`&ispAsOrg=${t.isp_as_org}`),t.loc_cc&&(e+=`&locCc=${t.loc_cc}`),t.loc_reg&&(e+=`&locReg=${t.loc_reg}`),e}_startConversation(e,t,i,a,s="",o=!1,p=!1,u){return c(this,null,function*(){let h=E.uuid();d.debug("Conversation: start",{conversationId:h,opponentIds:e,opponentType:t,direction:i});let I=a.includes(ce.VIDEO),b=yield this._api.startConversation(h,e,t,I,s,o,p,{onlyAdminCanShareMovie:u});d.debug("Api.startConversation",b);let D=yield this._getConversationParams(b.id);b.endpoint=this._addGeoParamsToEndpoint(b.endpoint,D);let A=yield this._connectSignaling(Fe.START,b);return yield this._setConversation(b,A,i),A})}_joinConversation(e){return c(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:a,joinLink:s,observedIds:o,payload:p}=e;d.debug("Conversation: join",{conversationId:t,joinLink:s,observedIds:o});let u=i.includes(ce.VIDEO),h;if(t)h=yield this._api.joinConversation(t,u,a);else if(s)h=yield this._api.joinConversationByLink(s,u,o,p);else throw new V(w.UNKNOWN_ERROR);d.debug("Api.joinConversation",h),yield this._getConversationParams(h.id);let I=yield this._connectSignaling(Fe.JOIN,h);return yield this._setConversation(h,I,$e.JOINING),I})}_prepareConversation(a){return c(this,arguments,function*(e,t=z.USER,i){d.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let s=this._api.getUserId();if(!s)throw new V(w.UNKNOWN_ERROR);let o=yield this._getConversationParams(e),p=o.device_idx||0,u=`${l.wssBase}?userId=${s}&entityType=${t}&deviceIdx=${p}&conversationId=${e}&token=${l.wssToken}`;u=this._addGeoParamsToEndpoint(u,o);let h={id:e,peerId:i,endpoint:u,is_concurrent:!1,p2p_forbidden:!1,device_idx:p},I=yield this._connectSignaling(Fe.ACCEPT,h);return K._current&&(K._current._participantState===$.ACCEPTED||K._current._participantState===$.CALLED)?(d.log("Push rejected (busy)"),S.log(T.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(w.BUSY),Promise.reject({hangup:w.BUSY})):(K._current&&(K._current.destroy(),K._current=null),yield this._setConversation(h,I,$e.INCOMING,t),I)})}_createParticipant(e){return c(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:ge(),participantState:{},state:$.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[],isInRoom:!1},e);if(e.externalId){let a=E.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(a,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return(i=t.observedIds)!=null&&i.length&&(t.externalId.observer=!0),this._setParticipantMarkers(t,t.markers),t})}_getParticipantId(e){return c(this,null,function*(){try{let t=E.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new V(w.NETWORK_ERROR),t),t}})}_setConversation(s,o,p){return c(this,arguments,function*(e,t,i,a=z.USER){yield this._prepareParticipants(t.conversation.participants);let u=this._api.getUserId(),h=e.device_idx||0;if(!u){let D=(t.conversation.participants||[]).find(A=>E.comparePeerId(A.peerId,t.peerId));if(!D)throw new V(w.UNKNOWN_ERROR);u=Number(D.id),D.idType&&(a=D.idType),D.deviceIdx&&(h=D.deviceIdx),this._api.setUserId(u)}let I=E.composeParticipantId(u,a,h),b=yield this._getParticipantId(I);this._conversation={userId:u,compositeUserId:I,externalId:b,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],featuresPerRole:t.conversation.featuresPerRole,id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||"DIRECT",direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordsInfoByRoom:new Map,muteStates:new Map,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1,asrInfo:null,roomId:null},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(l.forceRelayPolicy=e.p2p_forbidden),S.log(T.RELAY_POLICY,l.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new V(w.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.featuresPerRole=e.conversation.featuresPerRole,this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||"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 mi;return this.subscribe(e,"SOURCE_CHANGED",this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,"SCREEN_STATUS",this._onScreenSharingStatus.bind(this)),this._audioFix=new kt(e),e}_connectSignaling(e,t){return c(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,Ie.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,Ie.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,Ie.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_processConnection(e){return c(this,null,function*(){yield this._registerConnectionParticipants(e),this._processConnectionData(e)})}_prepareParticipants(e){return c(this,null,function*(){let t=e.map(i=>i.id);t.length&&(yield this._api.prepareUserIds(t))})}_onConversationParticipantListChunk(e){let t=e.participants;t&&g.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(this._createParticipantListChunk(t)))}_createParticipantListChunk(e){return Ce(Ce({},{participants:[],countBefore:0,countAfter:0,markerFound:!1}),e)}_participantListChunkToExternalChunk(e){let t=E.mapSharedParticipants(e.participants.map(i=>{let a=E.composeId(i);return this._participants[a]}));return Ye(Ce({},e),{participants:t})}_registerConnectionParticipants(e){return c(this,null,function*(){var i,a,s,o,p,u;yield this._registerParticipants(e.conversation.participants),(i=e.participants)!=null&&i.participants&&(yield this._registerParticipants((a=e.participants)==null?void 0:a.participants));let t=(o=(s=e==null?void 0:e.rooms)==null?void 0:s.rooms)!=null?o:[];for(let h of t)yield this._registerParticipants((u=(p=h==null?void 0:h.participants)==null?void 0:p.participants)!=null?u:[],!0)})}_registerParticipants(e,t=!1){return c(this,null,function*(){if(this._conversation)for(let i of e){let a=E.composeId(i);if(this._isMe(a)){this._conversation.roles=i.roles||[],this._conversation.roles.length&&(d.debug(`Local roles changed: ${i.roles}`),g.onLocalRolesChanged(this._conversation.roles)),yield this._registerParticipantLocalMuteState(i);continue}if(i.state===$.HUNGUP||i.state===$.REJECTED){this._participants[i.id]&&this._removeParticipant(this._participants[i.id],w.HUNGUP);continue}this._registerParticipantInCache(yield this._createParticipant({id:a,externalId:i.externalId&&pe.fromSignaling(i.externalId,i.deviceIdx||0),mediaSettings:ge(i.mediaSettings),participantState:E.mapParticipantState(i),state:i.state,roles:i.roles||[],status:l.batchParticipantsOnStart?"WAITING":null,muteStates:i.muteStates||{},unmuteOptions:i.unmuteOptions||[],observedIds:i.observedIds||[],markers:this._denormalizeMarkers(a,i.markers),movieShareInfos:i.movieShareInfos,isInRoom:t})),i.roles&&i.roles.length&&(d.debug(`Roles for participant [${a}] changed: ${i.roles}`),g.onRolesChanged(this._participants[a].externalId,i.roles))}})}_registerParticipantLocalMuteState(e){return c(this,null,function*(){if(!e.muteStates)return Promise.resolve();let t=Dt(e.muteStates,ye.MUTE),i=Dt(e.muteStates,ye.MUTE_PERMANENT);for(let a of[t,i])a.length&&(yield this._onMuteParticipant({muteStates:e.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:a,stateUpdated:!0}))})}_getStatusByTransportState(e){let t;return e==="CONNECTED"?t="CONNECTED":e==="CONNECTING"||e==="OPENED"?t="CONNECTING":e==="RECONNECTING"&&(t="RECONNECT"),t}_registerParticipantInCache(e){return this._participants[e.id]=e}_getExistedParticipantByIdOrCreate(e){return c(this,null,function*(){return this._participants[e]||this._createParticipant({id:e})})}_getExternalIdByParticipantId(e){return c(this,null,function*(){var t;if(this._isMe(e))return this._conversation.externalId;if(l.useParticipantListChunk)return(yield this._getExistedParticipantByIdOrCreate(e)).externalId;if((t=this._participants[e])!=null&&t.externalId)return this._participants[e].externalId;{let i=yield this._getParticipantId(e);return this._api.cacheExternalId(e,i),i}})}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){return c(this,null,function*(){if(l.useParticipantListChunk){let i=this._registerParticipantInCache(yield this._getExistedParticipantByIdOrCreate(e));return this._setParticipantMarkers(i,t),i}return this._participants[e]})}_warnParticipantNotInConversation(e){d.warn(`Participant [${e}] isn't in conversation`)}_setParticipantMarkers(e,t){return e.markers=this._denormalizeMarkers(e.id,t),e}_denormalizeMarkers(e,t){if(!t)return null;let i=Object.values(t).find(a=>"ts"in a&&"rank"in a);return Object.entries(t).reduce((a,[s,o])=>(a[s]=Ye(Ce(Ce({},i),o),{id:e}),a),{})}_processConnectionData(e){return c(this,null,function*(){this._processRooms(e),this._processMuteStates(e),e.conversation.pinnedParticipantId&&(yield this._onPinParticipant(e.conversation.pinnedParticipantId)),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(si.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)})}_processRooms(e){var i,a;let t=(a=(i=e.rooms)==null?void 0:i.roomId)!=null?a:null;this._onRoomSwitched(t,!0)}_processMuteStates(e){var i,a,s;this._setMuteStatesForRoomId((i=e.conversation)==null?void 0:i.muteStates,null);for(let o of(s=(a=e.rooms)==null?void 0:a.rooms)!=null?s:[])this._setMuteStatesForRoomId(o.muteStates,o.id);let t=this._getMuteStatesForCurrentRoom();this._onMuteParticipant({muteStates:t,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(t),muteAll:!0,stateUpdated:!0,roomId:this._conversation.roomId})}_processRecordInfos(e){var t,i,a,s;this._onRecordInfo((t=e.conversation.recordInfo)!=null?t:null);for(let o of(a=(i=e.rooms)==null?void 0:i.rooms)!=null?a:[])this._onRecordInfo((s=o.recordInfo)!=null?s:null,o.id)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Di(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new Yt,this.subscribe(this._transport,"STATE_CHANGED",this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,"LOCAL_STATE_CHANGED",this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,"REMOTE_TRACK_ADDED",this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,"REMOTE_TRACK_REMOVED",this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,"REMOTE_ALL_STALL",this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,"REMOTE_DATA_STATS",this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,"SIGNALLED_STALLED_PARTICIPANTS",this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,"TOPOLOGY_CHANGED",this._onTopologyChanged.bind(this)),this.subscribe(this._transport,"NETWORK_STATUS",this._onNetworkStatus.bind(this)),this.subscribe(this._transport,"REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,"PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this)),this.subscribe(this._transport,"ASR_TRANSCRIPTION",this._onAsrTranscription.bind(this)),this.subscribe(this._transport,"ANIMOJI_STREAM",this._onAnimojiStream.bind(this));let e=this._conversation.direction===$e.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===$.ACCEPTED||t.state===$.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new ki(this._transport),this.subscribe(this._volumesDetector,"VOLUMES_DETECTED",this._onVolumesDetected.bind(this)),this._speakerDetector=new Oi(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,"SPEAKER_CHANGED",this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Qt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Zt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=C.getCameras().length,t=C.getMicrophones().length;d.debug("Cameras: "+e+(C.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(C.hasMicrophonePermission()?"✔":"✖")),S.log(T.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){S.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===$.CALLED||e.state===$.ACCEPTED||this._state==="CLOSE"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),this._participants[e.id]&&(t===w.HUNGUP?this._setParticipantsStatus([e],"HANGUP"):this._setParticipantsStatus([e],"ERROR",t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:"CAMERA",stopStream:!0}]),delete this._participants[e.id],g.onRemoteRemoved(e.externalId,e.markers)))}_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,a;(t=e.remoteStream)==null||t.getTracks().forEach(s=>s.stop()),(i=e.secondStream)==null||i.getTracks().forEach(s=>s.stop()),(a=e.mediaSource)==null||a.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){d.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return c(this,null,function*(){d.debug(`Add new participant [${e}]`);let a=this._participants[e];if(a&&(a.state===$.ACCEPTED||a.state===$.CALLED)){d.warn(`Participant [${a.id}:${a.state}] is already in conversation`);return}a||(a=this._registerParticipantInCache(yield this._createParticipant({id:e,externalId:t.externalId&&pe.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:ge(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}))),this._setParticipantsStatus([a],"WAITING"),i?(a.state=$.HUNGUP,this._removeParticipant(a,i)):this._transport&&(a.state=$.CALLED,this._transport.allocate(a.id,!0),S.log(T.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(a))})}_onRemoveParticipant(e){d.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=ls;i++){let a=E.compose(e,i),s=this._participants[a];s&&t.push(s)}if(!t.length){this._warnParticipantNotInConversation(e);return}if(this._transport)for(let i of t)this._transport.close(i.id);S.log(T.REMOVE_PARTICIPANT)}changeDevice(e){return c(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new kt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ae.UNKNOWN)})}stopVideoTrack(){return c(this,null,function*(){return this._mediaSource.stopVideoTrack()})}toggleScreenCapturing(e){return c(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ae.UNKNOWN)})}disableScreenCapturing(){return c(this,null,function*(){return this._mediaSource?this._mediaSource.disableScreenCapturing():Promise.reject(ae.UNKNOWN)})}toggleAnimojiCapturing(e){this._mediaSource&&this._mediaSource.toggleAnimojiCapturing(e)}setAnimojiSvg(e,t=null,i=null){if(!this._transport)return;let a=!t,s=t!=null?t:this._conversation.compositeUserId;if(e instanceof ArrayBuffer){let o=i!=null?i:this._conversation.externalId.id;this._transport.setAnimojiSvg(s,{svg:e,userId:o,isMe:a});return}this._transport.setAnimojiSvg(s,{svg:e,isMe:a})}setVideoStream(e,t=!1){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return c(this,null,function*(){if(this._mediaSource)return S.log(T.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return c(this,null,function*(){if(this._mediaSource)return S.log(T.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return c(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let a of e){let s=typeof a.uid=="object"?a.uid:pe.fromId(a.uid),o=pe.toString(s);i[o]=a.priority}for(let a of Object.values(this._participants)){let s=pe.toString(a.externalId);i.hasOwnProperty(s)&&(t[a.id]=i[s])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return c(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return c(this,null,function*(){let t={};return t[Ge(e)]={keyFrameRequested:!0},this._signaling.updateDisplayLayout(t)})}requestTestMode(e,t){return c(this,null,function*(){return this._signaling.requestTestMode(e,t)})}updateDisplayLayout(e){return c(this,null,function*(){if(e.length<1||!this._signaling.ready)return;d.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let a of e){let s=typeof a.uid=="object"?a.uid:pe.fromId(a.uid),o=this._api.getCachedOkIdByExternalId(s);if(!o){let I=pe.toString(s);d.log(`Unknown participant external ID ${I}`);continue}let p=E.compose(o,s.deviceIdx),u=Ge({participantId:p,mediaType:a.mediaType,streamName:a.streamName}),h=this._participants[p];h?h.lastRequestedLayouts[u]=a:this._isMe(p)&&(this._myLastRequestedLayouts[u]=a),qt(a)?(this._isMe(p)&&delete this._myLastRequestedLayouts[u],this._streamIdByStreamDescription.has(u)&&!this._cooldownTimestampByStreamDescription.has(u)&&this._cooldownTimestampByStreamDescription.set(u,Date.now())):(this._cooldownTimestampByStreamDescription.delete(u),!this._streamIdByStreamDescription.has(u)&&l.videoTracksCount>0&&this._streamIdByStreamDescription.set(u,null),t[u]=a)}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>l.videoTracksCount;){let a=i.next();if(a.done){d.error("Cannot accommodate all streaming requests: tracks available "+l.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(a.value),t[a.value]={stopStream:!0}}yield this._sendUpdateDisplayLayout(t)})}feedback(e){return this._signaling.feedback(e)}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(d.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=Jt(e),a=this._participants[i.participantId],{externalId:s}=this._conversation,o=this._isMe(i.participantId);if(a){if(i.streamName&&(i.mediaType==="STREAM"||i.mediaType==="MOVIE")){let p={stream:null,streamName:i.streamName,mediaType:i.mediaType};o?g.onLocalLive(s,p):g.onRemoteLive(a.externalId,p)}else o||g.onRemoteStream(a.externalId,null);S.log(T.PAT_DEALLOCATED)}else d.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return c(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[a,s]of Object.entries(t.errorCodeByParticipantId||{})){let o=Jt(a),p=this._participants[o.participantId];if(p){let u;typeof s!="number"?(d.warn(`Unexpected error code ${s} received for participant ${o.participantId}`),u=Xr.UNKNOWN_ERROR):u=Zr(s),i.push({externalId:p.externalId,errorReason:u})}}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 a=i.value;if(a[1]+ds>Date.now())break;let o=a[0];this._stopStreaming(o),e[o]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e)}_onParticipantSourcesUpdate(e){if(this._conversation){d.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return c(this,null,function*(){d.log("Promoted in waiting hall",!e.demote),e.demote?(d.log("Kicked from waiting hall"),this._close(new V(w.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(a){return c(this,arguments,function*(e,t=0,i=[]){d.log(`Chat room updated: ${e}`);let s=[],o=[];i.length&&(i.forEach(p=>{if(p.externalId){let u=Se.fromSignaling(p.externalId);s.push(u),this._api.cacheExternalId(p.id.id,u)}else o.push(E.decomposeId(p.id.id).id)}),o.length&&!s.length&&(s=yield this._api.getExternalIdsByOkIds(o))),g.onChatRoomUpdated(e,t,s)})}_onSharedMovieUpdate(e){return c(this,null,function*(){let{externalId:t}=this._conversation,{data:i}=e;for(let a of i)if(this._isMe(a.participantId))g.onLocalLiveUpdate(t,a);else{let o=yield this._getExternalIdByParticipantId(a.participantId);o&&g.onRemoteLiveUpdate(o,a)}})}_onSharedMovieInfoStarted(e){return c(this,null,function*(){d.log(`Shared movie started data received: ${e.notification}`),yield this._processSharedMovieInfo(e.movieShareInfo)})}_processSharedMovieInfos(e){return c(this,null,function*(){e&&(yield Promise.all(e.map(t=>this._processSharedMovieInfo(t))))})}_processSharedMovieInfo(e){return c(this,null,function*(){if(!e)return;let{externalId:t}=this._conversation;if(this._isMe(e.initiatorId))g.onLocalSharedMovieInfo(t,e);else{let a=yield this._getExternalIdByParticipantId(e.initiatorId);a&&g.onRemoteSharedMovieInfo(a,e)}this._forceOpenTransportForAloneInCall()})}_processConnectionSharedMovieInfo(e){return c(this,null,function*(){let t=e.conversation.participants.find(i=>this._isMe(E.composeId(i)));yield this._processSharedMovieInfos(t==null?void 0:t.movieShareInfos)})}_onSharedMovieInfoStopped(e){return c(this,null,function*(){d.log(`Shared movie stopped data received: ${e.notification}`);let{externalId:t}=this._conversation,{initiatorId:i,movieId:a,source:s}=e,o={initiatorId:i,movieId:a,source:s};if(this._isMe(i))g.onLocalSharedMovieStoppedInfo(t,o);else{let u=yield this._getExternalIdByParticipantId(i);u&&g.onRemoteSharedMovieStoppedInfo(u,o)}})}_onFeaturesPerRoleChanged(e){d.log(`Features per role changed: ${e.notification}`),g.onFeaturesPerRoleChanged(e.featuresPerRole)}_waitForStreamIfNeeded(e){var h,I,b;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||t.mediaType==="ANIMOJI")return;let i=t.participantId,a=this._participants[i];if(l.producerScreenDataChannel&&t.mediaType==="SCREEN"&&!((h=a.mediaSettings)!=null&&h.isFastScreenSharingEnabled))return;let s=Ge(t),o=this._sequenceNumberByStreamDescription.get(s);if(o&&o>e.sequenceNumber){d.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${o}`),S.log(T.PAT_OUTDATED_RESPONSE);return}let p=e.streamId,u=e.rtpTimestamp?this._getWaitingTime(p,e.rtpTimestamp):0;if(u<=0){this._streamWaitTimerByStreamDescription.delete(s);let{externalId:D}=this._conversation,A=this._isMe(i);if(!a&&!A){S.log(T.PAT_ERROR,"participantMissing"),d.error(`Could not find participant by ID: ${i}`);return}let Y=A?D:a.externalId,H=this._streamByStreamId.get(p);if(!H){S.log(T.PAT_ERROR,"streamNotFound"),d.error(`Could not find stream by ID: ${p}`);return}S.log(T.PAT_ALLOCATED),this._streamIdByStreamDescription.set(s,p);let fe=(I=e.participantStreamDescription)==null?void 0:I.mediaType;if(fe==="STREAM"||fe==="MOVIE"){if((b=e.participantStreamDescription)!=null&&b.streamName){let W={streamName:e.participantStreamDescription.streamName,stream:H,mediaType:fe};A?g.onLocalLive(Y,W):g.onRemoteLive(Y,W)}}else if(l.producerScreenTrack&&fe==="SCREEN")g.onRemoteScreenStream(a.externalId,H);else if(!A){let W=(l.producerScreenTrack?null:a.secondStream)||H;g.onRemoteStream(a.externalId,W)}}else{d.debug(`Waiting for ${u} until stream ${p} for ${s} is switched`);let D=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),u);this._streamWaitTimerByStreamDescription.set(s,D)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Ge(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Ge(i)))return i}else{let i={participantId:t,mediaType:"CAMERA"};if(this._streamIdByStreamDescription.has(Ge(i)))return i;let a={participantId:t,mediaType:"SCREEN"};if(this._streamIdByStreamDescription.has(Ge(a)))return a}return d.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?E.includesOneOf(this._conversation.roles,[qe.ADMIN,qe.CREATOR]):!1}_checkAdminRole(){if(this._conversation&&!E.includesOneOf(this._conversation.roles,[qe.ADMIN,qe.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}startAsr(e){return c(this,null,function*(){yield this._signaling.startAsr(e)})}stopAsr(){return c(this,null,function*(){yield this._signaling.stopAsr()})}requestAsr(e){return c(this,null,function*(){yield this._signaling.requestAsr(e)})}muteParticipant(){return c(this,arguments,function*(e=null,t,i=[],a=null){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i,a)})}enableFeatureForRoles(e,t){return c(this,null,function*(){yield this._signaling.enableFeatureForRoles(e,t)})}pinParticipant(e,t){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return c(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return c(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Vr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return c(this,null,function*(){if(!this._signaling)return Promise.reject();let a=null;e&&(a=ya(e));let s=yield this._signaling.getWaitingHall(a,t,i);if(s.error)return Promise.reject(s.message);let o=s.participants||[],p=[],u=[],h=null;return o.length&&(o.forEach(I=>{if(I.externalId){let b=Se.fromSignaling(I.externalId);p.push(b),this._api.cacheExternalId(I.id.id,b)}else u.push(E.decomposeId(I.id.id).id)}),u.length&&!p.length&&(p=yield this._api.getExternalIdsByOkIds(u)),s.hasMore&&(h=Pa(o[o.length-1].id))),{participants:p,pageMarker:h,totalCount:s.totalCount||0}})}promoteParticipant(e,t){return c(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return c(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let a=t.messages[i];yield this._onChatMessage(a)}}})}customData(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return c(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return c(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(a){return c(this,arguments,function*({movieId:e,gain:t,metadata:i}){let s={movieId:e};(t||t===0)&&(s.gain=t),i&&(s.metadata=i);let o=yield this._signaling.addMovie(s);if(o.error)throw new Error(o.error);return{movieId:o.movieId,streamType:o.streamType}})}updateMovie(e){return c(this,null,function*(){let t=yield this._signaling.updateMovie(e);if(t.error)throw new Error(t.error)})}removeMovie(e){return c(this,null,function*(){let t={movieId:e},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}updateRooms(e,t){return c(this,null,function*(){let i=yield this._signaling.updateRooms(e,t);if(i.error)throw new Error(i.error)})}activateRooms(e,t){return c(this,null,function*(){let i=yield this._signaling.activateRooms(e,t);if(i.error)throw new Error(i.error)})}switchRoom(e,t){return c(this,null,function*(){let i=yield this._signaling.switchRoom(e,t);if(i.error)throw new Error(i.error)})}removeRooms(e){return c(this,null,function*(){let t=yield this._signaling.removeRooms(e);if(t.error)throw new Error(t.error)})}startStream(e=!1,t=null,i=null,a="DIRECT_LINK",s=null,o=null){return c(this,null,function*(){let p={movieId:i,name:t,privacy:a,groupId:s,roomId:o,streamMovie:!e},u=yield this._signaling.startStream(p);if(u.error)return Promise.reject(u.message)})}stopStream(e=null){return c(this,null,function*(){if((yield this._signaling.stopStream({roomId:e})).error)return Promise.reject()})}recordSetRole(e,t,i=null){return c(this,null,function*(){let a=yield this._signaling.recordSetRole(e,t,i);if(a.error)throw new Error(a.error)})}getStreamInfo(){return c(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(i){return c(this,arguments,function*({video:e,effect:t}){var a;if(e.width<l.videoMinWidth||e.height<l.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(t){if(t.width<l.videoMinWidth||t.height<l.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");l.videoEffectMaxHeight=t.height,l.videoEffectMaxWidth=t.width}return l.videoMaxWidth=e.width,l.videoMaxHeight=e.height,d.debug("Set local video resolution:",`video ${e.width}x${e.height}`+(t?`, effect ${t.width}x${t.height}`:"")),(a=this._mediaSource)==null?void 0:a.setResolution({video:e,effect:t})})}videoEffect(e){return c(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}getParticipants(e){return c(this,null,function*(){let t=e.externalIds.map(o=>({id:o.id,type:l.externalUserType})),i=yield this._signaling.getParticipants(t);if(i.error)throw new Error(i.error);let a=i.participants,s=this._transport.getState();return Promise.all(a.map(o=>c(this,null,function*(){var u;let p=E.composeId(o);return this._createParticipant({id:p,externalId:o.externalId&&pe.fromSignaling(o.externalId,o.deviceIdx||0),mediaSettings:ge(o.mediaSettings),participantState:E.mapParticipantState(o),state:o.state,roles:o.roles||[],status:(u=this._getStatusByTransportState(s))!=null?u:"WAITING",muteStates:o.muteStates||{},unmuteOptions:o.unmuteOptions||[],observedIds:o.observedIds||[],markers:this._denormalizeMarkers(p,o.markers)})}))).then(E.mapSharedParticipants)})}getParticipantListChunk(e){return c(this,null,function*(){var p;d.log("Request participant list chunk",e);let t=yield this._signaling.getParticipantListChunk(e);if(t.error)throw new Error(t.error);let i=this._createParticipantListChunk(t.chunk),a=i.participants.filter(u=>{let h=E.composeId(u);return!this._participants[h]});yield this._registerParticipants(a);let s=(p=this._transport)==null?void 0:p.getState();return i.participants.forEach(u=>{var b,D;let h=E.composeId(u),I=this._participants[h];I.status=(b=this._getStatusByTransportState(s))!=null?b:"WAITING",I.movieShareInfos=u.movieShareInfos,Object.assign(I.mediaSettings,ge(u.mediaSettings)),Object.assign(I.muteStates,u.muteStates),I.unmuteOptions=(D=u.unmuteOptions)!=null?D:I.unmuteOptions,this._openTransport([I],!0)}),this._participantListChunkToExternalChunk(i)})}_getInitialParticiapntListChunk(){return c(this,null,function*(){let e=l.participantListChunkInitIndex,t=l.participantListChunkInitCount,i="GRID",a=yield this._signaling.getParticipantListChunk({listType:i,fromIdx:e,count:t});return d.debug("Get initial participant list chunk",a.chunk),a.chunk})}_onLocalMediaStreamChanged(e){return c(this,null,function*(){var t,i;this._conversation&&(d.debug("Local media stream changed",e.mediaSettings),g.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)!=null&&t.waitingHall)&&!((i=this._conversation)!=null&&i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return c(this,null,function*(){var t,i;if(d.log("Screen sharing changed",e.track,e.mediaSettings),l.consumerScreenTrack){let a=e.track?new MediaStream([e.track]):null;g.onScreenStream(a,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)!=null&&t.waitingHall)&&!((i=this._conversation)!=null&&i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){d.debug(`Remote media settings changed [${e}]`,t);let{externalId:i}=this._conversation;if(this._isMe(e)){g.onLocalMediaSettings(i,t);return}let s=this._participants[e];if(!s){this._warnParticipantNotInConversation(e);return}s.mediaSettings=t,this._state==="ACTIVE"&&g.onRemoteMediaSettings(s.externalId,t,s.markers),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t)}_changeRemoteParticipantState(e,t){d.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];if(!i){this._warnParticipantNotInConversation(e);return}i.participantState=t||{},this._state==="ACTIVE"&&g.onRemoteParticipantState(i.externalId,i.participantState,i.markers)}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(d.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),g.onRolesChanged(e.externalId,e.roles))}_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,e.roomId);case x.RECORD_STOPPED:return this._onRecordInfo(null,e.roomId);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,e.markers);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);case x.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e);case x.FEEDBACK:return this._onFeedback(e);case x.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e);case x.MOVIE_SHARE_STARTED:return this._onSharedMovieInfoStarted(e);case x.MOVIE_SHARE_STOPPED:return this._onSharedMovieInfoStopped(e);case x.ROOMS_UPDATED:return this._onRoomsUpdated(e);case x.ROOM_UPDATED:return this._onRoomUpdated(e);case x.ROOM_PARTICIPANTS_UPDATED:return this._onRoomParticipantsUpdated(e);case x.FEATURES_PER_ROLE_CHANGED:return this._onFeaturesPerRoleChanged(e);case x.PARTICIPANT_ANIMOJI_CHANGED:return this._onParticipantAnimojiChanged(e);case x.ASR_STARTED:return this._onAsrInfo(e.asrInfo);case x.ASR_STOPPED:return this._onAsrInfo(null)}}_onSignalingReconnect(e){return c(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._conversation.featuresPerRole=e.conversation.featuresPerRole,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?yield this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&(yield this._onPinParticipant(this._conversation.pinnedParticipantId,!0))),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),a=[];for(let s of e.conversation.participants){let o=E.composeId(s),p=s.roles||[];if(this._isMe(o)){t=ge(s.mediaSettings),jt(this._conversation.roles,p)||this._onRolesChanged(o,p);continue}a.push(o);let u=this._participants[o];if(!u)yield this._onJoinedParticipant({participantId:s.id,participant:s,mediaSettings:s.mediaSettings});else{let h=ge(s.mediaSettings);da(h,u.mediaSettings)||this._changeRemoteMediaSettings(o,h);let I=E.mapParticipantState(s),b=u.participantState;E.isEqualParticipantState(I,b)||this._changeRemoteParticipantState(o,I),jt(p,u.roles)||this._onRolesChanged(u.id,p)}}for(let s of i)a.indexOf(s)<0&&this._removeParticipant(this._participants[s],w.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){d.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return c(this,null,function*(){let t=E.composeMessageId(e),i=E.getPeerIdString(e.peerId);if(d.debug(`Participant accepted call [${t}]`),this._conversation&&this._isMe(t)){this._close(new V(w.MISSED),"Call accepted on other device");return}let a=this._participants[t];a||(a=this._registerParticipantInCache(yield this._createParticipant({id:t,mediaSettings:ge(e.mediaSettings)}))),a.state=$.ACCEPTED,a.mediaSettings=ge(e.mediaSettings),this._logWithMediaSettings(T.ACCEPTED_OUTGOING,a.mediaSettings),this._conversation&&this._conversation.direction===$e.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([a.id],i),this._changeRemoteMediaSettings(t,a.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){return c(this,null,function*(){d.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=E.composeMessageId(e);if(this._conversation&&this._isMe(t)){this._close(new V(e.reason,{remote:!0}));return}yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers);let i=this._participants[t];if(!i){this._warnParticipantNotInConversation(t);return}this._transport&&this._transport.close(t),i.state=e.reason===w.REJECTED?$.REJECTED:$.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,w.HUNGUP)})}_onAddedParticipant(e){return c(this,null,function*(){var a,s;d.debug(`Participant added [${e.participantId}]`);let t=E.composeMessageId(e),i=this._participants[t];if(i&&i.state!==$.HUNGUP&&i.state!==$.REJECTED){d.debug(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&pe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:E.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}))),i.state=$.CALLED,i.mediaSettings=ge((a=e.participant)==null?void 0:a.mediaSettings),i.participantState=E.mapParticipantState(e.participant),i.roles=((s=e.participant)==null?void 0:s.roles)||[],this._setParticipantsStatus([i],"WAITING"),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),g.onParticipantAdded(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return c(this,null,function*(){var a,s;d.debug(`Participant joined [${e.participantId}]`);let t=E.composeMessageId(e),i=this._participants[t];if(i&&i.state===$.ACCEPTED){d.warn(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&pe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:E.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},movieShareInfos:e.participant.movieShareInfos,unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[],markers:this._denormalizeMarkers(t,e.participant.markers)}))),this._conversation&&this._conversation.direction===$e.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=$.ACCEPTED,i.mediaSettings=ge(e.mediaSettings),i.participantState=E.mapParticipantState(e.participant),i.roles=e.participant.roles||[],(a=this._transport)!=null&&a.isAllocated(i.id)?this._setParticipantsStatus([i],"CONNECTED"):this._setParticipantsStatus([i],"WAITING"),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((s=this._conversation)!=null&&s.observer))),g.onParticipantJoined(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i),g.onMuteStates(i.muteStates,i.unmuteOptions,Object.keys(i.muteStates),!1,!1,i.externalId,void 0,!0),yield this._processSharedMovieInfos(i.movieShareInfos)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new V(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){return c(this,null,function*(){let t=E.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,ge(e.mediaSettings))})}_onParticipantStateChanged(e){return c(this,null,function*(){let t=E.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteParticipantState(t,E.mapParticipantState(e))})}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._conversation.featuresPerRole=e.featuresPerRole,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),g.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return c(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ge(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),l.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing({captureScreen:i.isScreenSharingEnabled,fastScreenSharing:i.isFastScreenSharingEnabled,captureAudio:i.isAudioSharingEnabled}))})}_onSettingsUpdate(e){d.debug("Got settings update notification",e);let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Sr(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){d.debug("Got video quality update notification",e);let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,a={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=Sr(this._serverSettings,a),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=E.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return c(this,null,function*(){g.onDeviceSwitched(ce.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return c(this,null,function*(){let t=E.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),g.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return c(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=E.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),g.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e,t=null){return c(this,null,function*(){if(!this._conversation)return;let i=this._conversation.recordsInfoByRoom.get(t),a=!1;if(!i!=!e?a=!0:i&&e&&(a=i.recordMovieId!==e.recordMovieId),a)if(this._conversation.recordsInfoByRoom.set(t,e),e){let s=yield this._getParticipantId(e.initiator);g.onRecordStarted(s,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId,t)}else g.onRecordStopped(t);e&&this._forceOpenTransportForAloneInCall()})}_changeRecordInfoForRoom(){return c(this,null,function*(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.recordsInfoByRoom.get(e);if(t){let i=yield this._getParticipantId(t.initiator);g.onRecordStarted(i,t.recordMovieId,t.recordStartTime,t.recordType,t.recordExternalMovieId,t.recordExternalOwnerId,e)}else g.onRecordStopped(e)})}_onParticipantAnimojiChanged(e){return c(this,null,function*(){if(this._conversation){let t=yield this._getParticipantId(e.participantId);g.onParticipantVmojiUpdate(t)}})}_onAsrInfo(e){return c(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.asrInfo!=!e?t=!0:this._conversation.asrInfo&&e&&(t=this._conversation.asrInfo.movieId!==e.movieId),t)if(e){let i=yield this._getParticipantId(e.initiatorId);g.onAsrStarted(i,e.movieId),this._forceOpenTransportForAloneInCall()}else g.onAsrStopped();this._conversation.asrInfo=e})}_onAsrTranscription(e){return c(this,null,function*(){if(!this._conversation)return;let t=yield this._getParticipantId(e.participantId);g.onAsrTranscription(t,e.text,e.timestamp,e.duration)})}_onRolesChanged(e,t){if(this._conversation&&this._isMe(e)&&!jt(this._conversation.roles,t)){d.debug(`Local roles changed: ${t}`),this._conversation.roles=t,g.onLocalRolesChanged(t),this._processMuteState({mediaOptions:Dt(this._getMuteStatesForCurrentRoom(),ye.MUTE_PERMANENT),stateUpdated:!0}),E.includesOneOf(t,[qe.ADMIN,qe.CREATOR])&&this._refreshRooms(!0);return}let i=this._participants[e];i&&!jt(i.roles,t)&&(d.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,g.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return c(this,null,function*(){var h;if(!this._conversation)return;let i=(h=e.roomId)!=null?h:null,a=e.muteStates||{},s=e.unmuteOptions||[],o=e.mediaOptions||[],p=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&!this._isMe(e.participantId)){if(!this._isCallAdmin()){d.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let I=this._participants[e.participantId];I&&(d.debug(`Mute states for participant [${e.participantId}] changed`,a),g.onMuteStates(a,s,o,e.muteAll,e.unmute,I.externalId,p==null?void 0:p.externalId,e.stateUpdated,e.requestedMedia,e.roomId));return}let u=this._getMuteStatesForRoomId(i);if(!(E.isObjectsEquals(u,a)&&E.isArraysEquals(this._conversation.unmuteOptions,s)&&!o.length)){if(this._setMuteStatesForRoomId(a,i),this._conversation.unmuteOptions=s,this._isMe(e.adminId)){e.muteAll&&g.onMuteStates(a,s,o,e.muteAll,e.unmute,null,this._conversation.externalId,e.stateUpdated,e.requestedMedia,e.roomId);return}yield this._processMuteState({mediaOptions:o,muteAll:e.muteAll,unmute:e.unmute,serverSettings:t,admin:p,stateUpdated:e.stateUpdated,requestedMedia:e.requestedMedia,roomId:e.roomId})}})}_changeMuteStatesForRoom(e,t){if(!this._conversation)return;this._conversation.unmuteOptions=[];let i=this._getMuteStatesForRoomId(t),a=this._getMuteStatesForRoomId(e),s=Object.keys(i),o=Object.keys(a);this._processMuteState({mediaOptions:Array.from(new Set([...s,...o])),roomId:e,muteAll:!0,stateUpdated:!0})}_processMuteState(h){return c(this,arguments,function*({mediaOptions:e=[],muteAll:t=!1,unmute:i=!1,serverSettings:a=null,admin:s=null,stateUpdated:o,requestedMedia:p,roomId:u=null}){if(!this._conversation||!this._mediaSource||this._participantState!==$.ACCEPTED)return;let I=Object.assign({},this._getMuteStatesForRoomId(u)),b=this._conversation.unmuteOptions,D=this._mediaSource.getMediaSettings(),A=Object.entries(I);for(let[Y,H]of A)if(!(H!==ye.MUTE&&H!==ye.MUTE_PERMANENT)&&(this._isCallAdmin()&&H===ye.MUTE_PERMANENT&&!t&&(I[Y]=ye.MUTE),!(!e.includes(Y)||i)))switch(Y){case ce.VIDEO:D.isVideoEnabled&&!(a!=null&&a.isVideoEnabled)&&(g.onDeviceSwitched(ce.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case ce.AUDIO:D.isAudioEnabled&&!(a!=null&&a.isAudioEnabled)&&(g.onDeviceSwitched(ce.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case ce.SCREEN_SHARING:D.isScreenSharingEnabled&&!(a!=null&&a.isScreenSharingEnabled)&&(g.onDeviceSwitched(ce.SCREEN_SHARING,!1),yield this.disableScreenCapturing());break;case ce.AUDIO_SHARING:D.isAudioSharingEnabled&&!(a!=null&&a.isAudioSharingEnabled)&&(g.onDeviceSwitched(ce.AUDIO_SHARING,!1),yield this.toggleScreenCapturing({captureScreen:D.isScreenSharingEnabled,fastScreenSharing:D.isFastScreenSharingEnabled,captureAudio:!1}));break}g.onMuteStates(I,b,e,t,i,null,s==null?void 0:s.externalId,o,p,u)})}_onPinParticipant(e,t=!1,i){return c(this,null,function*(){if(!this._conversation)return;let a=this._conversation.pinnedParticipantId;if(a&&a!==e)if(this._isMe(a))g.onLocalPin(!0);else{let s=yield this._getExternalIdByParticipantId(a);s&&g.onPinnedParticipant(s,!0,this._denormalizeMarkers(e,i))}if(this._isMe(e))g.onLocalPin(t);else{let s=yield this._getExternalIdByParticipantId(e);s&&g.onPinnedParticipant(s,t,this._denormalizeMarkers(e,i))}this._conversation.pinnedParticipantId=t?null:e})}_onOptionsChanged(e){this._conversation&&!Br(this._conversation.options,e)&&(this._conversation.options=e,g.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,a]of Object.entries(e)){let s;if(this._isMe(i)||i==="")s=this._conversation.networkRating;else if(this._participants[i])s=this._participants[i].networkRating;else continue;if(s!==a)if(this._isMe(i)||i==="")this._conversation.networkRating=a,g.onLocalNetworkStatusChanged(a);else{let o=this._participants[i];o.networkRating=a,t.push({uid:o.externalId,rating:a})}}if(t.length===0)return;d.log("Received network status update: ",e),g.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(i){if(l.producerScreenTrack){g.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,l.videoTracksCount>0){let a=e;if(!this._streamIdByStreamDescription.has(a)){d.error("Received remote stream notification for a participant that has no track associated with it",a);return}let s=this._streamIdByStreamDescription.get(a);if(!s||this._streamWaitTimerByStreamDescription.has(a)){d.log("Delaying secondary stream start/stop until main stream becomes available",a);return}let o=this._streamByStreamId.get(s);if(!o){S.log(T.PAT_ERROR,"streamNotFound"),d.error(`Could not find stream by ID: ${s}`);return}g.onRemoteStream(i.externalId,i.secondStream||o)}else{let a=t||i.remoteStream;a&&g.onRemoteStream(i.externalId,a)}}}_onAnimojiStream(e,t){if(this._isMe(e)){g.onVmojiStream(t,this._mediaSource.getMediaSettings());return}let i=this._participants[e];i&&g.onRemoteVmojiStream(i.externalId,t)}_onPeerConnectionClosed(e){e==="SERVER"&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(oi.ADD_PARTICIPANT);g.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&g.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,a]of Object.entries(e)){let s=this._participants[i];s&&s.externalId&&t.push({uid:s.externalId,volume:a.real})}g.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return c(this,null,function*(){d.debug(`Transport state has changed: ${t}`,e);let i=this._getStatusByTransportState(t);if(!i)return;let a=e.reduce((s,o)=>{if(o in this._participants){let p=this._participants[o];s.push(p),t==="CONNECTED"&&(p.remoteStream||(p.mediaSettings&&this._changeRemoteMediaSettings(o,p.mediaSettings),this._changeRemoteParticipantState(o,p.participantState)),this._updateDisplayLayoutFromCache(o))}else this._warnParticipantNotInConversation(o);return s},[]);a.length&&this._setParticipantsStatus(a,i)})}_onTransportLocalStateChanged(e){return c(this,null,function*(){var t;if(d.debug(`Local transport state has changed: ${e}`),e==="CONNECTED"&&(g.onLocalStatus("CONNECTED"),((t=this._transport)==null?void 0:t.getTopology())==="SERVER")){let i=Object.values(this._myLastRequestedLayouts);yield this.updateDisplayLayout(i)}e==="CONNECTING"&&g.onLocalStatus("CONNECTING"),e==="RECONNECTING"&&g.onLocalStatus("RECONNECT"),e==="FAILED"&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(w.FAILED)),this._close(new V(w.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return c(this,null,function*(){if(e.endsWith(xe.AUDIO_MIX))d.debug("Remote audio mix track added"),this._audioOutput.add(i),g.onRemoteMixedAudioStream(t);else if(e.startsWith(xe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))d.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{d.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let a=this._participants[e];if(a||(d.warn(`Conversation: track added before participant [${e}]`),a=this._registerParticipantInCache(yield this._createParticipant({id:e})),this._setParticipantsStatus([a],"WAITING"),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(a.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(a.id)&&this._transport.allocate(a.id,!1),i.kind==="audio"&&(this._audioOutput.add(i),l.preserveAudioTracks||t.removeTrack(i)),a.remoteStream!==t){if(a.remoteStream=t,a.secondStream)return;g.onRemoteStream(a.externalId,t)}a.mediaSettings&&this._changeRemoteMediaSettings(e,a.mediaSettings),l.batchParticipantsOnStart||this._changeRemoteParticipantState(e,a.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(d.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!==xe.AUDIO_MIX){let a=this._participants[e];if(!a||a.remoteStream&&a.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e==="DIRECT"&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let a in this._participants)if(this._participants.hasOwnProperty(a)){let s=this._participants[a];e||this._lastStalled[a]?t.push(s):i.push(s)}t.length&&this._setParticipantsStatus(t,"RECONNECT"),i.length&&this._setParticipantsStatus(i,"CONNECTED")}_onRemoteSignalledStall(e){let t={},i=[],a=[];e.forEach(s=>{if(t[s]=!0,!this._lastStalled[s]){let o=this._participants[s];o&&!this._remoteAllStalled&&i.push(o)}delete this._lastStalled[s]}),Object.keys(this._lastStalled).forEach(s=>{let o=this._participants[s];o&&!this._remoteAllStalled&&a.push(o)}),i.length&&this._setParticipantsStatus(i,"RECONNECT"),a.length&&this._setParticipantsStatus(a,"CONNECTED"),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!C.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)!=null&&t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(d.debug("Toggle join availability",{available:t,chatId:e}),g.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return c(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!=="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 a=e.reduce((s,o)=>(o.status!==t&&(o.status=t,l.batchParticipantsOnStart?s.push(o.externalId):g.onParticipantStatus(o.externalId,t,i)),s),[]);a.length&&l.batchParticipantsOnStart&&g.onRemoteStatus(a,t,i)}_onJoinLinkChanged(e){g.onJoinLinkChanged(e.joinLink)}_onRoomsUpdated(e){return c(this,null,function*(){var i,a;let t={};for(let s of Object.keys(Et)){let o=e.updates[s];o&&(t[s]={rooms:yield Promise.all(((a=(i=o==null?void 0:o.rooms)==null?void 0:i.map)==null?void 0:a.call(i,this._convertRoomToExternal.bind(this)))||[]),roomIds:o==null?void 0:o.roomIds,deactivated:o==null?void 0:o.deactivated})}g.onRoomsUpdated(t)})}_onRoomUpdated(e){return c(this,null,function*(){let t=yield this._convertRoomToExternal(e.room);e.events.some(i=>i===Et.UPDATE)&&(e.muteStates!==void 0&&this._setMuteStatesForRoomId(e.muteStates,e.roomId),e.recordInfo!==void 0&&this._conversation.recordsInfoByRoom.set(e.roomId,e.recordInfo)),g.onRoomUpdated(e.events,e.roomId,t,e.deactivate)})}_convertRoomToExternal(e){return c(this,null,function*(){var s,o,p,u,h,I;if(!e)return null;let[t,i,a]=yield Promise.all([Promise.all(((o=(s=e==null?void 0:e.participantIds)==null?void 0:s.map)==null?void 0:o.call(s,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((u=(p=e==null?void 0:e.addParticipantIds)==null?void 0:p.map)==null?void 0:u.call(p,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((I=(h=e==null?void 0:e.removeParticipantIds)==null?void 0:h.map)==null?void 0:I.call(h,this._getExternalIdByParticipantId.bind(this)))||[])]);return{id:e.id,name:e.name,participantCount:e.participantCount,participantIds:t,addParticipantIds:i,removeParticipantIds:a,participants:e.participants,active:e.active,muteStates:e.muteStates}})}_onRoomParticipantsUpdated(e){return c(this,null,function*(){var I,b,D,A,Y;let t=this._transport.getState(),i=(I=e.roomId)!=null?I:null,[a,s]=yield Promise.all([Promise.all(((D=(b=e.addedParticipantIds)==null?void 0:b.map)==null?void 0:D.call(b,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((Y=(A=e==null?void 0:e.addedParticipants)==null?void 0:A.map)==null?void 0:Y.call(A,H=>c(this,null,function*(){var W;let fe=E.composeId(H);return this._createParticipant({id:fe,externalId:H.externalId&&pe.fromSignaling(H.externalId,H.deviceIdx||0),mediaSettings:ge(H.mediaSettings),participantState:E.mapParticipantState(H),state:H.state,roles:H.roles||[],status:(W=this._getStatusByTransportState(t))!=null?W:"WAITING",muteStates:H.muteStates||{},unmuteOptions:H.unmuteOptions||[],observedIds:H.observedIds||[],markers:this._denormalizeMarkers(fe,H.markers)})})))||[])]),o=!1;for(let H of s)H.id===this._conversation.compositeUserId&&(o=!0),this._registerParticipantInCache(H);this._openTransport(s,!0);let p=[],u=[];if(e!=null&&e.removedParticipantMarkers){for(let H of e.removedParticipantMarkers)H.GRID&&u.push(this._getExternalIdByParticipantId(H.GRID.id));p=yield Promise.all(u)}o&&(yield this._onRoomSwitched(i));let h={roomId:i,participantCount:e.participantCount,addedParticipantIds:a,addedParticipants:E.mapSharedParticipants(s),removedParticipantMarkers:e==null?void 0:e.removedParticipantMarkers,removedParticipantIds:p};g.onRoomParticipantsUpdated(h)})}_onRoomSwitched(e,t=!1){return c(this,null,function*(){if(!this._conversation||this._conversation.roomId===e)return;let i=this._conversation.roomId;if(this._conversation.roomId=e,t){g.onRoomStart(e);return}g.onRoomSwitched(e),e!==null&&!this._isCallAdmin()&&(yield this._refreshRooms(!1)),this._changeRecordInfoForRoom(),this._changeMuteStatesForRoom(e,i)})}_refreshRooms(e){return c(this,null,function*(){var a,s;let i=(s=(a=(yield this._signaling.getRooms(e)).rooms)==null?void 0:a.rooms)!=null?s:[];for(let o of i)this._setMuteStatesForRoomId(o.muteStates,o.id),this._conversation.recordsInfoByRoom.set(o.id,o.recordInfo);e&&g.onRoomsUpdated({[Et.UPDATE]:{rooms:yield Promise.all(i.map(this._convertRoomToExternal.bind(this)))}})})}_onFeedback(e){return c(this,null,function*(){let t=s=>c(this,null,function*(){return(yield this._registerParticipantAndSetMarkersIfChunkEnabled(s)).externalId}),i=e.feedback.map(s=>c(this,null,function*(){let o=s.items.map(u=>c(this,null,function*(){if(u.participantId===this._conversation.compositeUserId)return Promise.resolve(Ye(Ce({},u),{participantId:this._conversation.externalId}));let h=yield t(u.participantId);return Ye(Ce({},u),{participantId:h})})),p=yield Promise.all(o);return Ye(Ce({},s),{items:p})})),a=yield Promise.all(i);g.onFeedback(a,e.roomId)})}_isMe(e){var t;return e===((t=this._conversation)==null?void 0:t.compositeUserId)}_getMuteStatesForRoomId(e=null){var i;return(i=this._conversation.muteStates.get(e))!=null?i:{}}_getMuteStatesForCurrentRoom(){return this._getMuteStatesForRoomId(this._conversation.roomId)}_setMuteStatesForRoomId(e={},t=null){this._conversation.muteStates.set(t,e)}_forceOpenTransportForAloneInCall(){var e;this._transport.getTopology()==="SERVER"&&this._transport.getState()==="IDLE"&&this._participantState!==$.CALLED&&this._transport.open(this._transport.allocated(),null,!!((e=this._conversation)!=null&&e.observer),!0)}},U=K;U._delayedHangup=!1;var ei=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,ei.prototype),this.participantErrors=t}};var Lt,ti=null;function ps(){return c(this,null,function*(){var n;if(l.apiEnv!=="AUTO")return l.apiEndpoint;try{let r=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),t=yield(yield fetch(r,{method:"GET",mode:"cors",cache:"no-cache"})).json(),i=(n=t==null?void 0:t.Answer[0])==null?void 0:n.data;if(!i)throw new Error("Wrong DNS response");return d.debug("Resolved API endpoint",i),i}catch(r){return d.warn("Failed to resolve API endpoint using DNS, default is used",r),l.apiEndpoint}})}function ka(){return c(this,null,function*(){return Lt||ti||(ti=ps(),Lt=yield ti,ti=null,Lt)})}function Oa(){if(!l.apiKey)throw new V(ae.API,{message:"Required argument apiAppKey not passed"})}function Tr(t){return c(this,arguments,function*(n,r={},e=!1){if(!window.Blob||!window.navigator.sendBeacon)return;yield ka();let i=xa(n,r,e),a=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${Lt}/fb.do`,a)})}function wa(t){return c(this,arguments,function*(n,r={},e=!1){yield ka();let i=xa(n,r,e);return us(i)})}function us(n){return c(this,null,function*(){return new Promise((r,e)=>{let t=new XMLHttpRequest;t.open("POST",`${Lt}/fb.do`,!0),t.setRequestHeader("Content-type","application/x-www-form-urlencoded"),t.onreadystatechange=()=>{if(t.readyState!==XMLHttpRequest.DONE)return;let i;try{i=JSON.parse(t.responseText)}catch(a){i={result:t.responseText}}t.status!==200||i.hasOwnProperty("error_msg")?e(i):r(i)},t.send(n)})})}function xa(n,r={},e=!1){r.method=n,r.format="JSON",r.application_key||(r.application_key=l.apiKey),e||(ne.sessionKey?r.session_key=ne.sessionKey:ne.accessToken&&(r.access_token=ne.accessToken));for(let[i,a]of Object.entries(r))typeof a=="object"&&(r[i]=JSON.stringify(a));let t="";for(let[i,a]of Object.entries(r))t&&(t+="&"),t+=`${i}=${encodeURIComponent(a)}`;return t}var hs=10,_s=700,gs=3e3,Nt=class extends ot{constructor(){super(...arguments);this._userId=null;this._externalUidsCache=new Map;this._extrnalUidsBatch=new Set;this._extrnalUidsBatchTimeout=null}_callUnsafe(a){return c(this,arguments,function*(e,t={},i=!1){let s=o=>c(this,null,function*(){try{return yield wa(e,t,i)}catch(p){if(!p.hasOwnProperty("error_msg")&&(o++,d.debug(`${e} network error, attempt ${o}...`),o<hs))return yield E.delay(Math.min(o*_s,gs)),s(o);throw d.warn(e,"error",p),p}});return s(0)})}_call(a){return c(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(s){d.warn("Api call error",s);let o=ae.API;switch(s.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:o=w.SERVICE_DISABLED;break;case 1102:o=w.CALLEE_IS_OFFLINE;break;case 1103:o=w.NOT_FRIENDS;break;case 1104:case 1106:o=w.EXTERNAL_API_ERROR;break;case 1113:o=w.CALLER_IS_REJECTED;break}throw new V(o,{message:s.error_msg,code:s.error_code})}})}userId(e){return c(this,null,function*(){let t=E.decomposeId(e).id;return ne.isEmpty()?Se.fromId(String(t)):(yield this._prepareUserIdsByOkIdsBatched([t]),Se.fromString(this._externalUidsCache.get(t)))})}prepareUserIds(e){return c(this,null,function*(){ne.isEmpty()||(yield this._prepareUserIdsByOkIdsBatched(e))})}_prepareUserIdsByOkIdsBatched(e){return e.some(i=>!this._externalUidsCache.has(i))?(e.forEach(i=>this._extrnalUidsBatch.add(i)),this._extrnalUidsBatchTimeout||(this._extrnalUidsBatchPromise=new Promise(i=>{this._extrnalUidsBatchTimeout=window.setTimeout(()=>{if(this._extrnalUidsBatch.size>0){let a=[...this._extrnalUidsBatch];this._extrnalUidsBatch.clear(),this._getExternalIdsByOkIds(a).then(s=>{for(let o in s)s.hasOwnProperty(o)&&this._externalUidsCache.set(parseInt(o,10),s[o]);i()})}this._extrnalUidsBatchTimeout=null},l.api.userIdsByOkBatchedTimeout)})),this._extrnalUidsBatchPromise):Promise.resolve()}authorize(){return c(this,null,function*(){if(!this._uuid){let t=Qe.get("uuid");t||(t=E.uuid(),Qe.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:l.appVersion,client_type:"SDK_JS"}};return l.authToken&&(e.session_data.auth_token=l.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),ne.sessionKey=t.session_key,ne.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&g.onTokenExpired(),new V(ae.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${l.appName}:${l.sdkVersion}`,platform:l.platform,items:e})};Tr("log.externalLog",t)}init(){Oa()}joinConversation(e,t=!1,i){return c(this,null,function*(){let a={conversationId:e,isVideo:t,protocolVersion:l.protocolVersion};return i&&(a.chatId=i),this._call("vchat.joinConversation",a)})}createConversation(s){return c(this,arguments,function*(e,t="",i=!1,{onlyAdminCanShareMovie:a}={}){let o=this._preareStartConversationData({conversationId:e,isVideo:!1,joiningAllowed:!0,payload:t,requireAuthToJoin:i,onlyAdminCanShareMovie:a});return this._startConversation(o)})}startConversation(h,I,b){return c(this,arguments,function*(e,t,i,a=!1,s="",o=!1,p=!1,{onlyAdminCanShareMovie:u}={}){let D=this._preareStartConversationData({conversationId:e,isVideo:a,joiningAllowed:o,payload:s,requireAuthToJoin:p,onlyAdminCanShareMovie:u});if(t&&t.length)switch(i){case Ve.USER:D.uids=t.join(",");break;case Ve.GROUP:D.gid=t[0];break;case Ve.CHAT:D.chatId=t[0];break}return this._startConversation(D)})}_preareStartConversationData({conversationId:e,isVideo:t,payload:i="",joiningAllowed:a=!1,requireAuthToJoin:s=!1,onlyAdminCanShareMovie:o}){let p={conversationId:e,isVideo:t,protocolVersion:l.protocolVersion};return a&&(p.createJoinLink=!0),i&&(p.payload=i),l.domain&&(p.domainId=l.domain),l.externalDomain&&(p.externalDomain=l.externalDomain),s&&(p.requireAuthToJoin=!0),o!==void 0&&(p.onlyAdminCanShareMovie=o),p}_startConversation(e){return c(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return c(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return c(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return c(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let a=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(a.uid),a.token})}joinConversationByLink(e,t=!1,i,a){return c(this,null,function*(){let s={joinLink:e,isVideo:t,protocolVersion:l.protocolVersion};return i!=null&&i.length&&(s.observedIds=i.join(",")),l.anonymToken&&(s.anonymToken=l.anonymToken),a&&(s.payload=a),this._call("vchat.joinConversationByLink",s)})}getOkIdsByExternalIds(e){return c(this,null,function*(){let t=Se.fromIds(e),i=[],a={methods:[]},s=[],o=[...this._externalUidsCache.keys()],p=[...this._externalUidsCache.values()];for(let h of t){let I=Se.toString(h),b=p.indexOf(I);b>-1?i.push(Number(o[b])):(s.push(I),a.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:h.id,anonym:h.type==="ANONYM"},onError:"SKIP"}}))}return a.methods.length&&(yield this._call("batch.executeV2",a)).forEach((h,I)=>{if(h.ok){let b=Number(h.ok.ok_id);this._externalUidsCache.set(b,s[I]),i.push(b)}}),i})}getExternalIdsByOkIds(e){return c(this,null,function*(){let t=[],i=[];for(let s of e)this._externalUidsCache.has(s)?t.push(Se.fromString(this._externalUidsCache.get(s))):i.push(s);if(!i.length)return t;let a=yield this._getExternalIdsByOkIds(i);for(let s in a)a.hasOwnProperty(s)&&this._externalUidsCache.set(parseInt(s,10),a[s]);for(let s of i)a.hasOwnProperty(s)&&t.push(Se.fromString(a[s]));return t})}getCachedOkIdByExternalId(e){let t=[...this._externalUidsCache.keys()],i=[...this._externalUidsCache.values()],a=Se.toString(e),s=i.indexOf(a);return s>-1?E.composeUserId(t[s],z.USER):null}cacheExternalId(e,t){let i=E.decomposeId(e).id;this._externalUidsCache.set(i,Se.toString(t))}getConversationParams(e){return c(this,null,function*(){let t={};return l.anonymToken&&(t.anonymToken=l.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:w.HUNGUP};l.anonymToken&&(t.anonymToken=l.anonymToken),Tr("vchat.hangupConversation",t)}removeHistoryRecords(e){return c(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return c(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[a,s]of Object.entries(i.external_ids))t[a]=Se.fromIdToString(s,"USER");if(i.anonym_ids)for(let[a,s]of Object.entries(i.anonym_ids))t[a]=Se.fromIdToString(s,"ANONYM");return t}catch(i){return t}})}};var wi=class{requestAsr(r){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,1),t.setUint8(1,r?0:1),e}};var j=require("messagepack");var La=(N=>(N.RECOVER="recover",N.ACCEPT_CALL="accept-call",N.ADD_PARTICIPANT="add-participant",N.REMOVE_PARTICIPANT="remove-participant",N.HANGUP="hangup",N.TRANSMIT_DATA="transmit-data",N.ACCEPT_PRODUCER="accept-producer",N.ALLOCATE_CONSUMER="allocate-consumer",N.CHANGE_MEDIA_SETTINGS="change-media-settings",N.CHANGE_PARTICIPANT_STATE="change-participant-state",N.CHANGE_STREAM_PRIORITIES="change-streams-priorities",N.UPDATE_DISPLAY_LAYOUT="update-display-layout",N.REPORT_PERF_STAT="report-perf-stat",N.REPORT_SHARING_STAT="report-sharing-stat",N.RECORD_START="record-start",N.RECORD_STOP="record-stop",N.RECORD_SET_ROLE="record-set-role",N.RECORD_GET_STATUS="record-get-status",N.SWITCH_MICRO="switch-micro",N.SWITCH_TOPOLOGY="switch-topology",N.REQUEST_REALLOC="request-realloc",N.CHAT_MESSAGE="chat-message",N.CHAT_HISTORY="chat-history",N.CUSTOM_DATA="custom-data",N.GRANT_ROLES="grant-roles",N.MUTE_PARTICIPANT="mute-participant",N.ENABLE_FEATURE_FOR_ROLES="enable-feature-for-roles",N.PIN_PARTICIPANT="pin-participant",N.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",N.CHANGE_OPTIONS="change-options",N.GET_WAITING_HALL="get-waiting-hall",N.GET_PARTICIPANT_LIST_CHUNK="get-participant-list-chunk",N.GET_PARTICIPANTS="get-participants",N.PROMOTE_PARTICIPANT="promote-participant",N.REQUEST_TEST_MODE="request-test-mode",N.ADD_MOVIE="add-movie",N.UPDATE_MOVIE="update-movie",N.REMOVE_MOVIE="remove-movie",N.GET_ROOMS="get-rooms",N.UPDATE_ROOMS="update-rooms",N.ACTIVATE_ROOMS="activate-rooms",N.REMOVE_ROOMS="remove-rooms",N.SWITCH_ROOM="switch-room",N.FEEDBACK="feedback",N.ASR_START="asr-start",N.ASR_STOP="asr-stop",N.REQUEST_ASR="request-asr",N))(La||{}),L=La;function ii(){let n=new DataView(new ArrayBuffer(64)),r=0;function e(t){if(r+t>n.byteLength){let i=new Uint8Array(Math.max(r+t,n.byteLength+64));i.set(new Uint8Array(n.buffer.slice(0,r))),n=new DataView(i.buffer)}}return{put(t){if(e(t.byteLength),fs(t)){let i=t.buffer;new Uint8Array(n.buffer).set(new Uint8Array(i),r)}else new Uint8Array(n.buffer).set(new Uint8Array(t),r);r+=t.byteLength},putI8(t){e(1),n.setInt8(r,t),++r},putI16(t){e(2),n.setInt16(r,t),r+=2},putI32(t){e(4),n.setInt32(r,t),r+=4},putI64(t){e(8);let i=t<0;i&&(t=-t);let a=t/4294967296|0,s=t%4294967296|0;i&&(s=~s+1|0,a=s===0?~a+1|0:~a),n.setUint32(r,a),n.setUint32(r+4,s),r+=8},putUi8(t){e(1),n.setUint8(r,t),++r},putUi16(t){e(2),n.setUint16(r,t),r+=2},putUi32(t){e(4),n.setUint32(r,t),r+=4},putUi64(t){e(8),n.setUint32(r,t/4294967296|0),n.setUint32(r+4,t%4294967296),r+=8},putF(t){e(8),n.setFloat64(r,t),r+=8},ui8array(){return new Uint8Array(n.buffer.slice(0,r))}}}function fs(n){return n.buffer!==void 0}function xi(n){let r=ArrayBuffer.isView(n)?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),e=0;return{peek(){return r.getUint8(e)},get(t){e+=t;let i=r.byteOffset;return r.buffer.slice(i+e-t,i+e)},getI8(){return r.getInt8(e++)},getI16(){return e+=2,r.getInt16(e-2)},getI32(){return e+=4,r.getInt32(e-4)},getI64(){e+=8;let t=r.getInt32(e-8),i=r.getUint32(e-4);return t*4294967296+i},getUi8(){return r.getUint8(e++)},getUi16(){return e+=2,r.getUint16(e-2)},getUi32(){return e+=4,r.getUint32(e-4)},getUi64(){e+=8;let t=r.getUint32(e-8),i=r.getUint32(e-4);return t*4294967296+i},getF32(){return e+=4,r.getFloat32(e-4)},getF64(){return e+=8,r.getFloat64(e-8)}}}var Na=0,Ua=1,Ss=2,vs=0,Es=1,Is=2,Li=0,Ts=0,Rs=0,Cs=1,Ni=class{constructor(){this.participantIdRegistry=null}setParticipantIdRegistry(r){this.participantIdRegistry=r}serializeUpdateDisplayLayout(r,e){let t=ii();j.Int.enc(t,Na),j.Int.enc(t,Li),j.Int.enc(t,r),j.Nil.enc(t,null);let i=[];for(let a in e)e.hasOwnProperty(a)&&this.writeLayout(e,a,i);return j.Arr.enc(t,i),j.Nil.enc(t,null),t.ui8array()}writeLayout(r,e,t){let i=r[e],a=ii();if(this.writeStreamDesc(e,a),qt(i))j.Int.enc(a,Es);else if(gr(i))j.Int.enc(a,Is);else if(j.Int.enc(a,vs),i.priority!==void 0?j.Int.enc(a,i.priority):j.Nil.enc(a,null),i.width!==void 0&&i.height!==void 0?(j.Int.enc(a,Math.round(i.width)),j.Int.enc(a,Math.round(i.height))):(j.Nil.enc(a,null),j.Nil.enc(a,null)),i.fit!==void 0)switch(i.fit){case"cv":j.Int.enc(a,Rs);break;case"cn":j.Int.enc(a,Cs);break;default:j.Nil.enc(a,null)}else j.Nil.enc(a,null);t.push(a.ui8array())}writeStreamDesc(r,e){if(this.participantIdRegistry){let t=this.participantIdRegistry.getCompactId(r);if(t!==void 0){j.Int.enc(e,t);return}}j.Str.enc(e,r)}serializePerfStatReport(r,e){let t=ii();return j.Int.enc(t,Ua),j.Int.enc(t,Li),j.Int.enc(t,r),j.Int.enc(t,e.framesDecoded),j.Int.enc(t,e.framesReceived),t.ui8array()}serializeSharingStatReport(r,e){let t=ii();return j.Int.enc(t,Ss),j.Int.enc(t,Li),j.Int.enc(t,r),j.Int.enc(t,e.minDelay),j.Int.enc(t,e.maxDelay),j.Int.enc(t,e.avgDelay),j.Int.enc(t,e.largeDelayDuration),t.ui8array()}deserializeCommandResponse(r){return c(this,null,function*(){let e;if(r instanceof Blob){let s=Blob.prototype.arrayBuffer?yield r.arrayBuffer():yield ca(r);e=xi(s)}else e=xi(r);let t=j.Int.dec(e),i=j.Int.dec(e);if(i!==Li){d.warn("Unsupported version for command type: "+t+", version "+i);return}if(j.Int.dec(e)!==Ts){d.warn("Error code: "+t+"received for command type: "+t+", version "+i);return}switch(t){case Na:return this.deserializeUpdateDisplayLayoutResponse(e);case Ua:return this.deserializeReportPerfStatResponse(e);default:return d.warn("unsupported command response commandType: "+t),null}})}deserializeUpdateDisplayLayoutResponse(r){let e=j.Int.dec(r),t=j.Arr.dec(r),i={};return t.forEach(a=>{let s=xi(a),o=j.Any.dec(s);if(typeof o=="string")i[o]=j.Int.dec(s);else{let p=o,u=Ge(this.participantIdRegistry.getStreamDescription(p));i[u]=j.Int.dec(s)}}),{type:"response",sequence:e,response:L.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:i}}deserializeReportPerfStatResponse(r){let e=j.Int.dec(r),t=j.Int.dec(r);return{type:"response",sequence:e,response:L.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:t}}};var Ui="open",Ba=[()=>l.producerScreenTrack,()=>l.videoTracksCount>0,()=>!0,()=>l.filteredMessages,()=>l.consumerScreenTrack,()=>!0,()=>l.movieShare,()=>l.useParticipantListChunk,()=>l.useRooms,()=>l.useVmoji],Ps=10,Ae=class extends dt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.asrCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+l.platform+"&appVersion="+l.appVersion+"&version="+l.protocolVersion+"&device="+l.device+"&capabilities="+Ae._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null;this.asrDataChannel=null;this.producerCommandDataChannelEnabled=!1;this.producerCommandSerializationService=new Ni;this.asrCommandSerializer=new wi}static _getCapabilityFlags(){let e=0;for(let t=0;t<Ba.length;t++)Ba[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,this.producerCommandSerializationService.setParticipantIdRegistry(e)}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var a;let i=(a=this.participantIdRegistry)==null?void 0:a.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=t=>{this.producerCommandSerializationService.deserializeCommandResponse(t.data).then(i=>{i&&this._handleMessage(i)}).catch(i=>{d.warn("Cannot parse message at producerCommandDataChannel",i)})},this._handleCommandsQueue(this.datachannelCommandsQueue)}useCommandDataChannel(e){this.producerCommandDataChannelEnabled=e}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return c(this,null,function*(){return this.postfix+=`&clientType=${l.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){S.log(T.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=a=>{t(a),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=a=>{i(a),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(a){return c(this,arguments,function*(e,t={},i=0){if(t.participantId){let s=E.decomposeParticipantId(t.participantId),o=E.decomposeId(s.compositeUserId);t=Object.assign({},t,{participantId:o.id,participantType:o.type}),s.deviceIdx&&(t.deviceIdx=s.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(a){return c(this,arguments,function*(e,t={},i=0){let s=o=>{var p,u;if(e===L.REQUEST_ASR)this.asrCommandsQueue.push(o),((p=this.asrDataChannel)==null?void 0:p.readyState)===Ui&&this._handleCommandsQueue(this.asrCommandsQueue);else if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(o),((u=this.producerCommandDataChannel)==null?void 0:u.readyState)===Ui&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){S.log(T.SOCKET_ACTION,"not_opened"),d.warn("Socket not opened"),o.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(S.log(T.SOCKET_ACTION,"invalid_state"),d.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(o),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((o,p)=>{let u=(I,b=!1)=>{!i||b?p(I):(d.debug("Resending a signaling message",e,h.sequence),i--,s(h))},h={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:o,reject:u};s(h)})})}_isDataChannelCommand(e){return this.producerCommandDataChannelEnabled?e===L.UPDATE_DISPLAY_LAYOUT||e===L.REPORT_PERF_STAT||e===L.REPORT_SHARING_STAT:!1}static _isDataChannelResponseRequired(e){return e===L.UPDATE_DISPLAY_LAYOUT||e===L.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return c(this,null,function*(){return this._send(L.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return c(this,null,function*(){return this._send(L.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e,t){return c(this,null,function*(){return this._send(L.REQUEST_TEST_MODE,{consumer:e,producer:t})})}sendSdp(e,t){return c(this,null,function*(){return this._send(L.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return c(this,null,function*(){return this._send(L.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return c(this,null,function*(){return this._send(L.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},Ps)})}changeParticipantState(e){return c(this,null,function*(){return this._send(L.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return c(this,null,function*(){return this._send(L.ADD_PARTICIPANT,Ce({participantId:e},t))})}removeParticipant(e,t=!1){return c(this,null,function*(){return this._send(L.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return c(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(L.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return c(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(L.ACCEPT_PRODUCER,i)})}changePriorities(e){return c(this,null,function*(){return this._send(L.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return c(this,null,function*(){return this._send(L.UPDATE_DISPLAY_LAYOUT,e)})}addMovie(e){return c(this,null,function*(){return this._send(L.ADD_MOVIE,e)})}updateMovie(e){return c(this,null,function*(){return this._send(L.UPDATE_MOVIE,e)})}removeMovie(e){return c(this,null,function*(){return this._send(L.REMOVE_MOVIE,e)})}updateRooms(e,t){return c(this,null,function*(){return this._send(L.UPDATE_ROOMS,{rooms:e,assignRandomly:t})})}activateRooms(e,t){return c(this,null,function*(){return this._send(L.ACTIVATE_ROOMS,{roomIds:e,deactivate:t})})}switchRoom(e,t){return c(this,null,function*(){return this._sendRaw(L.SWITCH_ROOM,{toRoomId:e,participantId:t})})}getRooms(e){return c(this,null,function*(){return this._sendRaw(L.GET_ROOMS,{withParticipants:e})})}removeRooms(e){return c(this,null,function*(){return this._send(L.REMOVE_ROOMS,{roomIds:e})})}startStream(e){return c(this,null,function*(){return this._send(L.RECORD_START,e)})}stopStream(){return c(this,arguments,function*(e={roomId:null}){return this._send(L.RECORD_STOP,e)})}recordSetRole(e,t,i=null){return c(this,null,function*(){return this._send(L.RECORD_SET_ROLE,{participantId:e,role:t,roomId:i})})}getRecordStatus(){return c(this,null,function*(){return this._send(L.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return c(this,null,function*(){return this._send(L.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return c(this,null,function*(){return this._send(L.REQUEST_REALLOC)})}reportPerfStat(e){return c(this,null,function*(){return this._send(L.REPORT_PERF_STAT,e)})}reportSharingStat(e){return c(this,null,function*(){return this._send(L.REPORT_SHARING_STAT,e)})}chatMessage(e,t=null){return c(this,null,function*(){return this._send(L.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return c(this,null,function*(){return this._send(L.CHAT_HISTORY,{count:e})})}customData(e,t){return c(this,null,function*(){return this._send(L.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return c(this,null,function*(){let a={participantId:e,roles:t};return i&&(a.revoke=!0),this._sendRaw(L.GRANT_ROLES,a)})}muteParticipant(e,t,i,a=null){return c(this,null,function*(){return this._sendRaw(L.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i,roomId:a})})}enableFeatureForRoles(e,t){return c(this,null,function*(){return this._sendRaw(L.ENABLE_FEATURE_FOR_ROLES,{feature:e,roles:t})})}pinParticipant(e,t){return c(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(L.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return c(this,null,function*(){return this._send(L.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return c(this,null,function*(){return this._send(L.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return c(this,null,function*(){let a={};return e&&(a.fromId=e),t&&(a.count=t),i&&(a.backward=i),this._send(L.GET_WAITING_HALL,a)})}promoteParticipant(e,t=!1){return c(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(L.PROMOTE_PARTICIPANT,i)})}feedback(e){return c(this,null,function*(){return this._sendRaw(L.FEEDBACK,{key:e})})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}getParticipantListChunk(e){return c(this,null,function*(){return this._send(L.GET_PARTICIPANT_LIST_CHUNK,e)})}getParticipants(e){return c(this,null,function*(){return this._send(L.GET_PARTICIPANTS,{externalIds:e})})}startAsr(e){return c(this,null,function*(){return this._send(L.ASR_START,e)})}stopAsr(){return c(this,null,function*(){return this._send(L.ASR_STOP)})}requestAsr(e){return c(this,null,function*(){return this._send(L.REQUEST_ASR,{request:e})})}setAsrDataChannel(e){this.asrDataChannel=e,this._handleCommandsQueue(this.asrCommandsQueue)}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Fe.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),t=i(t),d.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();function i(a){if(!l.useParticipantListChunk)return a;let s=l.participantListChunkInitIndex;a+=`&partIdx=${s}`;let o=l.participantListChunkInitCount;return o!==null&&(a+=`&partCount=${o}`),a}}_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(){d.debug("Socket opened"),S.log(T.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){S.log(T.SOCKET_ACTION,"parse_error"),d.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(d.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(Ie.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Ie.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(Ie.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(S.log(T.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(S.log(T.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new V(w.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(Ie.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 V(ae.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(S.log(T.SOCKET_ACTION,"unknown_message"),d.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(Ie.FAILED,e)}_onError(e){S.log(T.SOCKET_ACTION,"error"),d.error("Signaling error",e)}_onClose(e){S.log(T.SOCKET_ACTION,"closed"),d.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Ae.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){this.socket&&(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(Ae.RECONNECT_MAX_DELAY,Ae.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));d.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),S.log(T.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Fe.RETRY),e)}_handleCommandResponse(e,t){var a;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)):((a=this.socket)==null?void 0:a.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],S.log(T.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Ae.WAIT_RESPONSE_DELAY)}_serializeAsrCommand(e){let t=e.params;return this.asrCommandSerializer.requestAsr(t.request)}_handleCommandsQueue(e){var t,i,a,s;for(;e.length>0;){let o=e.shift();if(o.name===L.REQUEST_ASR){if(((t=this.asrDataChannel)==null?void 0:t.readyState)!==Ui){o.reject(new Error(`Invalid data channel state: ${(i=this.asrDataChannel)==null?void 0:i.readyState}`));return}let p=this._serializeAsrCommand(o);p!==null&&(this.asrDataChannel.send(p),o.resolve({}))}else if(this._isDataChannelCommand(o.name)){if(((a=this.producerCommandDataChannel)==null?void 0:a.readyState)!==Ui){o.reject(new Error(`Invalid data channel state: ${(s=this.producerCommandDataChannel)==null?void 0:s.readyState}`));return}Ae._isDataChannelResponseRequired(o.name)&&(o.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:o.name,sequence:o.sequence}),Ae.WAIT_RESPONSE_DELAY),this.responseHandlers[o.sequence]=o);let p=this._serializeBinary(o);p!==null&&this.producerCommandDataChannel.send(p)}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){o.reject(new Error("Invalid state or socket already closed"));continue}o.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:o.name,sequence:o.sequence}),Ae.WAIT_RESPONSE_DELAY),this.responseHandlers[o.sequence]=o,this.socket.send(this._serializeJson(o))}}}_serializeBinary(e){switch(e.name){case L.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case L.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params);case L.REPORT_SHARING_STAT:return this.producerCommandSerializationService.serializeSharingStatReport(e.sequence,e.params)}return d.warn("cannot get binary data for data channel command: "+e.name),null}_serializeJson(e){let t;e.name===L.UPDATE_DISPLAY_LAYOUT?t=this._convertDisplayLayout(e.params):t=e.params;let i=Object.assign({command:e.name,sequence:e.sequence},t);return JSON.stringify(i)}_convertDisplayLayout(e){let t=e,i={};for(let a in t)t.hasOwnProperty(a)&&(i[a]=Ta(t[a]));return{layouts:i}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new V(ae.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Ae.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{d.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Fe.RETRY)},Ae.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},De=Ae;De.RECONNECT_DELAY=l.signalingReconnectDelay,De.RECONNECT_MAX_DELAY=l.signalingReconnectMaxDelay,De.RECONNECT_MAX_COUNT=l.signalingReconnectMaxCount,De.WAIT_CONNECTION_DELAY=l.waitConnectionDelay,De.WAIT_RESPONSE_DELAY=l.waitResponseDelay,De.WAIT_MESSAGE_DELAY=l.waitMessageDelay;var Va=(e=>(e.KING="KING",e.PAWN="PAWN",e))(Va||{}),Fa=Va;var Bi=class{constructor(r){this._queue=new Array(r).fill(null),this._readCursor=this._writeCursor=this._left=0,this._moveReadCursor=!1}get length(){return this._queue.length}get left(){return this._left}toArray(){return Array.from(this._queue)}add(r){this._moveReadCursor&&(this._readCursor=this.nextCursor(this._readCursor)),this._queue[this._writeCursor]===null&&(this._left+=1),this._queue[this._writeCursor]=r,this._writeCursor=this.nextCursor(this._writeCursor),this._moveReadCursor=this._writeCursor===this._readCursor}nextCursor(r){return(r+1)%this._queue.length}next(){let r=this._queue[this._readCursor];return r&&(this._moveReadCursor=!1,this._queue[this._readCursor]=null,this._readCursor=this.nextCursor(this._readCursor),this._left-=1),r}};var Ut,se,ri=null,ys={getCameras:C.getCameras,getMicrophones:C.getMicrophones,getOutput:C.getOutput,getVideoFacingMode:C.getVideoFacingMode,hasCamera:C.hasCamera,hasMicrophone:C.hasMicrophone,getSavedCamera:C.getSavedCamera,getSavedMicrophone:C.getSavedMicrophone,getSavedOutput:C.getSavedOutput,hasCameraPermission:C.hasCameraPermission,hasMicrophonePermission:C.hasMicrophonePermission,hasPermissions:C.hasPermissions,getUserMedia:C.getUserMedia,getUserVideo:C.getUserVideo,getUserAudio:C.getUserAudio,setResolution:C.setResolution,saveDeviceId:C.saveDeviceId,isBrowserSupported:C.isBrowserSupported,isScreenCapturingSupported:C.isScreenCapturingSupported,os:C.os,isMobile:C.isMobile,browserName:C.browserName,browserVersion:C.browserVersion,baseChromeVersion:C.baseChromeVersion,getAudioContext:C.getAudioContext,isAudioShareSupported:C.isAudioShareSupported},bs={participantMarkerCompare:E.participantMarkerCompare};function ja(n){se=n}function Ha(n){Ut=n}function Ms(n){ri=n}function As(n){l.videoEffects=n}function Ds(n,r=null){l.vmoji=n,r&&n.setSDK(r)}function ks(n){return c(this,null,function*(){if(l.set(n),C.browserName()==="Sferum"&&(l.platform=`SFERUM:${C.browserVersion()}`),se||ja(new Nt),Ut||Ha(()=>new De),l.debug&&(Rr.default.disableLog(!1),d.toggle(!0)),d.log(`Calls SDK ${l.sdkVersion}`,n),yield C.init(),!C.isBrowserSupported())throw new V(ae.UNSUPPORTED);d.log("UserAgent:",navigator.userAgent),d.log("Screen resolution:",`${window.screen.width}x${window.screen.height}`),d.log("Permissions:",`Camera: ${C.hasCameraPermission()}, Mic: ${C.hasMicrophonePermission()}`),se.init()})}function Os(s){return c(this,arguments,function*(n,r=[ce.AUDIO],e="",t=!1,i=!1,a){let o=[],p=[];if(Array.isArray(n)?o=n.length?n:[]:n&&(o=[n]),o.length&&(p=yield se.getOkIdsByExternalIds(o),!p.length))throw new V(w.CALLEE_IS_OFFLINE);return Ga(p,Ve.USER,r,e,t,i,a)})}function Ga(o){return c(this,arguments,function*(n,r=Ve.USER,e,t="",i=!1,a=!1,s){if(U.current())throw d.error("There is already active call"),new V(w.FAILED);return new U(se,Ut(),ri).onStart(n,r,e,t,i,a,s)})}function ws(n){return c(this,null,function*(){return Wa(n)})}function Wa(t){return c(this,arguments,function*(n,r=z.USER,e){if(n===U.id())throw new Error("Push has already been processed");return new U(se,Ut(),ri).onPush(n,r,e)})}function xs(n){return c(this,null,function*(){return n&&(l.authToken=n),se.authorize()})}function Ls(){return c(this,arguments,function*(n=[ce.AUDIO]){return vt().accept(n)})}function Ns(){return c(this,null,function*(){let n=U.current();if(n)return n.decline()})}function Us(e){return c(this,arguments,function*(n,r=[ce.AUDIO]){return Ka(n,r)})}function Ka(n,r,e){return c(this,null,function*(){if(U.current())throw d.error("There is already active call"),new V(w.FAILED);return new U(se,Ut(),ri).onJoin({conversationId:n,mediaOptions:r,chatId:e})})}function Bs(a){return c(this,arguments,function*(n,r=[ce.AUDIO],e,t,i){if(U.current())throw d.error("There is already active call"),new V(w.FAILED);return e&&(l.anonymToken=e),new U(se,Ut(),ri).onJoin({joinLink:n,mediaOptions:r,observedIds:t,payload:i})})}function Vs(){return c(this,null,function*(){let n=U.current();if(n)return n.hangup();U.hangupAfterInit()})}function Fs(n,r){return c(this,null,function*(){let e=yield se.getOkIdsByExternalIds([n]);if(!e.length)throw new Error("User not found");return $a(e[0],r)})}function $a(n,r){return c(this,null,function*(){let e=U.current();e&&(yield e.addParticipant(E.composeUserId(n,z.USER),r))})}function js(n,r=!1){return c(this,null,function*(){let e=yield se.getOkIdsByExternalIds([n]);return qa(e[0],r)})}function qa(n,r=!1){return c(this,null,function*(){let e=U.current();e&&(yield e.removeParticipant(E.composeUserId(n,z.USER),r))})}function Hs(n,r){return c(this,null,function*(){let e=U.current();return n==="videoinput"&&Je.contains(r)?(l.videoFacingMode=r,e?(C.isMobile()&&(yield e.stopVideoTrack()),e.changeDevice(n)):Promise.reject()):(yield C.saveDeviceId(n,r))&&e?e.changeDevice(n):Promise.reject()})}function Gs(n){return c(this,null,function*(){let r=typeof n=="object"?Ye(Ce({},n),{fastScreenSharing:n.captureScreen&&n.fastScreenSharing,captureAudio:n.captureScreen&&n.captureAudio&&l.audioShare}):{captureScreen:n,fastScreenSharing:!1,captureAudio:!1},e=U.current();return e?e.toggleScreenCapturing(r):Promise.reject()})}function Ws(n){let r=U.current();r&&r.toggleAnimojiCapturing(n)}function Ks(n,r=!1){return c(this,null,function*(){let e=U.current();e&&(yield e.setVideoStream(n,r))})}function $s(n){return c(this,null,function*(){let r=U.current();r&&(yield r.toggleLocalVideo(n))})}function qs(n){return c(this,null,function*(){let r=U.current();r&&(yield r.toggleLocalAudio(n))})}function Js(n){return c(this,null,function*(){let r=U.current();if(r)return r.setLocalResolution(n)})}function zs(n){return c(this,null,function*(){let r=U.current();r&&(yield r.changePriorities(n))})}function Ys(n){return c(this,null,function*(){let r=U.current();r&&(yield r.changeParticipantState(n))})}function Qs(n){return c(this,null,function*(){let r=U.current();r&&(yield r.updateDisplayLayout(n))})}function Xs(n,r,e=!1){return c(this,null,function*(){let t=yield se.getOkIdsByExternalIds([n]);return Ja(t[0],r,e)})}function Ja(n,r,e=!1){return c(this,null,function*(){let t=U.current();t&&(yield t.grantRoles(E.composeUserId(n,z.USER),r,e))})}function Zs(i){return c(this,arguments,function*({externalId:n=null,muteStates:r,requestedMedia:e=[],roomId:t=null}){let a=null;return n&&(a=(yield se.getOkIdsByExternalIds([n]))[0]),za({uid:a,muteStates:r,requestedMedia:e,deviceIdx:pe.getDeviceIdx(n),roomId:t})})}function za(a){return c(this,arguments,function*({uid:n=null,muteStates:r,requestedMedia:e=[],deviceIdx:t=0,roomId:i=null}){let s=U.current();if(s){let o=n?E.composeParticipantId(n,z.USER,t):null;yield s.muteParticipant(o,r,e,i)}})}function eo(n,r=!1){return c(this,null,function*(){let e=yield se.getOkIdsByExternalIds([n]);return Ya(e[0],r,pe.getDeviceIdx(n))})}function Ya(n,r=!1,e=0){return c(this,null,function*(){let t=U.current();t&&(yield t.pinParticipant(E.composeParticipantId(n,z.USER,e),r))})}function to(n){return c(this,null,function*(){let r=U.current();r&&(yield r.updateMediaModifiers(n))})}function io(n){return c(this,null,function*(){let r=U.current();r&&(yield r.changeOptions(n))})}function ro(n,r=null){return c(this,null,function*(){let e=null;return r&&(e=(yield se.getOkIdsByExternalIds([r]))[0]),Qa(n,e)})}function Qa(n,r=null){return c(this,null,function*(){let e=U.current();if(e){let t=r?E.composeUserId(r,z.USER):null;yield e.chatMessage(n,t)}})}function ao(n=10){return c(this,null,function*(){let r=U.current();if(r)return r.chatHistory(n)})}function no(n,r=null){return c(this,null,function*(){let e=null;return r&&(e=(yield se.getOkIdsByExternalIds([r]))[0]),Xa(n,e,pe.getDeviceIdx(r))})}function Xa(n,r=null,e=0){return c(this,null,function*(){let t=U.current();if(t){let i=r?E.composeParticipantId(r,z.USER,e):null;yield t.customData(n,i)}})}function so(){return c(this,arguments,function*(n="",r=!1,{onlyAdminCanShareMovie:e=!1}={}){return(yield se.createConversation(E.uuid(),n,r,{onlyAdminCanShareMovie:e})).join_link})}function oo(){return c(this,null,function*(){let n=U.current();return n?n.createJoinLink():Promise.reject()})}function co(){return c(this,null,function*(){let n=U.current();return n?n.removeJoinLink():Promise.reject()})}function lo(n,r){return c(this,null,function*(){return se.getAnonymTokenByLink(n,r)})}function po(n){let r=U.current();r&&r.setVolume(n)}function uo(n){l.forceRelayPolicy=n}function mo(n=!1,r=null,e=null,t="DIRECT_LINK",i=null,a=null){return c(this,null,function*(){let s=U.current();return s?s.startStream(n,r,e,t,i,a):Promise.reject()})}function ho(n=null){return c(this,null,function*(){let r=U.current();return r?r.stopStream(n):Promise.reject()})}function _o(n,r,e=null){return c(this,null,function*(){let t=U.current();if(t){let i=yield se.getOkIdsByExternalIds([n]),a=pe.getDeviceIdx(n);return t.recordSetRole(E.composeParticipantId(i[0],z.USER,a),r,e)}return Promise.reject()})}function go(){return c(this,null,function*(){let n=U.current();return n?n.getStreamInfo():Promise.reject()})}function fo(n){return c(this,null,function*(){let r=U.current();return r?r.addMovie(n):Promise.reject()})}function So(n){return c(this,null,function*(){let r=U.current();return r?r.updateMovie(n):Promise.reject()})}function vo(n){return c(this,null,function*(){let r=U.current();return r?r.removeMovie(n):Promise.reject()})}function Eo(n,r){return c(this,null,function*(){let e=U.current();if(e){let t=[];for(let i of n){let a,s;i.addParticipantIds&&(a=(yield se.getOkIdsByExternalIds(i.addParticipantIds)).map(o=>E.composeUserId(o,z.USER))),i.removeParticipantIds&&(s=(yield se.getOkIdsByExternalIds(i.removeParticipantIds)).map(o=>E.composeUserId(o,z.USER))),t.push({id:i.id,name:i.name,participantCount:i.participantCount,addParticipantIds:a,removeParticipantIds:s})}return e.updateRooms(t,r)}return Promise.reject()})}function Io(n,r){return c(this,null,function*(){let e=U.current();return e?e.activateRooms(n,r):Promise.reject()})}function To(n=null,r=null){return c(this,null,function*(){let e=null;if(r){let i=yield se.getOkIdsByExternalIds([r]);e=E.composeUserId(i[0],z.USER)}let t=U.current();return t?t.switchRoom(n,e):Promise.reject()})}function Ro(n){return c(this,null,function*(){let r=U.current();return r?r.removeRooms(n):Promise.reject()})}function Co(n){l.statisticsInterval=n;let r=U.current();if(r)return r.updateStatisticsInterval()}function Po(n){Rr.default.disableLog(!n),d.toggle(n)}function yo(n,...r){l.debugLog&&d.send(n,"[external]",...r)}function bo(n){return c(this,null,function*(){let r=U.current();if(r)return r.videoEffect(n)})}function Mo(n){return c(this,null,function*(){let r=U.current();r&&(yield r.setAudioStream(n))})}function Ao(n,r=null,e=null){return c(this,null,function*(){let t=U.current();if(!t)return;let i=e!=null?e:r==null?void 0:r.id,a=null;if(r){let o=(yield se.getOkIdsByExternalIds([r]))[0];if(!o)throw new Error("Could not get user id to set animoji svg");a=E.composeParticipantId(o,z.USER,pe.getDeviceIdx(r))}t.setAnimojiSvg(n,a,i)})}function Do(n=null,r,e=!1){return c(this,null,function*(){return vt().getWaitingHall(n,r,e)})}function ko(n,r=!1){return c(this,null,function*(){let e=vt(),t=yield se.getOkIdsByExternalIds([n]);return e.promoteParticipant(E.composeUserId(t[0],z.USER),r)})}function Oo(n){return c(this,null,function*(){return vt().getParticipantListChunk(n)})}function wo(n){return c(this,null,function*(){return vt().getParticipants(n)})}function xo(n){return c(this,null,function*(){return vt().feedback(n)})}function Lo(n,r){return c(this,null,function*(){return vt().enableFeatureForRoles(n,r)})}function vt(){let n=U.current();if(!n)throw new Error("Conversation not found");return n}function No(n){return c(this,null,function*(){yield se.removeHistoryRecords(n)})}function Uo(n){return c(this,null,function*(){let r=U.current();r&&(yield r.startAsr(n))})}function Bo(){return c(this,null,function*(){let n=U.current();n&&(yield n.stopAsr())})}function Vo(n){return c(this,null,function*(){let r=U.current();r&&(yield r.requestAsr(n))})}function Fo(){return l.sdkVersion}