@vkontakte/calls-sdk 2.6.2-dev.3549b06.0 → 2.6.2-dev.4163bb9.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 +8 -9
- package/calls-sdk.esm.js +8 -9
- package/classes/screenshare/ScreenCaptureSender.d.ts +0 -1
- package/package.json +1 -1
- package/static/External.d.ts +3 -1
- package/static/Params.d.ts +1 -1
- package/static/Utils.d.ts +0 -1
- package/types/SignalingMessage.d.ts +2 -0
- package/types/Timer.d.ts +0 -18
- package/utils/Timer.d.ts +0 -26
- package/worker/TimerWorker.d.ts +0 -3
package/calls-sdk.cjs.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/calls-sdk v2.6.2-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/calls-sdk v2.6.2-dev.4163bb9.0
|
|
3
|
+
* Thu, 22 Sep 2022 16:22:10 GMT
|
|
4
4
|
* https://st.mycdn.me/static/callssdk/2-6-2/doc/
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
var Ba=Object.create;var It=Object.defineProperty,Va=Object.defineProperties,Fa=Object.getOwnPropertyDescriptor,Ga=Object.getOwnPropertyDescriptors,Ha=Object.getOwnPropertyNames,dr=Object.getOwnPropertySymbols,Wa=Object.getPrototypeOf,pr=Object.prototype.hasOwnProperty,ja=Object.prototype.propertyIsEnumerable;var lr=Math.pow,ur=(a,e,t)=>e in a?It(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,st=(a,e)=>{for(var t in e||(e={}))pr.call(e,t)&&ur(a,t,e[t]);if(dr)for(var t of dr(e))ja.call(e,t)&&ur(a,t,e[t]);return a},_i=(a,e)=>Va(a,Ga(e)),mr=a=>It(a,"__esModule",{value:!0});var Ka=(a,e)=>{mr(a);for(var t in e)It(a,t,{get:e[t],enumerable:!0})},qa=(a,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ha(e))!pr.call(a,i)&&i!=="default"&&It(a,i,{get:()=>e[i],enumerable:!(t=Fa(e,i))||t.enumerable});return a},Ye=a=>qa(mr(It(a!=null?Ba(Wa(a)):{},"default",a&&a.__esModule&&"default"in a?{get:()=>a.default,enumerable:!0}:{value:a,enumerable:!0})),a);var o=(a,e,t)=>new Promise((i,r)=>{var n=l=>{try{d(t.next(l))}catch(h){r(h)}},s=l=>{try{d(t.throw(l))}catch(h){r(h)}},d=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,s);d((t=t.apply(a,e)).next())});Ka(exports,{Api:()=>Bt,BaseApi:()=>ot,BaseLogger:()=>ct,BaseSignaling:()=>dt,CallDirection:()=>We,CallType:()=>Be,ChatRoomEventType:()=>Gt,ConversationOption:()=>Ht,DebugMessageType:()=>Hi,ExternalIdType:()=>tt,FacingMode:()=>Oi,FatalError:()=>ee,HangupReason:()=>x,HangupType:()=>A,MediaOption:()=>ne,MediaTrackKind:()=>ie,MediaType:()=>ve,MuteState:()=>je,ParticipantState:()=>W,ParticipantStatus:()=>$,RecordRole:()=>ya,Signaling:()=>xe,SignalingCommandType:()=>U,SignalingConnectionType:()=>Ve,SignalingNotification:()=>w,UserRole:()=>ze,UserType:()=>Y,Utils:()=>_,acceptCall:()=>rs,addMovie:()=>Us,addParticipant:()=>cs,addParticipantInternal:()=>Aa,authorize:()=>is,browser:()=>zn,callInternal:()=>ba,callTo:()=>es,captureScreen:()=>ls,changeConversationOptions:()=>Cs,changeDevice:()=>ps,changeParticipantState:()=>fs,changePriorities:()=>gs,changeVideoEffect:()=>Ws,chatHistory:()=>Ps,chatMessage:()=>ys,chatMessageInternal:()=>La,createJoinLink:()=>Ms,customData:()=>Rs,customDataInternal:()=>Na,debug:()=>Gs,debugMessage:()=>Hs,declineCall:()=>as,forceRelayPolicy:()=>Os,getAnonymTokenByLink:()=>As,getParticipantListChunk:()=>$s,getParticipants:()=>Js,getStreamInfo:()=>Ns,getWaitingHall:()=>Ks,grantRoles:()=>vs,grantRolesInternal:()=>Oa,hangup:()=>os,init:()=>Zn,joinCall:()=>ns,joinCallByLink:()=>ss,joinCallInternal:()=>Da,muteParticipant:()=>Es,muteParticipantInternal:()=>wa,pinParticipant:()=>Ts,pinParticipantInternal:()=>xa,processPush:()=>ts,processPushInternal:()=>Ma,promoteParticipant:()=>qs,recordSetRole:()=>Ls,removeHistoryRecords:()=>Ys,removeJoinLink:()=>Ds,removeMovie:()=>Vs,removeParticipant:()=>ds,removeParticipantInternal:()=>ka,setApi:()=>Pa,setAudioStream:()=>js,setLocalResolution:()=>_s,setLogger:()=>Qn,setMediaModifiers:()=>Is,setSignalingFactory:()=>Ra,setStatisticsInterval:()=>Fs,setVideoEffects:()=>Xn,setVideoStream:()=>us,setVolume:()=>ks,startConversation:()=>bs,startStream:()=>ws,stopStream:()=>xs,toggleLocalAudio:()=>hs,toggleLocalVideo:()=>ms,updateDisplayLayout:()=>Ss,updateMovie:()=>Bs,version:()=>zs});var rr=Ye(require("webrtc-adapter"));var ot=class{createJoinLink(e){return o(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return o(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return o(this,null,function*(){return""})}log(e){}prepareUserIds(e){return o(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return o(this,null,function*(){})}cleanup(){}};var ct=class{log(e,t,i=!1){}destroy(){}};var Q=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var dt=class extends Q{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e,t){}getNextCommandSequenceNumber(){return 0}};var hr=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(hr||{}),We=hr;var _r=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(_r||{}),Be=_r;var gr=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(gr||{}),Gt=gr;var fr=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(fr||{}),Sr=fr;var vr=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(vr||{}),Ht=vr;function Er(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function Tr(a,e){let t=new Set(a);for(let[i,r]of Object.entries(e))r?t.add(i):t.delete(i);return Array.from(t)}var Ir=(q=>(q.CAMERA_PERMISSION="camera",q.MIC_PERMISSION="mic",q.CAMERA_ACCESS="cameralock",q.MIC_ACCESS="miclock",q.MIC_NOT_FOUND="nomic",q.SCREEN_PERMISSION="screenpermission",q.SCREEN_ACCESS="screenlock",q.CONNECTION="connection",q.NETWORK="network",q.UNKNOWN="unknown",q.UNSUPPORTED="unsupported",q.SIGNALING_FAILED="signalingfailed",q.API="api",q.AUTH="auth",q))(Ir||{}),ee=Ir;var Cr=(J=>(J.CANCELED="CANCELED",J.REJECTED="REJECTED",J.REMOVED="REMOVED",J.HUNGUP="HUNGUP",J.MISSED="MISSED",J.BUSY="BUSY",J.FAILED="FAILED",J.NETWORK_ERROR="NETWORK_ERROR",J.KILLED="KILLED",J.BANNED="BANNED",J.HAS_ACTIVE_CALL="HAS_ACTIVE_CALL",J.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",J.NOT_FRIENDS="NOT_FRIENDS",J.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",J.UNKNOWN_ERROR="UNKNOWN_ERROR",J.UNSUPPORTED="UNSUPPORTED",J.OLD_VERSION="OLD_VERSION",J.SERVICE_DISABLED="SERVICE_DISABLED",J.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",J.SOCKET_CLOSED="SOCKET_CLOSED",J.ENDED="ENDED",J.KILLED_WITHOUT_DELETE="KILLED_WITHOUT_DELETE",J))(Cr||{}),A=Cr;var yr=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(yr||{}),ne=yr;var Pr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(Pr||{}),je=Pr;var Rr=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(Rr||{}),W=Rr;var br=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(br||{}),Ve=br;var Mr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(Mr||{}),ge=Mr;var Dr=(D=>(D.TRANSMITTED_DATA="transmitted-data",D.ACCEPTED_CALL="accepted-call",D.HUNGUP="hungup",D.PARTICIPANT_ADDED="participant-added",D.PARTICIPANT_JOINED="participant-joined",D.CLOSED_CONVERSATION="closed-conversation",D.MEDIA_SETTINGS_CHANGED="media-settings-changed",D.PARTICIPANT_STATE_CHANGED="participant-state-changed",D.RATE_CALL_DATA="rate-call-data",D.FEATURE_SET_CHANGED="feature-set-changed",D.TOPOLOGY_CHANGED="topology-changed",D.PRODUCER_UPDATED="producer-updated",D.CONSUMER_ANSWERED="consumer-answered",D.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",D.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",D.SETTINGS_UPDATE="settings-update",D.VIDEO_QUALITY_UPDATE="video-quality-update",D.REGISTERED_PEER="registered-peer",D.SWITCH_MICRO="switch-micro",D.RECORD_STARTED="record-started",D.RECORD_STOPPED="record-stopped",D.REALLOC_CON="realloc-con",D.AUDIO_ACTIVITY="audio-activity",D.SPEAKER_CHANGED="speaker-changed",D.STALLED_ACTIVITY="stalled-activity",D.CHAT_MESSAGE="chat-message",D.CUSTOM_DATA="custom-data",D.ROLES_CHANGED="roles-changed",D.MUTE_PARTICIPANT="mute-participant",D.PIN_PARTICIPANT="pin-participant",D.OPTIONS_CHANGED="options-changed",D.NETWORK_STATUS="network-status",D.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",D.PROMOTE_PARTICIPANT="promote-participant",D.CHAT_ROOM_UPDATED="chat-room-updated",D.PROMOTION_APPROVED="promotion-approved",D.JOIN_LINK_CHANGED="join-link-changed",D))(Dr||{}),w=Dr;var Ar=(K=>(K.ERROR="callError",K.DEVICES="callDevices",K.CALL_SPEC_ERROR="callSpecError",K.ICE_CONNECTION_STATE="callIceConnectionState",K.ICE_CONNECTION_TYPE="callIceConnectionType",K.ICE_RESTART="callIceRestart",K.PUSH="callPush",K.OUTGOING_CALL="callStart",K.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",K.JOIN_CONVERSATION="callJoinConversation",K.ACCEPTED_OUTGOING="callAcceptedOutgoing",K.ACCEPT_INCOMING="callAcceptIncoming",K.DECLINE_INCOMING="callDeclineIncoming",K.ACCEPT_CONCURRENT="callAcceptConcurrent",K.HANGUP="callHangup",K.MEDIA_STATUS="callMediaStatus",K.DEVICE_CHANGED="callDeviceChanged",K.SOCKET_ACTION="callSocketAction",K.ADD_PARTICIPANT="callAddParticipant",K.REMOVE_PARTICIPANT="callRemoveParticipant",K.POOR_CONNECTION="callPoorConnection",K.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",K.RELAY_POLICY="callForceRelay",K.PAT_ALLOCATED="patAllocate",K.PAT_DEALLOCATED="patDeallocate",K.PAT_ERROR="patError",K.PAT_WAITING_TIME_ERROR="patWaitingTimeError",K.PAT_OUTDATED_RESPONSE="patOutdatedResponse",K))(Ar||{}),v=Ar;var kr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(kr||{}),Oe=kr;var Or=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(Or||{}),wr=Or;function xr(a){switch(a){case 1:return"no-available-tracks";default:return"unknown-error"}}var Lr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(Lr||{}),ze=Lr;function Ct(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var Nr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(Nr||{}),Y=Nr;var gi=class{constructor(){this._items=[]}get length(){return this._items.length}push(e){this._items.push(e)}shift(){return this._items.shift()||null}bisect(){let e=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(e)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(e,t)=>t instanceof Error?String(t):t):""}};var Ur=2*1024*1024,$a=512*1024,yt=100*1024,Ja=5,fi="_okcls_logs_session_",Ya=3e4,Br=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=Ur;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(fi)!==0)continue;let i=e.getItem(t);if(!i){Gr(t);continue}let r=Fr(i);this.add(t,r)}}catch(e){console.error("Storage is blocked",e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(yt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(fi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Gr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>Ur||this.length>Ja-1||this.size+e>this.available);)this.deleteOldestItem()}};function Vr(){return`${fi}${Date.now()}`}function Fr(a){return new Blob([a]).size}function Gr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function Si(){let a=Qe.toString();if(!Se.available||!a)return;let e=Fr(a);Se.cleanup(e);try{window.localStorage.setItem(Wt,a)}catch(t){if(console.warn("Failed to write log to storage",t),Se.storageSize=Se.size+e,Se.cleanup(yt+e),Se.available>=yt+e){Si();return}if(e>yt){Qe.bisect(),Si();return}Se.storageSize=0;return}e>$a&&(Se.add(Wt,e),Wt=Vr(),Qe.clear(),Se.cleanup(yt))}function vi(){!Se.available||!Qe.length||Si()}function za(a=!1){let e=[];try{let r=window.localStorage;for(let s of Se.items){let d=r.getItem(s.key);e.push(d)}let n=Qe.toString();n&&e.push(n)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(a)return t;let i=`logs_${Date.now()}.json`;return Qa(t,i),i}function Qa(a,e){let t=document.createElement("a"),i=new Blob([a],{type:"text/json"});t.href=URL.createObjectURL(i),t.download=e,t.click()}function Hr(a,e){!Se.available||(Qe.push({t:Date.now(),l:a,d:e}),Ti||(Ti=window.setTimeout(()=>{Ti=null,vi()},Ya)))}function Ei(){Se||(Se=new Br,Qe=new gi,Wt=Vr(),window.addEventListener("beforeunload",vi))}var Se,Qe,Wt,Ti=null;window.__VKCallsSDKLogs__=(a=!1)=>(Se||Ei(),vi(),za(a));var Ni=Ye(require("@vkontakte/libvpx"));var fe=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(fe||{});var Ii="_okcls_",pt=(()=>{try{let a=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(a,a),t=e.getItem(a)===a,e.removeItem(a),t?e:null}catch(a){return null}})();function Za(a){let e=pt?pt.getItem(Ii+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function en(a,e){try{pt&&pt.setItem(Ii+a,JSON.stringify(e))}catch(t){}}function tn(a){pt&&pt.removeItem(Ii+a)}var Ci;(i=>{function a(r){return Za(r)||null}i.get=a;function e(r,n){en(r,n)}i.set=e;function t(r){tn(r)}i.remove=t})(Ci||(Ci={}));var qe=Ci;var Xe=null,yi=null,jt=[],Kt=[],Pi=[],Pt=null,Rt=null,Ri=null,bi=!1,Mi=!1,qt,lt,$t,Wr=!1,jr=!1,Di=null,Ai="",Jt=[],ki=null,Kr=navigator.appVersion,rn=navigator.appName,Ie=navigator.userAgent,Oi=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(Oi||{}),bt=class{constructor(e,t=!1,i=p.videoMaxWidth,r=p.videoMaxHeight){let n=!1;if(e){n={noiseSuppression:p.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let d;Rt&&(d=Rt.deviceId),typeof e=="string"&&(d=e),d&&(n.deviceId={ideal:d})}let s=!1;if(t){s={width:{min:p.videoMinWidth,max:i,ideal:i},height:{min:p.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:p.videoAspectRatio},frameRate:{ideal:p.videoFrameRate}};let d;Pt&&(d=Pt.deviceId),typeof t=="string"&&(d=t),d&&(s.deviceId={ideal:d}),p.videoFacingMode&&(s.facingMode={ideal:p.videoFacingMode})}this.audio=n,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},qr=class extends bt{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=p.screenFrameRate}};function an(){return o(this,null,function*(){Xe=null,yield Yt()})}function nn(){Xe=null,Yt().then(()=>E.onDeviceChange())}function Yt(){return o(this,null,function*(){return Xe||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!yi&&navigator.mediaDevices.addEventListener&&(yi=_.throttle(nn,1e3),navigator.mediaDevices.addEventListener("devicechange",yi)),Xe=navigator.mediaDevices.enumerateDevices().then(a=>{jt=a.filter(r=>r.kind==="videoinput"?(r.label&&(bi=!0),!0):!1),Kt=a.filter(r=>r.kind==="audioinput"?(r.label?Mi=!0:Ze.isMobile()&&Ze.browserName()==="Firefox"&&(Mi=bi),!0):!1),Pi=a.filter(r=>r.kind==="audiooutput");let e=qe.get("videoinput"),t=qe.get("audioinput"),i=qe.get("audiooutput");return Pt=jt.find(r=>r.deviceId===e)||null,Rt=Kt.find(r=>r.deviceId===t)||null,Ri=Pi.find(r=>r.deviceId===i)||null,Xe=Promise.resolve(a),a}).catch(()=>(Xe=null,[]))))})}function sn(){return o(this,null,function*(){return Ze.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(Wr=!0),/^a=mid:0$/m.test(t.sdp)&&(jr=!0),a()}).catch(a)}):Promise.resolve()})}function zt(a,e){return o(this,null,function*(){c.debug("Try to get media",a.getNative());let t=Ze.hasPermissions(a.isVideo());!t&&!e&&E.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield an()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?ee.CAMERA_PERMISSION:ee.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?ee.CAMERA_ACCESS:ee.MIC_ACCESS;break}if(a.canSimplify())return zt(a.simplify(),e);let r=e||ee.UNKNOWN;throw E.onPermissionsError(r),r}})}function on(a){return o(this,null,function*(){c.debug("Try to get screen",a.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(a.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(c.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw ee.SCREEN_PERMISSION;default:throw ee.SCREEN_ACCESS}}})}function Qt(){return Jt.length||(Jt=(()=>{let a,e=!1,t=0,i="0",r=Ie.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return a=/\brv[ :]+(\d+)/g.exec(Ie),["IE",a&&a[1]||"Unknown",e,t,i];if(r[1]==="Safari"){if(a=Ie.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(a=Ie.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,Number(a[1]),i];if(a=Ie.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t,i];if(a=Ie.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t,i];if(a=Ie.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t,i]}if(r[1]==="Chrome"){if(e=!0,t=Number(r[2]),a=Ie.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t,i];if(a=Ie.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t,i];if(a=Ie.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t,i];if(a=Ie.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t,i]}return a=Ie.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),a&&a[2]!==void 0&&(i=a[2]),[r[2]?r[1]:rn,a&&a[1]||r[2]||Kr,e,t,i]})()),Jt}var Ze;(k=>{function a(){return o(this,null,function*(){return yield sn(),Yt()})}k.init=a;function e(){return jt}k.getCameras=e;function t(){return Kt}k.getMicrophones=t;function i(){return Pi}k.getOutput=i;function r(){return jt.length>0}k.hasCamera=r;function n(){return Kt.length>0}k.hasMicrophone=n;function s(){return Pt}k.getSavedCamera=s;function d(){return Rt}k.getSavedMicrophone=d;function l(){return Ri}k.getSavedOutput=l;function h(){return bi}k.hasCameraPermission=h;function C(){return Mi}k.hasMicrophonePermission=C;function P(S=!1){return C()?r()&&S?h():!0:!1}k.hasPermissions=P;function L(S=!1,O=!0,M=!0){return o(this,null,function*(){let D=n()&&O,Ee=r()&&S,_e;if(!D&&!Ee)_e=new MediaStream;else try{_e=yield zt(new bt(D,Ee))}catch(ye){_e=new MediaStream}return!_e.getVideoTracks().length&&M&&_e.addTrack(Je()),!_e.getAudioTracks().length&&M&&_e.addTrack(de()),_e})}k.getUserMedia=L;function F(){return o(this,null,function*(){return on(new qr(window.screen.width,window.screen.height))})}k.getScreenMedia=F;function q(S,O=!1){return o(this,null,function*(){let M=O?p.videoEffectMaxWidth:p.videoMaxWidth,D=O?p.videoEffectMaxHeight:p.videoMaxHeight;return zt(new bt(!1,S||!0,M,D))})}k.getUserVideo=q;function ue(S){return o(this,null,function*(){return zt(new bt(S||!0,!1))})}k.getUserAudio=ue;function Le(S,O){return o(this,null,function*(){let D=(yield Yt()).find(Ee=>Ee.kind===S&&Ee.deviceId===O);return D?(S==="videoinput"?Pt=D:S==="audioinput"?Rt=D:S==="audiooutput"&&(Ri=D),qe.set(S,O),D):null})}k.saveDeviceId=Le;function de(){if(!$t||$t.readyState==="ended"){let S=I(),O=S.createMediaStreamDestination(),M=S.createGain();M.gain.value=1e-5,M.connect(O),M.connect(S.destination);let D=S.createOscillator();D.type="sine",D.frequency.value=0,D.connect(M),D.start(),$t=O.stream.getAudioTracks()[0]}return Object.assign($t.clone(),{enabled:!1})}k.getSilentMediaTrack=de;function Je(S=p.videoMinWidth,O=p.videoMinHeight){return lt||(lt=document.createElement("canvas"),lt.getContext("2d")),lt.width=S,lt.height=O,(!qt||qt.readyState==="ended")&&(qt=lt.captureStream(p.videoFrameRate).getVideoTracks()[0]),Object.assign(qt.clone(),{enabled:!1})}k.getBlackMediaTrack=Je;function ce(){if(K()==="Edge"&&Number(ui())<70)return!1;try{let S=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&S.RTCPeerConnection&&S.RTCIceCandidate&&S.RTCSessionDescription&&S.HTMLCanvasElement&&S.HTMLCanvasElement.prototype.captureStream&&S.RTCRtpSender&&S.RTCRtpSender.prototype.replaceTrack&&S.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(S){return!1}}k.isBrowserSupported=ce;function Me(){return!!navigator.mediaDevices.getDisplayMedia}k.isScreenCapturingSupported=Me;function De(){return Wr}k.canVP8=De;function J(){return jr}k.isUnifiedPlan=J;function ar(){let S=k.browserName()==="Safari"&&k.browserVersion()==="15"&&k.browserSubVersion()==="1",O=k.browserName()==="Opera"&&k.os()==="Windows";return S||O}k.isBrokenH264=ar;function nr(){return!(k.baseChromeVersion()&&k.isMobile())}k.canPreferH264=nr;function sr(){var S;return((S=window.RTCRtpTransceiver)==null?void 0:S.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}k.canPreferRed=sr;function or(){return Ai||(Ai=(()=>{let S={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let O in S)if(S.hasOwnProperty(O)&&S[O].test(Ie))return O;return"Unknown"})()),Ai}k.os=or;function cr(){return Di===null&&(Di=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Kr)),Di}k.isMobile=cr;function K(){return Qt()[0]}k.browserName=K;function ui(){return Qt()[1]}k.browserVersion=ui;function f(){return Qt()[3]}k.baseChromeVersion=f;function I(){return ki||(ki=new(window.AudioContext||window.webkitAudioContext)),ki}k.getAudioContext=I;function b(){return Qt()[4]}k.browserSubVersion=b})(Ze||(Ze={}));var y=Ze;function $r(a,e){if(a.isAudioEnabled!==e.isAudioEnabled||a.isVideoEnabled!==e.isVideoEnabled||a.isScreenSharingEnabled!==e.isScreenSharingEnabled||a.videoStreams.length!==e.videoStreams.length)return!1;for(let t of a.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function me(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}var Jr=a=>a.stop(),Yr=a=>a.getTracks().forEach(Jr),wi=a=>a.getVideoTracks().forEach(Jr),zr=a=>a.getVideoTracks()[0].clone();var x=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(A).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,x)}};var m=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 r={};typeof t!="undefined"&&(r.param=t),this._logInternal(e,r,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){m._instance||(m._instance=new m(e,t))}static log(e,t,i=!1){m._instance&&m._instance.log(e,t,i)}static logCustom(e,t,i=!1){m._instance&&m._instance.logCustom(e,t,i)}static destroy(){m._instance&&m._instance.destroy(),m._instance=null}};var Ce=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(Ce||{}),ie=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(ie||{}),xi=class extends Q{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=me();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return o(this,arguments,function*(e=[ne.AUDIO],t=!0){if(this._stream)return;let i=e.includes(ne.VIDEO),r=e.includes(ne.AUDIO);if(!y.isBrowserSupported())throw new x(ee.UNSUPPORTED);try{this._stream=yield y.getUserMedia(i,r,t),this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(n=>n.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=r&&this._stream.getAudioTracks().filter(n=>n.enabled).length>0||!1}catch(n){throw new x(n)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t,i,r){let n=this.getStream(),s=this._getSendAudioTrack(),d=this.getSendVideoTrack(i);if(!n||!s&&!d&&!t)throw new Error("No local stream found");if(s&&!t){if(r){let{codecs:l}=RTCRtpSender.getCapabilities("audio"),h="audio/red",C=48e3,P=l.findIndex(L=>L.mimeType===h&&L.clockRate===C);if(P>=0){let L=[];L.push(l[P]);for(let F=0;F<l.length;F++)F!==P&&L.push(l[F]);e.getTransceivers().forEach(F=>F.setCodecPreferences(L))}}e.addTrack(s,n)}d&&!t&&e.addTrack(d,n)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return o(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return o(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=_.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);this._onDeviceChange=()=>o(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),s=n&&n.deviceId,d=this._stream.getVideoTracks()[0],l=d&&d.enabled&&d.getSettings(),h=l&&l.deviceId;if(!s&&!h)return;let C=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!C.find(P=>P.deviceId===s)),!t&&h&&(t=!C.find(P=>P.deviceId===h)),i()}),navigator.mediaDevices.addEventListener("devicechange",this._onDeviceChange)}_destroyDeviceChangeListener(){this._onDeviceChange&&navigator.mediaDevices.removeEventListener("devicechange",this._onDeviceChange)}_changeVideoInput(e=null){return o(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield y.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{p.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),n=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),m.log(v.DEVICE_CHANGED,t),c.log("Video stream changed"),yield this._replaceLocalTrack(n),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(v.ERROR,"change_video"),c.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=zr(e)),t=this._trackVideoStreamBackup.clone(),wi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),wi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return o(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return o(this,null,function*(){try{if(e=e||(yield y.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),m.log(v.DEVICE_CHANGED,"audio"),c.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(v.ERROR,"change_audio"),c.error("Microphone change failed",t),t}})}_changeScreen(e){return o(this,null,function*(){try{if(e=e||(yield y.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=p.consumerScreenTrack?t:yield this._videoEffect(null,t);m.log(v.DEVICE_CHANGED,"screen"),c.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,p.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=p.consumerScreenDataChannel?y.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(v.ERROR,"screen"),c.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return o(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,n;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(n=this._stream)==null||n.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return o(this,null,function*(){if(!p.videoEffects)return t;try{return m.log(v.DEVICE_CHANGED,`effect_${e}`),p.videoEffects.setEffect(e,t)}catch(i){return c.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){this._destroyDeviceChangeListener(),p.videoEffects&&(this._effect=null,p.videoEffects.destroy()),this._stream&&(Yr(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return o(this,null,function*(){return e?this._changeScreen():p.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return o(this,null,function*(){if(!this._stream)return;p.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield y.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=y.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return o(this,null,function*(){if(!this._stream)return;let t;e?t=(yield y.getUserAudio()).getAudioTracks()[0]:t=y.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return o(this,null,function*(){if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return o(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks()[0];if(!e)throw new Error("Local audio track not found");if(!!e.enabled)return e.applyConstraints({noiseSuppression:p.noiseSuppression})})}videoEffect(e){return o(this,null,function*(){if(!p.videoEffects)throw new Error("Video Effects library is not set");if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var ut=":",Xt="d",Li;(ui=>{function a(f,I,b,k,S=!1,O=!1){let M=/[\r\n]+/,D=`\r
|
|
8
|
-
`;if(!
|
|
9
|
-
`);for(let O of b)if(O.startsWith("a=fingerprint")){let M=O.split(" ");if(M.length===2){I=M[1];break}}if(!I)return BigInt(-1);let k=I.split(":"),S=BigInt(0);for(let O=Math.min(7,k.length-1);O>=0;O--){let M=BigInt(parseInt(k[O],16));S<<=BigInt(8),S|=M}return BigInt.asIntN(64,S)}ui.sdpFingerprint=ue;function Le(f){return o(this,null,function*(){return new Promise(I=>window.setTimeout(I,f))})}ui.delay=Le;function de(f,I,b){let k=[];return f.getSenders().forEach(S=>Je(I,S,S.track,b,k)),k}ui.applySettings=de;function Je(f,I,b,k,S){var O;if(f&&b&&b.kind===ie.video){let M=b.getSettings();if(M){let D=f.maxBitrateK?f.maxBitrateK*1024:null,Ee=M.width,_e=M.height,ye=Ee&&_e&&f.maxDimension?Math.max(1,Math.max(Ee,_e)/f.maxDimension):null,Pe=f.maxFramerate?f.maxFramerate:null,Ne=f.degradationPreference?f.degradationPreference:"balanced",Z=k[b.id];if(Z&&Z.bitrate===D&&Z.scaleResolutionDownBy===ye&&Z.maxFramerate===Pe&&Z.degradationPreference===Ne){S[b.id]=Z;return}S[b.id]={bitrate:D,scaleResolutionDownBy:ye,maxFramerate:Pe,degradationPreference:Ne};let Ae=I.getParameters();Ae.encodings||(Ae.encodings=[{}]),Ae.encodings.forEach(ke=>{D?ke.maxBitrate=D:delete ke.maxBitrate,ye?ke.scaleResolutionDownBy=ye:delete ke.scaleResolutionDownBy,Pe?ke.maxFramerate=Pe:delete ke.maxFramerate}),Ae.degradationPreference=Ne,(O=I.setParameters)==null||O.call(I,Ae)}}}ui.applyVideoTrackSettings=Je;function ce(f,I){Array.isArray(I)||(I=[I]);for(let b of I)if(f.includes(b))return!0;return!1}ui.includesOneOf=ce;function Me(f){var I;return Object.entries(((I=f.participantState)==null?void 0:I.state)||{}).reduce((b,[k,S])=>(f.participantState&&(b[k]={ts:f.participantState.stateUpdateTs[k],state:S}),b),{})}ui.mapParticipantState=Me;function De(f){let I=f.map(b=>({uid:b.externalId,mediaSettings:b.mediaSettings,status:b.status,muteStates:b.muteStates,unmuteOptions:b.unmuteOptions,participantState:b.participantState,markers:b.markers}));return p.filterObservers?I.filter(b=>!b.uid.observer):I}ui.mapSharedParticipants=De;function J(f,I){let b=Object.keys(f),k=Object.keys(I);if(b.length!==k.length)return!1;for(let S of b)if(!k.hasOwnProperty(S)||f[S].state!==I[S].state||f[S].ts!==I[S].ts)return!1;return!0}ui.isEqualParticipantState=J;function ar(f,I){let b=Object.keys(f),k=Object.keys(I);if(b.length!==k.length)return!1;for(let S of b)if(!I.hasOwnProperty(S)||f[S]!==I[S])return!1;return!0}ui.isObjectsEquals=ar;function nr(f,I){if(f.length!==I.length)return!1;for(let b of f)if(I.indexOf(b)<0)return!1;return!0}ui.isArraysEquals=nr;function sr(f){return!Object.keys(f).length}ui.isEmptyObject=sr;function or(f,I){if(!f&&!I)return 0;if(!f||!I)return f?-1:1;return k(I.rank,f.rank)||k(f.ts,I.ts)||b(f,I);function b(S,O){let M={[Y.USER]:0,[Y.GROUP]:1},{compositeUserId:D,deviceIdx:Ee}=L(S.id),{compositeUserId:_e,deviceIdx:ye}=L(O.id),{id:Pe,type:Ne}=P(D),{id:Z,type:Ae}=P(_e);return k(M[Ne],M[Ae])||k(Pe,Z)||k(Ee,ye)}function k(S,O){return S<O?-1:S===O?0:1}}ui.participantMarkerCompare=or;function cr(f,I){let b=Object.entries(f).filter(([,k])=>Array.isArray(I)?!I.includes(k):k!==I);return Object.fromEntries(b)}ui.objectFilterOutValues=cr;function K(f,I=[]){let b=I.join(","),k=new Blob([f,`exports.default(${b});`],{type:"application/javascript; charset=utf-8"});return window.URL.createObjectURL(k)}ui.createBlobWorker=K})(Li||(Li={}));var _=Li;var Fe=class{constructor(){this._worker=null}_createWorker(s,d){return o(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((l,h)=>{let C=_.createBlobWorker(e,i);this._worker=new Worker(C),this._worker.onmessage=P=>{switch(P.data.type){case fe.READY:l();break;case fe.ERROR:h(P.data.error);break;case fe.FRAME:t(P.data);break;case fe.DEBUG:c.debug(P.data.message);break;case fe.LOG_ERROR:m.log(v.ERROR,P.data.message);break}},this._sendToWorker(fe.INIT,r,n)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var mt=class extends Fe{init(e){return o(this,null,function*(){c.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var b=Object.defineProperty;var E=a=>b(a,"__esModule",{value:!0});var M=(a,p)=>{E(a);for(var e in p)b(a,e,{get:p[e],enumerable:!0})};var V={};M(V,{default:()=>D});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var D=(a,p)=>{let e=null,n=null,g=!0;function y(){return a({locateFile:p}).then(r=>n=r)}function s(r,m,l,R,x){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(x),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let d=e.getImageBuffer();if(!d){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let c=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(d.byteLength);if(i.set(d),R){let o=new ImageData(i,c,f);createImageBitmap(o,0,0,c,f).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:i.buffer,width:c,height:f},[i.buffer])}y().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return V;})();\n',t=>{if(t.error)c.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i)}else e(t.data)},[Ni.default,Ni.default.getUrl])})}decodeFrame(e,t,i,r){let n="ImageBitmap"in window;this._sendToWorker(fe.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:n,debug:c.enabled()},[t.buffer])}destroy(){this._removeWorker(),c.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var Ke=class extends Fe{init(e){return o(this,null,function*(){c.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var i=Object.defineProperty;var E=a=>i(a,"__esModule",{value:!0});var g=(a,e)=>{E(a);for(var t in e)i(a,t,{get:e[t],enumerable:!0})};var V={};g(V,{default:()=>D});var n=(t=>(t.VP9="vp09.00.50.08",t.VP8="vp8",t))(n||{}),o=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(o||{});var D=a=>{let e=null,t=!0;function p(){self.postMessage({type:o.READY})}function f(d,r,s,l=!1){if(!e||t!==s){if(!l){self.postMessage({type:o.DEBUG,message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}t=s,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${s?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${s?"VP9":"VP8"}`}),e=new VideoDecoder({output:c=>{let m=a?[c]:[];self.postMessage({type:o.FRAME,data:c},m),c.close()},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:s?n.VP9:n.VP8})}let u=new EncodedVideoChunk({type:l?"key":"delta",timestamp:d,data:r});e.decode(u)}self.onmessage=d=>{switch(d.data.type){case o.INIT:p();break;case o.FRAME:f(d.data.timestamp,d.data.data,d.data.isVP9,d.data.keyFrame);break}}};return V;})();\n',t=>{t.error?c.warn("WebCodecsDecoder",t.error):e(t.data)},[y.baseChromeVersion()>=92])})}decodeFrame(e,t,i,r=!1){this._sendToWorker(fe.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),c.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window}};var Qr=Ye(require("bit-buffer"));var cn=65536,et=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(c.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%cn!==e.sequence){c.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:n}=et.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:n})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((n,s)=>n+s.data.byteLength,0),i=new Uint8Array(t),r=0;for(let n of e)i.set(new Uint8Array(n.data),r),r+=n.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new Qr.BitStream(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),s=i.readBits(1)<<1|r;return s===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,s>=2&&i.index++,i.readBits(3)!==7?(i.index++,(s===1||s===3)&&(i.index+=3)):(s===1||s===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var ht=class{constructor(e){this._onStream=e}drawFrame(e){return o(this,null,function*(){throw new Error("Method `drawFrame` is not supported by this implementation")})}drawImage(e){throw new Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Mt=class extends ht{constructor(e){super(e);this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;c.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 o(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(),c.debug("CanvasRenderer destroyed")}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(y.browserName()==="Safari"&&Number(y.browserVersion())===15)}};var _t=class extends ht{constructor(e){super(e);c.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:ie.video}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}drawFrame(e){return o(this,null,function*(){yield this._writer.write(e)})}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),c.debug("TrackGeneratorRenderer destroyed")}static isBrowserSupported(){return"VideoFrame"in window&&"MediaStreamTrackGenerator"in window&&Ke.isBrowserSupported()}};var Dt=class extends et{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];c.debug(`StreamBuilder started for participant [${e}]`),_t.isBrowserSupported()?this._renderer=new _t(t):this._renderer=new Mt(t),Ke.isBrowserSupported()?this._decoder=new Ke:this._decoder=new mt;let i=r=>o(this,null,function*(){"VideoFrame"in window&&r instanceof VideoFrame?yield this._renderer.drawFrame(r):this._renderer.drawImage(r)});this._decoder.init(i).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._renderer.destroy(),c.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return Mt.isBrowserSupported()||_t.isBrowserSupported()}};var Zt=1,dn=1,Xr=0,ei=11,Zr=1,ea=2,ta=4,ia=8;function ra(a,e,t,i,r,n,s){let d=0;e&&(d|=Zr),t&&(d|=ea),i&&(d|=ta),s||(d|=ia);let l=new ArrayBuffer(ei),h=new DataView(l);if(h.setUint8(0,Zt),h.setUint16(1,r),h.setUint32(3,a),h.setUint8(7,n?1:0),h.setUint16(8,Xr),h.setUint8(10,d),!s)return l;let C=new Uint8Array(l.byteLength+s.byteLength);return C.set(new Uint8Array(l),0),C.set(new Uint8Array(s),l.byteLength),C.buffer}function aa(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,s=e.getUint16(8),d=e.getUint8(10),l=!!(d&Zr),h=!!(d&ea),C=!!(d&ta),P=!!(d&ia);if(t!==Zt)throw new Error(`Unexpected protocol version. Got ${t}, expected ${Zt}`);return{timestamp:r,start:l,end:h,keyframe:C,sequence:i,isVP9:n,ssrc:s,eos:P,data:a.slice(ei)}}function na(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==Zt||e.getUint8(1)!==dn||e.getUint16(2)!==Xr)}var T=Ye(require("simple-ebml-builder"));var pn=lr(2,15)-1,Ui=1,ln=5,un=5;var ti=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),c.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=ti._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return T.build(e[0])}else return new Uint8Array;let t=e.reduce((n,s)=>n+s.countSize(),0),i=new Uint8Array(t),r=0;for(let n of e){let s=T.build(n);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var n,s,d;((n=this._mediaSource)==null?void 0:n.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let e=(d=this._sourceBuffer)==null?void 0:d.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-ln);r-i>un&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},we=class extends et{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;c.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return T.element(T.ID.EBML,[T.element(T.ID.EBMLVersion,T.number(1)),T.element(T.ID.EBMLReadVersion,T.number(1)),T.element(T.ID.EBMLMaxIDLength,T.number(4)),T.element(T.ID.EBMLMaxSizeLength,T.number(8)),T.element(T.ID.DocType,T.string("webm")),T.element(T.ID.DocTypeVersion,T.number(2)),T.element(T.ID.DocTypeReadVersion,T.number(2))])}static _genSegmentHeader(e,t,i){let r=T.element(T.ID.Info,[T.element(T.ID.TimecodeScale,T.number(1e6)),T.element(T.ID.MuxingApp,T.string("vk-webm-builder")),T.element(T.ID.WritingApp,T.string("vk-webm-builder"))]),n=[T.element(T.ID.PixelWidth,T.number(e)),T.element(T.ID.PixelHeight,T.number(t))],s=T.element(T.ID.Tracks,T.element(T.ID.TrackEntry,[T.element(T.ID.TrackNumber,T.number(Ui)),T.element(T.ID.TrackUID,T.number(Ui)),T.element(T.ID.TrackType,T.number(1)),T.element(T.ID.FlagLacing,T.number(0)),T.element(T.ID.DefaultDuration,T.number(1e9)),T.element(T.ID.CodecID,T.string(`V_${i.toUpperCase()}`)),T.element(T.ID.Video,n)]));return T.unknownSizeElement(T.ID.Segment,[r,s])}static _genClusterHeader(e){return T.unknownSizeElement(T.ID.Cluster,[T.element(T.ID.Timecode,T.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new ti(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){c.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>c.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"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,c.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),c.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=we._genWebmHeader();this._mediaBuffer.append(s);let d=we._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(d)}let r=Math.round(i-this._clusterStartTime);if(r>pn&&(this._clusterStartTime=i,r=0),r===0){c.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=we._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let n=T.element(T.ID.SimpleBlock,[T.vintEncodedNumber(Ui),T.bytes(we._intToU16BE(r)),T.number((e.keyframe?1:0)<<7),T.bytes(e.frameData)]);this._mediaBuffer.append(n,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),c.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var gt=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};c.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=n=>this._onDataChannelMessage(n.data)}_onDataChannelMessage(e){var n,s;let t=aa(e),i=(s=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){c.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];if(!r){let d=l=>this._onStream(i,l);p.screenShareWebmBuilder&&we.isBrowserSupported()?r=new we(i,d):r=new Dt(i,d),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,c.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(Ke.isBrowserSupported()||mt.isBrowserSupported())&&(Dt.isBrowserSupported()||we.isBrowserSupported())}};var Bi=class{constructor(){this._timeouts=new Map;this._throttles=new Map;this._worker=new Worker(_.createBlobWorker(`var exports=(()=>{var m=Object.defineProperty;var i=e=>m(e,"__esModule",{value:!0});var l=(e,s)=>{i(e);for(var t in s)m(e,t,{get:s[t],enumerable:!0})};var c={};l(c,{default:()=>I});var n=new Map,r=new Map,p=5,I=()=>{self.onmessage=t=>{switch(t.data.type){case"timeout":e(t.data.id,t.data.ms);break;case"throttle":s(t.data.id,t.data.ms);break;case"ready":self.postMessage({type:"ready"});break;default:self.postMessage({type:"error",data:t.data});break}};function e(t,o=p){let a=setTimeout(()=>{self.postMessage({type:"timeout",id:t}),n.delete(t)},o);n.set(t,a)}function s(t,o=p){let a=r.get(t);a&&clearTimeout(a);let u=setTimeout(()=>{self.postMessage({type:"throttle",id:t}),r.delete(t)},o);r.set(t,u)}self.postMessage({type:"ready"})};return c;})();
|
|
10
|
-
|
|
11
|
-
`,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength})},[Vi.default,Vi.default.getUrl],{isVP9:this.isVP9(),debug:c.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(fe.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},mn),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),c.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var ft=class extends Fe{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return o(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;c.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var E=Object.defineProperty;var g=i=>E(i,"__esModule",{value:!0});var F=(i,l)=>{g(i);for(var r in l)E(i,r,{get:l[r],enumerable:!0})};var A={};F(A,{default:()=>h});var n=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(n||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,l,r,c,s,f,t,a=null,p=0,u=!1;function V(e){l=e.readable,r=l.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&b(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),l.cancel();return}a=R,b(R,e)}}))}function b(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
|
|
12
|
-
`,r=>{var n;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(n=r.data)==null?void 0:n.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:p.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(fe.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),c.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var hn=65536,Fi=0,St=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;c.debug("ScreenCaptureSender started"),this.DATA_SIZE=p.consumerScreenDataChannelPacketSize-ei,this._datachannel=t,this._timer=new Bi;let i=(r,n)=>{if(!this._destroyed){if(!r){c.warn("requestFrame failed, keyFrame: "+this._needKeyframe,n),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{c.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};ft.isBrowserSupported()?this._encoder=new ft(e,i):this._encoder=new At(e,i),this._datachannel.onmessage=r=>{na(r.data)&&(c.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},Promise.all([this._timer.initWorker(),this._encoder.init()]).then(()=>this._requestFrame()).catch(r=>c.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,n){let s=ra(e,t,i,r,Fi,this._encoder.isVP9(),n);return Fi=(Fi+1)%hn,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return o(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let n=e.data.slice(t,t+this.DATA_SIZE),s=e.data.byteLength<=t+n.byteLength,d=this._wrapHeader(e.timestamp,!t,s,e.type==="key",n);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(d)}catch(l){c.warn("Error send data to DataChannel",l),r();return}s||this._timer.postTimeout(Date.now(),()=>this._sendChunk(e,t+this.DATA_SIZE,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),this._timer.destroy(),c.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return ft.isBrowserSupported()||At.isBrowserSupported()}};var X=class{static get sessionKey(){return X._sessionKey}static set sessionKey(e){X._sessionKey=e}static get sessionSecretKey(){return X._sessionSecretKey}static set sessionSecretKey(e){X._sessionSecretKey=e}static get accessToken(){return X._accessToken}static set accessToken(e){X._accessToken=e}static isEmpty(){return!X._sessionKey||!X._sessionSecretKey}};var g=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(g._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(g._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(g._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(X.accessToken=e.apiAuth.accessToken,X.sessionKey=e.apiAuth.sessionKey,X.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(g._params,_.objectFilterOutValues(e,void 0))}static get(e){return g._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.6.2-dev.3549b06.0"}static get debug(){return undefined}static get protocolVersion(){return g._params.joinFromMultipleDevices?6:5}static get platform(){return g._params.platform}static set platform(e){g._params.platform=e}static get clientType(){return g._params.clientType}static set clientType(e){g._params.clientType=e}static get device(){return g._params.device}static get apiKey(){return g._params.apiKey}static get apiEnv(){return g._params.apiEnv}static get apiEndpoint(){switch(g.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return g._params.apiEnv}}static get authToken(){return g._params.authToken}static set authToken(e){g._params.authToken=e}static get anonymToken(){return g._params.anonymToken}static set anonymToken(e){g._params.anonymToken=e}static get domain(){return g._params.domain}static get iceServers(){return g._params.iceServers}static set iceServers(e){g._params.iceServers=e}static get wssBase(){return g._params.wssBase}static set wssBase(e){g._params.wssBase=e}static get wssToken(){return g._params.wssToken}static set wssToken(e){g._params.wssToken=e}static get signalingReconnectDelay(){return g._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return g._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return g._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return g._params.waitConnectionDelay}static get waitResponseDelay(){return g._params.waitResponseDelay}static get waitMessageDelay(){return g._params.waitMessageDelay}static get waitAnotherTabDelay(){return g._params.waitAnotherTabDelay}static get debugLog(){return g._params.debugLog}static get forceRelayPolicy(){return g._params.forceRelayPolicy}static set forceRelayPolicy(e){g._params.forceRelayPolicy=e}static get videoMinWidth(){return g._params.videoMinWidth}static get videoMaxWidth(){return g._params.videoMaxWidth}static set videoMaxWidth(e){g._params.videoMaxWidth=e}static get videoMinHeight(){return g._params.videoMinHeight}static get videoMaxHeight(){return g._params.videoMaxHeight}static set videoMaxHeight(e){g._params.videoMaxHeight=e}static get videoAspectRatio(){return g._params.videoAspectRatio}static get videoFrameRate(){return g._params.videoFrameRate}static get videoFacingMode(){return g._params.videoFacingMode}static get screenFrameRate(){return g._params.screenFrameRate}static get videoEffects(){return g._params.videoEffects}static set videoEffects(e){g._params.videoEffects=e}static get videoEffectMaxWidth(){return g._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){g._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return g._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){g._params.videoEffectMaxHeight=e}static get voiceParams(){return g._params.voiceParams}static get specListenerParams(){return g._params.specListenerParams}static get iceRestartWaitTime(){return g._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return g._params.transportConnectionWaitTime}static get statisticsInterval(){return g._params.statisticsInterval}static set statisticsInterval(e){g._params.statisticsInterval=e}static get networkStatisticsInterval(){return g._params.networkStatisticsInterval}static get perfStatReportEnabled(){return g._params.perfStatReportEnabled}static get callStatReportEnabled(){return g._params.callStatReportEnabled}static get producerNotificationDataChannel(){return g._params.producerNotificationDataChannel}static get producerCommandDataChannel(){return g._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return g._params.consumerScreenDataChannel&&St.isBrowserSupported()}static get producerScreenDataChannel(){return g._params.producerScreenDataChannel&&g.producerNotificationDataChannel&>.isBrowserSupported()}static get consumerScreenDataChannelPacketSize(){return g._params.consumerScreenDataChannelPacketSize}static get screenShareWebmBuilder(){return g._params.screenShareWebmBuilder}static get noiseSuppression(){return g._params.noiseSuppression}static set noiseSuppression(e){g._params.noiseSuppression=e}static get preferH264(){return g._params.preferH264}static get preferVP9(){return g._params.preferVP9}static get audioNack(){return g._params.audioNack}static get consumerScreenTrack(){return g._params.consumerScreenTrack&&g.consumerScreenDataChannel}static get producerScreenTrack(){return g._params.producerScreenTrack}static isUnifiedPlanSupported(e,t){let i=g._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return g._params.movieShare&&g.videoTracksCount>0}static get videoTracksCount(){return g.producerNotificationDataChannel?g._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return g._params.breakVideoPayloadTypes}static get filteredMessages(){return g._params.filteredMessages}static get useParticipantListChunk(){return g._params.useParticipantListChunk&&g._params.videoTracksCount>0}static get participantListChunkInitIndex(){var e;return(e=g._params.participantListChunkInitIndex)!=null?e:0}static get participantListChunkInitCount(){var e;return(e=g._params.participantListChunkInitCount)!=null?e:null}static get serverAudioRed(){return g._params.serverAudioRed&&y.canPreferRed()}static get p2pAudioRed(){return g._params.p2pAudioRed&&y.canPreferRed()}static get batchParticipantsOnStart(){return g._params.batchParticipantsOnStart}static get filterObservers(){return g._params.filterObservers}static get muteMode(){return g._params.muteMode}static get preserveAudioTracks(){return g._params.preserveAudioTracks}},p=g;p._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,consumerScreenDataChannelPacketSize:16*1024,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,useParticipantListChunk:!1,participantListChunkInitIndex:0,participantListChunkInitCount:null,serverAudioRed:!1,p2pAudioRed:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1};var $=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))($||{});function j(a,...e){let t=p.get(a);t&&setTimeout(t,0,...e)}function Te(a,e,...t){if(p.filterObservers){if(Array.isArray(e)){if(e=e.filter(i=>!i.observer),!e.length)return}else if(e.observer)return}j(a,e,...t)}function Ge(a){return Object.assign({},a)}function vt(a){return a.slice()}var Gi;(te=>{function a(u,R){j("onLocalStream",u,Ge(R))}te.onLocalStream=a;function e(u,R){j("onScreenStream",u,Ge(R))}te.onScreenStream=e;function t(u,R){j("onLocalStreamUpdate",Ge(u),R)}te.onLocalStreamUpdate=t;function i(u){j("onLocalStatus",u)}te.onLocalStatus=i;function r(u,R){Te("onRemoteStream",u,R)}te.onRemoteStream=r;function n(u,R,z){Te("onRemoteLive",u,R,z)}te.onRemoteLive=n;function s(u,R){Te("onRemoteScreenStream",u,R)}te.onRemoteScreenStream=s;function d(u,R,z,Tt){Te("onConversation",u,Ge(R),Ge(z),Tt)}te.onConversation=d;function l(u){u&&j("onConversationParticipantListChunk",u)}te.onConversationParticipantListChunk=l;function h(u,R,z){Te("onRemoteMediaSettings",u,Ge(R),z)}te.onRemoteMediaSettings=h;function C(u,R){Te("onParticipantAdded",u,R)}te.onParticipantAdded=C;function P(u,R){Te("onParticipantJoined",u,R)}te.onParticipantJoined=P;function L(u,R,z){Te("onRemoteParticipantState",u,Ge(R),z)}te.onRemoteParticipantState=L;function F(u,R,z=null){Te("onRemoteStatus",u,R,z)}te.onRemoteStatus=F;function q(u,R,z=null){Te("onParticipantStatus",u,R,z)}te.onParticipantStatus=q;function ue(){j("onPermissionsRequested")}te.onPermissionsRequested=ue;function Le(u){j("onPermissionsError",u)}te.onPermissionsError=Le;function de(u,R){Te("onRemoteRemoved",u,R)}te.onRemoteRemoved=de;function Je(u,R,z){j("onCallState",u,R,Ge(z))}te.onCallState=Je;function ce(u,R){j("onDeviceSwitched",u,R)}te.onDeviceSwitched=ce;function Me(u,R,z,Tt=!1,mi=!1,hi=null,Ua=null){j("onMuteStates",Ge(u),vt(R),vt(z),Tt,mi,hi,Ua)}te.onMuteStates=Me;function De(u,R){Te("onRolesChanged",u,vt(R))}te.onRolesChanged=De;function J(u){j("onLocalRolesChanged",vt(u))}te.onLocalRolesChanged=J;function ar(u,R,z){Te("onPinnedParticipant",u,R,z)}te.onPinnedParticipant=ar;function nr(u){j("onLocalPin",u)}te.onLocalPin=nr;function sr(u){j("onOptionsChanged",vt(u))}te.onOptionsChanged=sr;function or(){j("onCallAccepted")}te.onCallAccepted=or;function cr(){j("onRateNeeded")}te.onRateNeeded=cr;function K(u){Te("onSpeakerChanged",u)}te.onSpeakerChanged=K;function ui(u){j("onVolumesDetected",vt(u))}te.onVolumesDetected=ui;function f(u,R){j("onLocalVolume",u,R)}te.onLocalVolume=f;function I(u,R){j("onJoinStatus",u,R)}te.onJoinStatus=I;function b(u,R){j("onHangup",u,R)}te.onHangup=b;function k(u){j("onMultipartyChatCreated",Ge(u))}te.onMultipartyChatCreated=k;function S(){j("onDeviceChange")}te.onDeviceChange=S;function O(u){j("onFingerprintChange",u)}te.onFingerprintChange=O;function M(){j("onTokenExpired")}te.onTokenExpired=M;function D(u,R,z=!1){j("onChatMessage",u,R,z)}te.onChatMessage=D;function Ee(u,R,z=!1){j("onCustomData",u,R,z)}te.onCustomData=Ee;function _e(u,R,z,Tt,mi,hi){j("onRecordStarted",u,R,z,Tt,mi,hi)}te.onRecordStarted=_e;function ye(){j("onRecordStopped")}te.onRecordStopped=ye;function Pe(u){j("onLocalNetworkStatusChanged",u)}te.onLocalNetworkStatusChanged=Pe;function Ne(u){j("onNetworkStatusChanged",u)}te.onNetworkStatusChanged=Ne;function Z(u,...R){j("onDebugMessage",u,...R)}te.onDebugMessage=Z;function Ae(u,R){let z=Object.assign({},u,{memory:R});j("onStatistics",z)}te.onStatistics=Ae;function ke(){j("onAutoplayError")}te.onAutoplayError=ke;function ae(u,R,z){j("onChatRoomUpdated",u,R,z)}te.onChatRoomUpdated=ae;function Ue(u){j("onRemoteMixedAudioStream",u)}te.onRemoteMixedAudioStream=Ue;function pe(u){j("onJoinLinkChanged",u)}te.onJoinLinkChanged=pe})(Gi||(Gi={}));var E=Gi;var Hi=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(Hi||{}),Wi;(ce=>{let a="📞",e=(Me,...De)=>{E.onDebugMessage(Me,...De)},t=!1,i=(Me,De)=>(...J)=>{Me(...J),Hr(De,J)},r=console.debug.bind(console,a),n=console.log.bind(console,a),s=console.warn.bind(console,a),d=console.error.bind(console,a),l=e.bind(null,"DEBUG"),h=e.bind(null,"LOG"),C=e.bind(null,"WARN"),P=e.bind(null,"ERROR");ce.debug=l,ce.log=h,ce.warn=C,ce.error=P;function Le(){return t}ce.enabled=Le;function de(Me){t=Me,p.debugLog&&Ei(),Me?(ce.debug=p.debugLog?i(r,"DEBUG"):r,ce.log=p.debugLog?i(n,"LOG"):n,ce.warn=p.debugLog?i(s,"WARN"):s,ce.error=p.debugLog?i(d,"ERROR"):d):(ce.debug=p.debugLog?i(l,"DEBUG"):l,ce.log=p.debugLog?i(h,"LOG"):h,ce.warn=p.debugLog?i(C,"WARN"):C,ce.error=p.debugLog?i(P,"ERROR"):P)}ce.toggle=de;function Je(Me,...De){switch(Me){case"DEBUG":ce.debug(...De);break;case"LOG":ce.log(...De);break;case"WARN":ce.warn(...De);break;case"ERROR":ce.error(...De);break}}ce.send=Je})(Wi||(Wi={}));var c=Wi;var tt=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(tt||{}),he;(d=>{function a(l){return l.length?typeof l[0]=="object"?l:l.map(h=>e(h)):[]}d.fromIds=a;function e(l,h="USER"){return{id:l,type:h}}d.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}d.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}d.toString=i;function r(l,h="USER"){return i(e(l,h))}d.fromIdToString=r;function n(l){try{return JSON.parse(l)}catch(h){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}d.fromString=n;function s(l,h){return l.id===h.id&&l.type===h.type}d.compare=s})(he||(he={}));var le;(r=>{function a(n,s="USER",d=0){return{id:n,type:s,deviceIdx:d}}r.fromId=a;function e(n){return`{"id":"${n.id}","type":"${n.type}","deviceIdx":"${n.deviceIdx}"}`}r.toString=e;function t(n,s){return Object.assign({deviceIdx:s},he.fromSignaling(n))}r.fromSignaling=t;function i(n){return n&&typeof n=="object"?n.deviceIdx:0}r.getDeviceIdx=i})(le||(le={}));var _n="kf";function kt(a){return a.stopStream}function ji(a){return a.keyFrameRequested}function sa(a){if(kt(a))return"ss";if(ji(a))return _n;let e="";return a.priority!==void 0&&(e+="p="+a.priority),a.width!==void 0&&a.height!==void 0&&(e!==""&&(e+=":"),e+="sz="+Math.round(a.width)+"x"+Math.round(a.height)),a.fit!==void 0&&(e!==""&&(e+=":"),e+="fit="+a.fit),e}var ve=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(ve||{}),oa="s",ca="m";function He(a){return a.participantId+(a.mediaType?ut+oa+a.mediaType:"")+(a.streamName?ut+ca+a.streamName:"")}function Ot(a){let e=a.split(ut),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i=null,r,n=0;for(let d of e)switch(d.charAt(0)){case oa:i=gn(d.slice(1));break;case ca:r=d.slice(1);break;case Xt:n=Number.parseInt(d.slice(1),10);break;default:throw new Error("Unexpected parameter type "+d.charAt(0)+" in stream description "+a)}return{participantId:_.compose(t,n),mediaType:i,streamName:r}}function gn(a){for(let e of Object.keys(ve))if(e===a)return ve[e];return null}function Ki(a,e){return a===null||e===null?a===null&&e===null:!(a.maxDimension!==e.maxDimension||a.maxBitrateK!==e.maxBitrateK||a.maxFramerate!==e.maxFramerate||a.degradationPreference!==e.degradationPreference)}function ii(a,e){return!(!Ki(a.camera,e.camera)||!Ki(a.screenSharing,e.screenSharing))}function qi(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function da(a){try{return btoa(JSON.stringify(a))}catch(e){c.warn("WaitingParticipant: failed convert to string",a,e)}return null}function pa(a){try{return JSON.parse(atob(a))}catch(e){c.warn("WaitingParticipant: failed convert from string",a,e)}return null}var wt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,m.log(v.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,m.log(v.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(c.log("Failed to fix RV"),m.log(v.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),m.log(v.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,c.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===ie.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var ri=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(p.muteMode||!((s=this._output)==null?void 0:s.audioTrack))return;let e=y.browserName()!=="Safari"||y.isMobile(),t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{c.warn("Error on play audio"),E.onAutoplayError()},r=d=>{t.srcObject=new MediaStream([d]),t.load();let l=t.play();l?l.catch(i):i()},n=()=>{var l;c.debug("Recover audio playback");let d=(l=this._output)==null?void 0:l.audioTrack;d?r(d):c.warn("Broken audio track")};t.onpause=n,t.onstalled=n,t.onerror=n,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return o(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=y.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw m.log(v.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var fn=90,Sn=3,ai=class extends Q{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),E.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>fn?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Sn)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var vn=44100,xt=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=y.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=vn/this._fftBins.length,t=Math.ceil(p.voiceParams.minFreq/e),i=Math.floor(p.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((n,s)=>n+s,0)/e.length/255,r=this._lastSmoothedLevel*p.voiceParams.smoothing+i*(1-p.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var ni=class extends Q{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&E.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,p.voiceParams.interval)};this._interval=window.setTimeout(t,p.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,Ce.SOURCE_CHANGED,r=>{r.kind===ie.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new xt("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var la="videochat-epi",En=5e3,Tn=3e4,it=class extends Q{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,V.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(la)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return o(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&p.perfStatReportEnabled&&this._previousTimestamp+En<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),p.callStatReportEnabled&&this._previousCallStatReportTimestamp+Tn<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return o(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(la,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,n)=>(n.kind==="video"?(n.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+n.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+n.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=n.framesDropped,r.nack_sent+=n.nackCount,r.pli_sent+=n.pliCount,r.fir_sent+=n.firCount):(n.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+n.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+n.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=n.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=n.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=n.removedSamplesForAcceleration,r.concealed_audio_samples+=n.concealedSamples,r.silent_concealed_audio_samples+=n.silentConcealedSamples,r.audio_concealment_events+=n.concealmentEvents),r),t),e.outbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.nack_received+=n.nackCount,r.pli_received+=n.pliCount,r.fir_received+=n.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,n=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,d=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,l=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,h=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=n/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=d/r*1e3,i.concealed_silent_audio_samples=l/r*1e3,i.concealment_audio_avg_size=d/h,i.total_audio_energy=t.total_audio_energy}m.logCustom("callStat",i),c.log("Sent call stats",i),this._previousCallStatReport=t}};var In=1e3;function se(a,e,t=0){return e in a&&a[e]?a[e]:t}function ua(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function $e(a,e){return t=>t[a]===e}function Cn(a){return(e,t)=>e[a]-t[a]}function si(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function yn(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Pn(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function $i(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=Pn(t[1])?$i(t[1]):t[1],e),{})}function Rn(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function bn(a){return o(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...a.getReceivers().map(t=>t.getStats())),e.push(...a.getSenders().map(t=>t.getStats()))):e.push(a.getStats()),Promise.all(e).then(Rn).then(yn)})}function Mn(a){let e=a.filter($e("type","candidate-pair")).sort(Cn("priority")).find(ua($e("nominated",!0),$e("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=a.find($e("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=a.find($e("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),$i(t)}function Dn(a,e){let t=si("id",a),i=a.filter(ua($e("type","inbound-rtp"),$e("type","outbound-rtp")));y.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,s)=>{if(!n[s.ssrc])n[s.ssrc]=s;else{let d=Object.assign({},n[s.ssrc],s),l=n[s.ssrc].isRemote?s:n[s.ssrc];d.id=l.id,d.type=l.type,delete d.isRemote,delete d.remoteId,n[d.ssrc]=d}return n},{})));let r={};if(y.browserName()==="Safari"){let n=a.filter($e("type","track"));r=si("trackIdentifier",n)}return i.map(n=>{let s=Number(n.ssrc),d=n.mediaType||n.kind,l=n.trackId,h=n.type,C=n.codecId;if(y.browserName()==="Safari"){let L=/^.+_([\d]+)$/.exec(n.id);if(L&&(s=parseInt(L[1],10)),d=n.id.indexOf("Audio")>0?"audio":"video",e[s]){let F=d+"-"+e[s];r[F]&&(l=r[F].id)}}if(!h||!s||!d)return null;let P={ssrc:s,type:h,kind:d,bytesReceived:se(n,"bytesReceived"),bytesSent:se(n,"bytesSent"),jitter:se(n,"jitter"),packetsLost:se(n,"packetsLost"),packetsReceived:se(n,"packetsReceived"),packetsSent:se(n,"packetsSent"),fractionLost:se(n,"fractionLost"),pliCount:se(n,"pliCount"),firCount:se(n,"firCount"),nackCount:se(n,"nackCount"),userId:e[s]};if(d==="video"){let L=se(n,"framesDecoded"),F=se(n,"totalInterFrameDelay"),q=se(n,"totalSquaredInterFrameDelay");P.interframeDelayVariance=(q-F*F/L)/L}if(d==="audio"&&(P.totalSamplesReceived=se(n,"totalSamplesReceived"),P.concealedSamples=se(n,"concealedSamples"),P.insertedSamplesForDeceleration=se(n,"insertedSamplesForDeceleration"),P.removedSamplesForAcceleration=se(n,"removedSamplesForAcceleration"),P.silentConcealedSamples=se(n,"silentConcealedSamples"),P.concealmentEvents=se(n,"concealmentEvents"),P.totalAudioEnergy=se(n,"totalAudioEnergy")),C&&t[C]){let L=t[C];P.clockRate=L.clockRate,P.mimeType=L.mimeType}if(l&&t[l]){let L=t[l];P.frameHeight=L.frameHeight,P.frameWidth=L.frameWidth,P.framesDecoded=L.framesDecoded,P.framesReceived=L.framesReceived,P.framesDropped=L.framesDropped}return $i(P)}).filter(n=>!!n)}function An(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=si("ssrc",a.rtps),i=si("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let s=t[n],d=i[n];if(!(!s||!d)){if(s.bytesReceived&&s.bytesReceived>d.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-d.bytesReceived)/r)),s.bytesSent&&s.bytesSent>d.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-d.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>d.packetsReceived||s.packetsLost>d.packetsLost){let l=s.packetsLost-d.packetsLost,h=s.packetsReceived-d.packetsReceived;s.packetLoss=parseFloat((100*l/(l+h)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&d.framesDropped&&s.framesDropped>d.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-d.framesDropped)/r).toFixed(0)))}}),a}function Lt(i,r){return o(this,arguments,function*(a,e,t={}){let n=yield bn(a),s={timestamp:Date.now(),transport:Mn(n),rtps:Dn(n,t)};return e?An(s,e):(yield _.delay(In),Lt(a,s,t))})}var oi=.8,rt=class extends Q{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=B.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=n,this._perfStatReporter=new it(this,i,!0),this.subscribe(this._signaling,ge.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Ce.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Ce.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:p.iceServers,iceTransportPolicy:p.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,p.p2pAudioRed),this._applySettings()}catch(s){m.log(v.ERROR,"addTrack-direct"),c.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===B.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==B.IDLE&&e!==B.CLOSED&&e!==B.FAILED&&this._startStatInterval()}open(e=null){return o(this,null,function*(){if(this._isOpen){c.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(c.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,p.p2pAudioRed),this._applySettings()}catch(i){m.log(v.ERROR,"addTrack-direct"),c.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(B.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){ii(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(V.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(c.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(B.FAILED)):(c.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(B.CLOSED)),this._triggerEvent(V.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(V.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case w.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case w.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case w.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((n=e.data.sdk)==null?void 0:n.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=_.getPeerIdString(e.peerId);_.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){c.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw m.log(v.ERROR,"addIceCandidate-direct"),c.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else c.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return o(this,null,function*(){if(!this._remoteCandidates[e]){c.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){c.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw m.log(v.ERROR,"setRemoteDescription-direct"),c.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){c.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(V.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(V.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return o(this,null,function*(){e.candidate&&this._signaling.ready&&(c.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(c.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>o(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(c.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===B.IDLE||e===B.OPENED?this._setState(B.CONNECTING):this._setState(B.RECONNECTING);break}}_onConnectionStateChange(){switch(c.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),m.log(v.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(B.CONNECTED),this._stopReconnection(),_.getPeerConnectionHostInfo(this._pc).then(e=>{e&&m.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(B.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(c.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},p.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(c.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(oe.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(m.log(v.ICE_RESTART),c.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):c.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,c.error("Ice restart failed",{participantId:this._participantId}),m.log(v.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},p.iceRestartWaitTime)}_createOffer(e){return o(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return c.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw c.error("Unable to create offer",i,{participantId:this._participantId}),m.log(v.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=rt._patchDescription(i),c.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw c.error("Unable to set local description",i,{participantId:this._participantId}),m.log(v.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return o(this,null,function*(){return c.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw c.error("Unable to create answer",e,{participantId:this._participantId}),m.log(v.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=rt._patchDescription(e),c.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw c.error("Unable to set local description",e,{participantId:this._participantId}),m.log(v.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=_.patchSDP(e.sdp,p.preferH264&&y.canPreferH264(),y.isBrokenH264(),p.preferVP9,t&&p.audioNack,p.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{c.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),m.log(v.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Lt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:oe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:oe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(V.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=de=>de.rtt<=this._networkLimits.goodNet.rtt&&de.loss<=this._networkLimits.goodNet.loss,i=de=>de.rtt>=this._networkLimits.badNet.rtt||de.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((de,Je)=>Math.max(de,Je.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-oi)+r*oi,loss:this._lastNetworkStat.loss*(1-oi)+n*oi},d=i(s),l=t(s),h=i(this._remoteNetworkStat),C=t(this._remoteNetworkStat),P=i(this._lastNetworkStat),L=t(this._lastNetworkStat),ue=d||h?.2:l&&C?1:0,Le=Date.now();if((P!==d||L!==l||Le-this._lastNetworkStat.date>p.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(de=>{c.warn("Unable to send [bad-net]",de)})),ue){let de={};de[this._participantId]=de[""]=ue,this._triggerEvent(V.NETWORK_STATUS,de)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=_.sdpFingerprint(e);if(t===null){c.warn("Fingerprint calculation is unsupported");return}this._fingerprint===null?this._fingerprint=t:(E.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=_.applySettings(this._pc,e,this._prevConsumerSettings))}};var ma=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(ma||{}),Nt=ma;var at=Ye(require("messagepack"));var Ji=class{constructor(){this.streamDescriptionByCompactId=new Map;this.compactIdByStreamDescription=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}getCompactId(e){return this.compactIdByStreamDescription.get(e)}handleMessage(e){var n,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let d=(0,at.decode)(r);return Object.entries(d).forEach(([q,ue])=>{let Le=Ot(q);this.streamDescriptionByCompactId.set(ue,Le),this.compactIdByStreamDescription.set(q,ue)}),null;case 2:case 4:let l=(0,at.decode)(r),h=[];for(let q of l){let ue=this.getStreamDescription(q);ue&&h.push(ue.participantId)}return i===2?{type:"notification",notification:w.AUDIO_ACTIVITY,activeParticipants:h}:{type:"notification",notification:w.STALLED_ACTIVITY,stalledParticipants:h};case 3:let C=(0,at.decode)(r);return{type:"notification",notification:w.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(C))==null?void 0:n.participantId};case 5:let P=(0,at.decode)(r);return{type:"notification",notification:w.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:P[0],maxDimension:P[1]}};case 6:let L=(0,at.decode)(r),F={};for(let[q,ue]of Object.entries(L)){let Le=(s=this.getStreamDescription(Number(q)))==null?void 0:s.participantId;Le&&(F[Le]=ue/100)}return{type:"notification",notification:w.NETWORK_STATUS,statuses:F};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,at.decode)(e),i=[];for(let[r,n]of Object.entries(t)){let s=n[0],d=n[1],l=n[2],h;if(s!==null){if(h=this.getStreamDescription(s),!h){c.error(`could not uncompress participant ID ${s}`);continue}}else h=null;if(l===null){c.error("unexpected null sequenceNumber",r,n);continue}let C=Oe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,P=d?d>>>0:null;i.push({participantStreamDescription:h,streamId:C,rtpTimestamp:P,sequenceNumber:l})}return{type:"notification",notification:w.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var kn=90,On=4294967295,Re=class extends Q{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=B.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,ge.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Ce.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Ce.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,Ce.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new it(this,e),this._serverSettings=i,c.debug("ServerTransport: Created")}getState(){return this._state||B.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==B.IDLE&&e!==B.CLOSED&&e!==B.FAILED&&this._startStatInterval()}open(e=!1){if(this._isOpen){c.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(c.error("ServerTransport: Closed",e),this._setState(B.FAILED)):(c.debug("ServerTransport: Closed"),this._setState(B.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){ii(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,Re._closeDataChannel(this._producerNotification),Re._closeDataChannel(this._producerCommand),Re._closeDataChannel(this._producerScreen),Re._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(V.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let n=r.readyState;n==="open"?(c.debug(`[${t}] data channel opened`),r.onerror=s=>{c.error(`[${t}] data channel error`,s)},i(r)):c.error(`[${t}] data channel open failed, state [${n}]`)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection");let t={};y.baseChromeVersion()&&(t.sdpSemantics=Re._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=_.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Re._onSignalingStateChange.bind(this,this._pc),p.producerNotificationDataChannel&&this._createDataChannel(this._pc,Nt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Ji,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),p.producerCommandDataChannel&&(this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,Nt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)})),p.producerScreenDataChannel&&this._createDataChannel(this._pc,Nt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,p.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){c.error("ServerTransport: Unable to add media source tracks",i),m.log(v.ERROR,"addTrack-single"),this.close(i);return}p.consumerScreenDataChannel&&this._createDataChannel(this._pc,Nt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(B.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==B.OPENED&&(this._setState(B.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(V.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(V.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(V.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(V.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
|
|
13
|
-
`).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Oe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!p.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new St(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!p.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new gt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(V.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(V.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!p.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==ie.video)return;let r=!this._disabledSenders.has(i),n=e.maxDimension!==0;if(r&&!n){c.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(y.getBlackMediaTrack()).catch(d=>{c.error("Could not disable video upload",d)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&n&&s){c.log("Enabling video upload"),this._disabledSenders.delete(i);let d=i.track;d.enabled=s.enabled,i.replaceTrack(s).then(()=>d.stop()).catch(l=>{c.error("Could not enable video upload",l)})}_.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(V.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,p.statisticsInterval)};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return o(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Lt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(V.REMOTE_DATA_STATS,{inbound:{topology:oe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:oe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=Oe.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(V.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:it.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:p.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:p.producerCommandDataChannel?3:0,consumerScreenDataChannelVersion:p.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:p.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:Re._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:p.videoTracksCount,red:p.serverAudioRed};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return o(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,c.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(c.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw c.error("[single] unable to set remote offer",i),m.log(v.ERROR,"setRemoteDescription-single"),i}).then(()=>o(this,null,function*(){if(c.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw c.error("[single] unable to create answer",i),m.log(v.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=_.patchSDP(i.sdp,!1,y.isBrokenH264(),!1),i)).then(i=>o(this,null,function*(){if(c.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw c.error("[single] unable to set local answer",i),m.log(v.ERROR,"setLocalDescription-single"),i}).then(i=>o(this,null,function*(){c.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),c.debug("[single] remote offer has been processed")})).catch(i=>{c.warn("[single] unable to send local answer",i),m.log(v.ERROR,"acceptProducer")}).then(()=>o(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){c.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return o(this,null,function*(){if(!!this._isOpen)switch(e.notification){case w.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case w.REALLOC_CON:this._reconnect();break;case w.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case w.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case w.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case w.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return o(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),p.breakVideoPayloadTypes&&(c.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes",null)),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){c.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent(V.REMOTE_TRACK_REMOVED,i.id,i,n.track)}),i.getTracks().find(n=>n.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(V.REMOTE_TRACK_ADDED,i.id,i,t.track)):c.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){c.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(c.debug("[single] connection state changed",{state:e.connectionState},t),m.log(v.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===B.IDLE||i===B.OPENED?this._setState(B.CONNECTING):e.iceConnectionState==="checking"&&this._setState(B.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(B.RECONNECTING);break;case"connected":this._setState(B.CONNECTED),_.getPeerConnectionHostInfo(e).then(r=>{r&&m.log(v.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(p.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{c.error("ServerTransport: Unable to replace track",r),m.log(v.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=y.baseChromeVersion();return e?p.isUnifiedPlanSupported("Chrome",e):p.isUnifiedPlanSupported(y.browserName(),Number(y.browserVersion()))}getStreamWaitingTimeMs(e,t){if(!this._pc)return m.log(v.PAT_WAITING_TIME_ERROR,"noConnection"),c.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return m.log(v.PAT_WAITING_TIME_ERROR,"noReceiver"),c.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return c.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return m.log(v.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),c.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let d=t-s&On,l=Math.ceil(d/kn);return Math.min(100,Math.max(0,l))}};var V=(F=>(F.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",F.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",F.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",F.REMOTE_ALL_STALL="REMOTE_ALL_STALL",F.REMOTE_DATA_STATS="REMOTE_DATA_STATS",F.STATE_CHANGED="STATE_CHANGED",F.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",F.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",F.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",F.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",F.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",F.NETWORK_STATUS="NETWORK_STATUS",F.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",F))(V||{}),B=(d=>(d.IDLE="IDLE",d.OPENED="OPENED",d.CONNECTING="CONNECTING",d.RECONNECTING="RECONNECTING",d.CONNECTED="CONNECTED",d.CLOSED="CLOSED",d.FAILED="FAILED",d))(B||{}),oe=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(oe||{}),Yi=class extends Q{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,ge.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){c.log("Update transport settings",e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){c.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,r=!1){let n=r;for(let s of e){if(this._opened.indexOf(s)!==-1){c.warn(`The participant [${s}] has already had opened transport`);continue}if(this._allocated.indexOf(s)===-1){c.warn(`The participant [${s}] has no allocated transport`);continue}this._opened.push(s),n=!0}!n||(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())),c.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&c.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}getState(){return this._topology==="SERVER"?this._serverTransport.getState():this._directTransport.getState()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===w.TOPOLOGY_CHANGED)return this._onTopologyChanged(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),m.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||[],r=e.offerToTypes||[],n=e.offerToDeviceIdxs||[],s=i.length&&r.length?_.composeParticipantId(i[0],r[0],n[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){c.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&c.warn("Topology changed to DIRECT, but the allocated participants count more then one");let d=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=s===d;this._directTransport=this._createDirectTransport(d,l)}this._opened.indexOf(d)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_createDirectTransport(e,t=!1){let i=new rt(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._dtListeners&&this._dtListeners.length>0&&c.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new Re(this._signaling,this._mediaSource,this._serverSettings);return this._stListeners&&this._stListeners.length>0&&c.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;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 r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(m.log(v.PAT_WAITING_TIME_ERROR,"wrongTopology"),c.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(m.log(v.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var nt=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(nt||{}),zi=class extends Q{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,V.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,V.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,V.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,V.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===ie.audio&&((r=this._detector)==null||r.destroy(),this._detector=new xt(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,p.voiceParams.interval)};this._interval=window.setTimeout(n,p.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===ie.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===Oe.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e===oe.DIRECT&&(this._activeParticipants=null)}};var Qi=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(Qi||{}),Xi=class extends Q{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i===oe.SERVER,this.subscribe(e,nt.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,V.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,V.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>p.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*p.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent("SPEAKER_CHANGED",e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e===oe.SERVER}};var ci=class extends Q{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,V.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,nt.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===B.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===B.FAILED&&this._connectionTimeout&&(c.warn("Transport failed, send callSpecError"),m.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!==B.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(c.warn("There is not connected transport, send callSpecError"),m.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",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),m.log(v.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&c.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var wn=1e3,xn=1e4;var Ln=15,H=class extends Q{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=W.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;m.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),m.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new ri,p.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),wn))}static current(){return H._current}static hangupAfterInit(){H._activationMutex&&!H._current&&(H._delayedHangup=!0)}static id(){var e,t;return((t=(e=H._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,s=!1){return o(this,null,function*(){if(H._activationMutex)throw m.log(v.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new x(A.FAILED);H._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let d=this._mediaSource.getMediaSettings();t===Be.CHAT||e.length>1?this._logWithMediaSettings(v.OUTGOING_MULTIPARTY_CALL,d):this._logWithMediaSettings(v.OUTGOING_CALL,d);let l=yield this._startConversation(e,t,We.OUTGOING,i,r,n,s);if(!this._conversation)throw new x(A.UNKNOWN_ERROR);if(this._participantState=W.ACCEPTED,this._signaling.changeMediaSettings(d),yield this._processConnection(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),H._delayedHangup)throw new x(A.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let h=Object.values(this._participants),C;return p.batchParticipantsOnStart&&(C=_.mapSharedParticipants(h)),E.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,C),this._onConversationParticipantListChunk(l),E.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),H._current=this,this._conversation.concurrent?yield this._acceptConcurrent():p.batchParticipantsOnStart||this._setParticipantsStatus(h,$.WAITING),this._conversation}catch(d){throw this._close(d,"Unable to start conversation"),d}finally{H._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){var t;if(H._activationMutex)throw m.log(v.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new x(A.FAILED);H._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(v.JOIN_CONVERSATION,r);let n=yield this._joinConversation(e);if(!this._conversation)throw new x(A.UNKNOWN_ERROR);return this._conversation.observer=i,E.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(c.log("In waiting hall"),H._current=this,H._activationMutex=!1,this._signaling.readyToSend(),E.onLocalStatus($.WAITING_HALL),this._conversation):this._onJoinPart2(n)}catch(i){throw H._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return o(this,null,function*(){c.debug("Join conversation part 2"),H._activationMutex=!0;try{if(this._participantState=W.ACCEPTED,!this._conversation||!this._mediaSource)throw new x(A.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(),H._delayedHangup)throw new x(A.CANCELED);let t=Object.values(this._participants),i;return p.batchParticipantsOnStart&&(i=_.mapSharedParticipants(t)),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),this._onConversationParticipantListChunk(e),E.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),H._current=this,p.batchParticipantsOnStart||this._setParticipantsStatus(t,$.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{H._activationMutex=!1}})}onPush(r){return o(this,arguments,function*(e,t=Y.USER,i){if(H._activationMutex)throw c.warn("Conversation: there is already running activation"),new x(A.REJECTED);H._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new x(A.UNKNOWN_ERROR);if(!n.conversation.participants.find(d=>{var l;return d.state===W.CALLED&&d.id===((l=this._conversation)==null?void 0:l.userId)}))throw c.log("Push rejected (there is an active call)"),m.log(v.PUSH,"rejected"),new x(A.REJECTED);if(yield this._processConnection(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),m.log(v.PUSH,"accepted"),H._current=this,H._delayedHangup)throw new x(A.CANCELED);H._activationMutex=!1}catch(n){throw H._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Ht.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>_.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return o(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new x(A.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(v.ACCEPT_CONCURRENT,e),c.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),E.onCallAccepted(),this._state="ACTIVE",this._participantState=W.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return o(this,null,function*(){if(this._state!=="IDLE")throw m.log(v.ERROR,"acceptIncoming"),c.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new x(A.UNKNOWN_ERROR);this._state="PROCESSING",c.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(v.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=W.ACCEPTED;let i=Object.values(this._participants),r;if(p.batchParticipantsOnStart&&(r=_.mapSharedParticipants(i)),E.onCallAccepted(),E.onLocalStream(this._mediaSource.getStream(),t),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),p.useParticipantListChunk){let s=yield this._getInitialParticiapntListChunk();this._onConversationParticipantListChunk({participants:s})}E.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(je.MUTE)||n.includes(je.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),p.batchParticipantsOnStart||this._setParticipantsStatus(i,$.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return o(this,null,function*(){var e;if(this._state!=="IDLE")throw m.log(v.ERROR,"declineIncoming"),c.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",c.debug("Decline incoming call"),this._logWithMediaSettings(v.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=W.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(A.REJECTED)),this._close(new x(A.REJECTED))})}hangup(){return o(this,null,function*(){c.debug("Hangup");let e=this._state==="ACTIVE"?A.HUNGUP:A.CANCELED;m.log(v.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new x(e))):E.onHangup(new x(A.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new x(A.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=A.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(_.composeId(n),n,r)})}removeParticipant(e,t=!1){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let n of e)(n.state===W.CALLED||n.state===W.ACCEPTED)&&(this._transport.isAllocated(n.id)||this._transport.allocate(n.id,t)),n.state===W.ACCEPTED&&i.push(n.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&c.error(t,e),c.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(A.FAILED):m.log(v.ERROR,e.hangup),H._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([A.CANCELED,A.NOT_FRIENDS,A.CALLEE_IS_OFFLINE,A.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===A.REJECTED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===A.HUNGUP&&(!e.remote||this._participantState===W.CALLED)){E.onHangup(e,i),this.destroy();return}if(e.hangup===A.MISSED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===A.SOCKET_CLOSED&&H._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===A.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=W.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),m.destroy(),this._conversation=null,H._current=null,H._delayedHangup=!1,E.onHangup(e||new x(A.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;c.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),m.destroy(),this._conversation=null,H._current=null,H._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return o(this,null,function*(){let t=yield this._api.getConversationParams(e);c.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let s=r.urls.filter((d,l,h)=>h.indexOf(d)===l);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return p.iceServers=i,p.wssBase=t.endpoint,p.wssToken=t.token,t.client_type&&(p.clientType=t.client_type),t})}_addGeoParamsToEndpoint(e,t){return t.isp_as_no&&(e+=`&ispAsNo=${t.isp_as_no}`),t.isp_as_org&&(e+=`&ispAsOrg=${t.isp_as_org}`),t.loc_cc&&(e+=`&locCc=${t.loc_cc}`),t.loc_reg&&(e+=`&locReg=${t.loc_reg}`),e}_startConversation(e,t,i,r,n="",s=!1,d=!1){return o(this,null,function*(){let l=_.uuid();c.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let h=r.includes(ne.VIDEO),C=yield this._api.startConversation(l,e,t,h,n,s,d);c.debug("Api.startConversation",C);let P=yield this._getConversationParams(C.id);C.endpoint=this._addGeoParamsToEndpoint(C.endpoint,P);let L=yield this._connectSignaling(Ve.START,C);return yield this._setConversation(C,L,i),L})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n,observedIds:s}=e;c.debug("Conversation: join",{conversationId:t,joinLink:n,observedIds:s});let d=i.includes(ne.VIDEO),l;if(t)l=yield this._api.joinConversation(t,d,r);else if(n)l=yield this._api.joinConversationByLink(n,d,s);else throw new x(A.UNKNOWN_ERROR);c.debug("Api.joinConversation",l),yield this._getConversationParams(l.id);let h=yield this._connectSignaling(Ve.JOIN,l);return yield this._setConversation(l,h,We.JOINING),h})}_prepareConversation(r){return o(this,arguments,function*(e,t=Y.USER,i){c.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let n=this._api.getUserId();if(!n)throw new x(A.UNKNOWN_ERROR);let s=yield this._getConversationParams(e),d=s.device_idx||0,l=`${p.wssBase}?userId=${n}&entityType=${t}&deviceIdx=${d}&conversationId=${e}&token=${p.wssToken}`;l=this._addGeoParamsToEndpoint(l,s);let h={id:e,peerId:i,endpoint:l,is_concurrent:!1,p2p_forbidden:!1,device_idx:d},C=yield this._connectSignaling(Ve.ACCEPT,h);return H._current&&(H._current._participantState===W.ACCEPTED||H._current._participantState===W.CALLED)?(c.log("Push rejected (busy)"),m.log(v.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(A.BUSY),Promise.reject({hangup:A.BUSY})):(H._current&&(H._current.destroy(),H._current=null),yield this._setConversation(h,C,We.INCOMING,t),C)})}_createParticipant(e){return o(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:me(),participantState:{},state:W.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[]},e);if(e.externalId){let r=_.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(r,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return((i=t.observedIds)==null?void 0:i.length)&&(t.externalId.observer=!0),this._setParticipantMarkers(t,t.markers),t})}_getParticipantId(e){return o(this,null,function*(){try{let t=_.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new x(A.NETWORK_ERROR),t),t}})}_setConversation(n,s,d){return o(this,arguments,function*(e,t,i,r=Y.USER){yield this._prepareParticipants(t.conversation.participants);let l=this._api.getUserId(),h=e.device_idx||0;if(!l){let L=(t.conversation.participants||[]).find(F=>_.comparePeerId(F.peerId,t.peerId));if(!L)throw new x(A.UNKNOWN_ERROR);l=Number(L.id),L.idType&&(r=L.idType),L.deviceIdx&&(h=L.deviceIdx),this._api.setUserId(l)}let C=_.composeParticipantId(l,r,h),P=yield this._getParticipantId(C);this._conversation={userId:l,compositeUserId:C,externalId:P,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||oe.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(p.forceRelayPolicy=e.p2p_forbidden),m.log(v.RELAY_POLICY,p.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new x(A.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||oe.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new xi;return this.subscribe(e,Ce.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Ce.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new wt(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,ge.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,ge.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,ge.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_processConnection(e){return o(this,null,function*(){yield this._registerConnectionParticipants(e),this._processConnectionData(e)})}_prepareParticipants(e){return o(this,null,function*(){let t=e.map(i=>i.id);t.length&&(yield this._api.prepareUserIds(t))})}_onConversationParticipantListChunk(e){let t=e.participants;t&&E.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(t))}_participantListChunkToExternalChunk(e){let t=_.mapSharedParticipants(e.participants.map(i=>{let r=_.composeId(i);return this._participants[r]}));return _i(st({},e),{participants:t})}_registerConnectionParticipants(e){return o(this,null,function*(){var t,i;yield this._registerParticipants(e.conversation.participants),((t=e.participants)==null?void 0:t.participants)&&(yield this._registerParticipants((i=e.participants)==null?void 0:i.participants))})}_registerParticipants(e){return o(this,null,function*(){if(!!this._conversation)for(let t of e){let i=_.composeId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(c.debug(`Local roles changed: ${t.roles}`),E.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===W.HUNGUP||t.state===W.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],A.HUNGUP);continue}this._registerParticipantInCache(yield this._createParticipant({id:i,externalId:t.externalId&&le.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:me(t.mediaSettings),participantState:_.mapParticipantState(t),state:t.state,roles:t.roles||[],status:p.batchParticipantsOnStart?$.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[],markers:this._denormalizeMarkers(i,t.markers)})),t.roles&&t.roles.length&&(c.debug(`Roles for participant [${i}] changed: ${t.roles}`),E.onRolesChanged(this._participants[i].externalId,t.roles))}})}_getClientType(){return p.clientType}_getStatusByTransportState(e){let t;return e===B.CONNECTED?t=$.CONNECTED:e===B.CONNECTING||e===B.OPENED?t=$.CONNECTING:e===B.RECONNECTING&&(t=$.RECONNECT),t}_registerParticipantInCache(e){return this._participants[e.id]=e}_getExistedParticipantByIdOrCreate(e){return o(this,null,function*(){return this._participants[e]||this._createParticipant({id:e})})}_getExternalIdByParticipantId(e){return o(this,null,function*(){var t;return p.useParticipantListChunk?(yield this._getExistedParticipantByIdOrCreate(e)).externalId:(t=this._participants[e])==null?void 0:t.externalId})}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){return o(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){c.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(r=>"ts"in r&&"rank"in r);return Object.entries(t).reduce((r,[n,s])=>(r[n]=_i(st(st({},i),s),{id:e}),r),{})}_processConnectionData(e){return o(this,null,function*(){_.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&(yield this._onPinParticipant(e.conversation.pinnedParticipantId)),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Gt.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)})}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Yi(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new ai,this.subscribe(this._transport,V.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,V.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,V.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,V.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,V.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,V.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,V.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,V.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,V.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,V.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,V.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===We.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===W.ACCEPTED||t.state===W.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new zi(this._transport),this.subscribe(this._volumesDetector,nt.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Xi(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,Qi.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new ni(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new ci(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=y.getCameras().length,t=y.getMicrophones().length;c.debug("Cameras: "+e+(y.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(y.hasMicrophonePermission()?"✔":"✖")),m.log(v.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){m.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===W.CALLED||e.state===W.ACCEPTED||this._state==="CLOSE"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),!!this._participants[e.id]&&(t===A.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:ve.CAMERA,stopStream:!0}]),delete this._participants[e.id],E.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,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){c.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return o(this,null,function*(){c.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===W.ACCEPTED||r.state===W.CALLED)){c.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(r=this._registerParticipantInCache(yield this._createParticipant({id:e,externalId:t.externalId&&le.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:me(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}))),this._setParticipantsStatus([r],$.WAITING),i?(r.state=W.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=W.CALLED,this._transport.allocate(r.id,!0),m.log(v.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){c.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=Ln;i++){let r=_.compose(e,i),n=this._participants[r];n&&t.push(n)}if(!t.length){this._warnParticipantNotInConversation(e);return}if(this._transport)for(let i of t)this._transport.close(i.id);m.log(v.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new wt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ee.UNKNOWN)})}toggleScreenCapturing(e){return o(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ee.UNKNOWN)})}setVideoStream(e,t=!1){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return o(this,null,function*(){if(this._mediaSource)return m.log(v.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return m.log(v.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return o(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let n=typeof r.uid=="object"?r.uid:le.fromId(r.uid),s=le.toString(n);i[s]=r.priority}for(let r of Object.values(this._participants)){let n=le.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return o(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return o(this,null,function*(){let t={};return t[He(e)]={keyFrameRequested:!0},this._signaling.updateDisplayLayout(t)})}requestTestMode(e,t){return o(this,null,function*(){return this._signaling.requestTestMode(e,t)})}updateDisplayLayout(e){return o(this,null,function*(){if(e.length<1||!this._signaling.ready)return;c.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:le.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(n);if(!s){let C=le.toString(n);c.log(`Unknown participant external ID ${C}`);continue}let d=_.compose(s,n.deviceIdx),l=He({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),h=this._participants[d];h&&(h.lastRequestedLayouts[l]=r),kt(r)?this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now()):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&p.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=r)}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>p.videoTracksCount;){let r=i.next();if(r.done){c.error("Cannot accommodate all streaming requests: tracks available "+p.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]={stopStream:!0}}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(c.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Ot(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===ve.STREAM||i.mediaType===ve.SCREEN)?E.onRemoteLive(r.externalId,i.streamName,null):E.onRemoteStream(r.externalId,null),m.log(v.PAT_DEALLOCATED)):c.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return o(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,n]of Object.entries(t.errorCodeByParticipantId||{})){let s=Ot(r),d=this._participants[s.participantId];if(d){let l;typeof n!="number"?(c.warn(`Unexpected error code ${n} received for participant ${s.participantId}`),l=wr.UNKNOWN_ERROR):l=xr(n),i.push({externalId:d.externalId,errorReason:l})}}if(i&&i.length)throw new di("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+xn>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e)}_onParticipantSourcesUpdate(e){if(this._conversation){c.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){c.log("Promoted in waiting hall",!e.demote),e.demote?(c.log("Kicked from waiting hall"),this._close(new x(A.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return o(this,arguments,function*(e,t=0,i=[]){c.log(`Chat room updated: ${e}`);let n=[],s=[];i.length&&(i.forEach(d=>{if(d.externalId){let l=he.fromSignaling(d.externalId);n.push(l),this._api.cacheExternalId(d.id.id,l)}else s.push(_.decomposeId(d.id.id).id)}),s.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(s))),E.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var d,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||p.producerScreenDataChannel&&t.mediaType===ve.SCREEN)return;let i=He(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){c.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),m.log(v.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let h=t.participantId,C=this._participants[h];if(!C){m.log(v.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${h}`);return}let P=this._streamByStreamId.get(n);if(!P){m.log(v.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${n}`);return}m.log(v.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let L=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(L===ve.STREAM||L===ve.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&E.onRemoteLive(C.externalId,e.participantStreamDescription.streamName,P);else if(p.producerScreenTrack&&L===ve.SCREEN)E.onRemoteScreenStream(C.externalId,P);else{let F=(p.producerScreenTrack?null:C.secondStream)||P;E.onRemoteStream(C.externalId,F)}}else{c.debug(`Waiting for ${s} until stream ${n} for ${i} is switched`);let h=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,h)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(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:ve.CAMERA};if(this._streamIdByStreamDescription.has(He(i)))return i;let r={participantId:t,mediaType:ve.SCREEN};if(this._streamIdByStreamDescription.has(He(r)))return r}return c.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?_.includesOneOf(this._conversation.roles,[ze.ADMIN,ze.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!_.includesOneOf(this._conversation.roles,[ze.ADMIN,ze.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return o(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return o(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return o(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Tr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return o(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=pa(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let s=n.participants||[],d=[],l=[],h=null;return s.length&&(s.forEach(C=>{if(C.externalId){let P=he.fromSignaling(C.externalId);d.push(P),this._api.cacheExternalId(C.id.id,P)}else l.push(_.decomposeId(C.id.id).id)}),l.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(l)),n.hasMore&&(h=da(s[s.length-1].id))),{participants:d,pageMarker:h,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return o(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return o(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return o(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return o(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return o(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return o(this,null,function*(){var d;let n={movieId:e,participantId:(d=this._conversation)==null?void 0:d.compositeUserId};(t||t===0)&&(n.gain=t),i&&(n.offset=i),typeof r!==void 0&&(n.pause=r);let s=yield this._signaling.updateMovie(n);if(s.error)throw new Error(s.error)})}removeMovie(e){return o(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",n=null){return o(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},d=yield this._signaling.startStream(s);return d.error?Promise.reject(d.message):d})}stopStream(){return o(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return o(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return o(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return o(this,null,function*(){var r;if(e<p.videoMinWidth||t<p.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<p.videoMinWidth||i.effect.height<p.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");p.videoEffectMaxHeight=i.effect.height,p.videoEffectMaxWidth=i.effect.width}return p.videoMaxWidth=e,p.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return o(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}getParticipants(e){return o(this,null,function*(){let t=e.externalIds.map(s=>({id:s.id,type:this._getClientType()})),i=yield this._signaling.getParticipants(t);if(i.error)throw new Error(i.error);let r=i.participants,n=this._transport.getState();return Promise.all(r.map(s=>o(this,null,function*(){var l;let d=_.composeId(s);return this._createParticipant({id:d,externalId:s.externalId&&le.fromSignaling(s.externalId,s.deviceIdx||0),mediaSettings:me(s.mediaSettings),participantState:_.mapParticipantState(s),state:s.state,roles:s.roles||[],status:(l=this._getStatusByTransportState(n))!=null?l:$.WAITING,muteStates:s.muteStates||{},unmuteOptions:s.unmuteOptions||[],observedIds:s.observedIds||[],markers:this._denormalizeMarkers(d,s.markers)})}))).then(_.mapSharedParticipants)})}getParticipantListChunk(e){return o(this,null,function*(){let t=yield this._signaling.getParticipantListChunk(e);if(t.error)throw new Error(t.error);let i=t.chunk,r=i.participants.filter(d=>{let l=_.composeId(d);return!this._participants[l]});yield this._registerParticipants(r);let n=this._transport.getState();return i.participants.forEach(d=>{var C;let l=_.composeId(d),h=this._participants[l];h.status=(C=this._getStatusByTransportState(n))!=null?C:$.WAITING}),this._participantListChunkToExternalChunk(i)})}_getInitialParticiapntListChunk(){return o(this,null,function*(){let e=p.participantListChunkInitIndex,t=p.participantListChunkInitCount,i="GRID";return(yield this._signaling.getParticipantListChunk({listType:i,fromIdx:e,count:t})).chunk})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t,i;!this._conversation||(c.debug("Local media stream changed",e.mediaSettings),E.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return o(this,null,function*(){var t,i;if(c.log("Screen sharing changed",e.track,e.mediaSettings),p.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;E.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){c.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];if(!i){this._warnParticipantNotInConversation(e);return}i.mediaSettings=t,this._state==="ACTIVE"&&E.onRemoteMediaSettings(i.externalId,t,i.markers),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t)}_changeRemoteParticipantState(e,t){c.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];if(!i){this._warnParticipantNotInConversation(e);return}i.participantState=t||{},this._state==="ACTIVE"&&E.onRemoteParticipantState(i.externalId,i.participantState,i.markers)}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(c.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),E.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case w.ACCEPTED_CALL:return this._onAcceptedCall(e);case w.HUNGUP:return this._onHungup(e);case w.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case w.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case w.CLOSED_CONVERSATION:return this._onClosedConversation(e);case w.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case w.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case w.RATE_CALL_DATA:return this._onNeedRate();case w.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case w.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case w.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case w.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case w.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case w.REGISTERED_PEER:return this._onPeerRegistered(e);case w.SWITCH_MICRO:return this._onMicSwitched(e);case w.CHAT_MESSAGE:return this._onChatMessage(e);case w.CUSTOM_DATA:return this._onCustomData(e);case w.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case w.RECORD_STOPPED:return this._onRecordInfo(null);case w.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case w.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case w.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin,e.markers);case w.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case w.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case w.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case w.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants);case w.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e)}}_onSignalingReconnect(e){return o(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?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),r=[];for(let n of e.conversation.participants){let s=_.composeId(n),d=n.roles||[];if(s===this._conversation.compositeUserId){t=me(n.mediaSettings),Ct(this._conversation.roles,d)||this._onRolesChanged(s,d);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let h=me(n.mediaSettings);$r(h,l.mediaSettings)||this._changeRemoteMediaSettings(s,h);let C=_.mapParticipantState(n),P=l.participantState;_.isEqualParticipantState(C,P)||this._changeRemoteParticipantState(s,C),Ct(d,l.roles)||this._onRolesChanged(l.id,d)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],A.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){c.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return o(this,null,function*(){let t=_.composeMessageId(e),i=_.getPeerIdString(e.peerId);if(c.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new x(A.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(r=this._registerParticipantInCache(yield this._createParticipant({id:t,mediaSettings:me(e.mediaSettings)}))),r.state=W.ACCEPTED,r.mediaSettings=me(e.mediaSettings),this._logWithMediaSettings(v.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===We.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){return o(this,null,function*(){c.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=_.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new x(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===A.REJECTED?W.REJECTED:W.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,A.HUNGUP)})}_onAddedParticipant(e){return o(this,null,function*(){var r,n;c.debug(`Participant added [${e.participantId}]`);let t=_.composeMessageId(e),i=this._participants[t];if(i&&i.state!==W.HUNGUP&&i.state!==W.REJECTED){c.debug(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&le.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:me(e.participant.mediaSettings),state:e.participant.state,participantState:_.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}))),i.state=W.CALLED,i.mediaSettings=me((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=_.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],$.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),E.onParticipantAdded(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return o(this,null,function*(){var r,n;c.debug(`Participant joined [${e.participantId}]`);let t=_.composeMessageId(e),i=this._participants[t];if(i&&i.state===W.ACCEPTED){c.warn(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&le.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:me(e.participant.mediaSettings),state:e.participant.state,participantState:_.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[],markers:this._denormalizeMarkers(t,e.participant.markers)}))),this._conversation&&this._conversation.direction===We.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=W.ACCEPTED,i.mediaSettings=me(e.mediaSettings),i.participantState=_.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],$.CONNECTED):this._setParticipantsStatus([i],$.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((n=this._conversation)==null?void 0:n.observer))),E.onParticipantJoined(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new x(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){return o(this,null,function*(){let t=_.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,me(e.mediaSettings))})}_onParticipantStateChanged(e){return o(this,null,function*(){let t=_.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteParticipantState(t,_.mapParticipantState(e))})}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),E.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=me(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),p.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){c.debug("Got settings update notification",e);let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=qi(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){c.debug("Got video quality update notification",e);let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=qi(this._serverSettings,r),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=_.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return o(this,null,function*(){E.onDeviceSwitched(ne.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return o(this,null,function*(){let t=_.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),E.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return o(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=_.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),E.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return o(this,null,function*(){var i;if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let r=yield this._getParticipantId(e.initiator);E.onRecordStarted(r,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else E.onRecordStopped();this._conversation.recordInfo=e,e&&this._transport.getTopology()===oe.SERVER&&this._participantState!==W.CALLED&&this._transport.open(this._transport.allocated(),null,!!((i=this._conversation)==null?void 0:i.observer),!0)})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!Ct(this._conversation.roles,t)){c.debug(`Local roles changed: ${t}`),this._conversation.roles=t,E.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!Ct(i.roles,t)&&(c.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,E.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){c.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let d=this._participants[e.participantId];d&&(c.debug(`Mute states for participant [${e.participantId}] changed`,i),E.onMuteStates(i,r,n,e.muteAll,e.unmute,d.externalId,s==null?void 0:s.externalId));return}_.isObjectsEquals(this._conversation.muteStates,i)&&_.isArraysEquals(this._conversation.unmuteOptions,r)&&!n.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(n,e.muteAll,e.unmute,t,s)))})}_processMuteState(){return o(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==W.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),d=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),h=Object.entries(s);for(let[C,P]of h)if(!(P!==je.MUTE&&P!==je.MUTE_PERMANENT)&&(this._isCallAdmin()&&P===je.MUTE_PERMANENT&&(s[C]=je.MUTE),!(!e.includes(C)||i)))switch(C){case ne.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(E.onDeviceSwitched(ne.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case ne.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(E.onDeviceSwitched(ne.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case ne.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(E.onDeviceSwitched(ne.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}E.onMuteStates(s,d,e,t,i,null,n==null?void 0:n.externalId)})}_onPinParticipant(e,t=!1,i){return o(this,null,function*(){if(!this._conversation)return;let r=this._conversation.pinnedParticipantId;if(r&&r!==e)if(this._conversation.compositeUserId===r)E.onLocalPin(!0);else{let n=yield this._getExternalIdByParticipantId(r);n&&E.onPinnedParticipant(n,!0,this._denormalizeMarkers(e,i))}if(this._conversation.compositeUserId===e)E.onLocalPin(t);else{let n=yield this._getExternalIdByParticipantId(e);n&&E.onPinnedParticipant(n,t,this._denormalizeMarkers(e,i))}this._conversation.pinnedParticipantId=t?null:e})}_onOptionsChanged(e){this._conversation&&!Er(this._conversation.options,e)&&(this._conversation.options=e,E.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let n;if(i===this._conversation.compositeUserId||i==="")n=this._conversation.networkRating;else if(this._participants[i])n=this._participants[i].networkRating;else continue;if(n!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,E.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;c.log("Received network status update: ",e),E.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(p.producerScreenTrack){E.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,p.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){c.error("Received remote stream notification for a participant that has no track associated with it",r);return}let n=this._streamIdByStreamDescription.get(r);if(!n||this._streamWaitTimerByStreamDescription.has(r)){c.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(n);if(!s){m.log(v.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${n}`);return}E.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&E.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===oe.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Sr.ADD_PARTICIPANT);E.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&E.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}E.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){c.debug(`Transport state has changed: ${t}`,e);let i=this._getStatusByTransportState(t);if(!i)return;let r=e.reduce((n,s)=>{if(s in this._participants){let d=this._participants[s];n.push(d),t===B.CONNECTED&&(d.remoteStream||(d.mediaSettings&&this._changeRemoteMediaSettings(s,d.mediaSettings),this._changeRemoteParticipantState(s,d.participantState)),this._updateDisplayLayoutFromCache(s))}else this._warnParticipantNotInConversation(s);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){c.debug(`Local transport state has changed: ${e}`),e===B.CONNECTED&&E.onLocalStatus($.CONNECTED),e===B.CONNECTING&&E.onLocalStatus($.CONNECTING),e===B.RECONNECTING&&E.onLocalStatus($.RECONNECT),e===B.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(A.FAILED)),this._close(new x(A.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(Oe.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i),E.onRemoteMixedAudioStream(t);else if(e.startsWith(Oe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))c.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{c.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(c.warn(`Conversation: track added before participant [${e}]`),r=this._registerParticipantInCache(yield this._createParticipant({id:e})),this._setParticipantsStatus([r],$.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===ie.audio&&(this._audioOutput.add(i),p.preserveAudioTracks||t.removeTrack(i)),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;E.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),p.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(c.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case ie.audio:this._removeAudioTrack(e,t,i);break;case ie.video:case ie.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Oe.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e===oe.DIRECT&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let n=this._participants[r];e||this._lastStalled[r]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,$.RECONNECT),i.length&&this._setParticipantsStatus(i,$.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let s=this._participants[n];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let s=this._participants[n];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,$.RECONNECT),r.length&&this._setParticipantsStatus(r,$.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!y.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(c.debug("Toggle join availability",{available:t,chatId:e}),E.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==oe.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,s)=>(s.status!==t&&(s.status=t,p.batchParticipantsOnStart?n.push(s.externalId):E.onParticipantStatus(s.externalId,t,i)),n),[]);!r.length||p.batchParticipantsOnStart&&E.onRemoteStatus(r,t,i)}_onJoinLinkChanged(e){E.onJoinLinkChanged(e.joinLink)}},N=H;N._delayedHangup=!1;var di=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,di.prototype),this.participantErrors=t}};var Ut,pi=null;function Nn(){return o(this,null,function*(){var a;if(p.apiEnv!=="AUTO")return p.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(a=i==null?void 0:i.Answer[0])==null?void 0:a.data;if(!r)throw new Error("Wrong DNS response");return c.debug("Resolved API endpoint",r),r}catch(e){return c.warn("Failed to resolve API endpoint using DNS, default is used",e),p.apiEndpoint}})}function ha(){return Ut?Promise.resolve(Ut):pi||(pi=Nn().then(a=>Ut=a).finally(()=>pi=null))}function _a(){if(!p.apiKey)throw new x(ee.API,{message:"Required argument apiAppKey not passed"})}function Zi(i){return o(this,arguments,function*(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;yield ha();let r=fa(a,e,t),n=new window.Blob([r],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${Ut}/fb.do`,n)})}function ga(i){return o(this,arguments,function*(a,e={},t=!1){yield ha();let r=fa(a,e,t);return Un(r)})}function Un(a){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${Ut}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(n){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(a)})})}function fa(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=p.apiKey),t||(X.sessionKey?e.session_key=X.sessionKey:X.accessToken&&(e.access_token=X.accessToken));for(let[r,n]of Object.entries(e))typeof n=="object"&&(e[r]=JSON.stringify(n));let i="";for(let[r,n]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(n)}`;return i}var Vn=10,Fn=700,Gn=3e3,Bt=class extends ot{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return o(this,arguments,function*(e,t={},i=!1){let n=s=>o(this,null,function*(){try{return yield ga(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<Vn))return yield _.delay(Math.min(s*Fn,Gn)),n(s);throw c.warn(e,"error",d),d}});return n(0)})}_call(r){return o(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){c.warn("Api call error",n);let s=ee.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=A.SERVICE_DISABLED;break;case 1102:s=A.CALLEE_IS_OFFLINE;break;case 1103:s=A.NOT_FRIENDS;break;case 1104:case 1106:s=A.EXTERNAL_API_ERROR;break}throw new x(s,{message:n.error_msg,code:n.error_code})}})}userId(e){return o(this,null,function*(){let t=_.decomposeId(e).id;return X.isEmpty()?he.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),he.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return o(this,null,function*(){X.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return o(this,null,function*(){if(!this._uuid){let t=qe.get("uuid");t||(t=_.uuid(),qe.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)),X.sessionKey=t.session_key,X.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&E.onTokenExpired(),new x(ee.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})};Zi("log.externalLog",t)}init(){_a()}joinConversation(e,t=!1,i){return o(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:p.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return o(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1,protocolVersion:p.protocolVersion};return t&&(r.payload=t),p.domain&&(r.domainId=p.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,n="",s=!1,d=!1){return o(this,null,function*(){let l={conversationId:e,isVideo:r,protocolVersion:p.protocolVersion};if(t&&t.length)switch(i){case Be.USER:l.uids=t.join(",");break;case Be.GROUP:l.gid=t[0];break;case Be.CHAT:l.chatId=t[0];break}return s&&(l.createJoinLink=!0),n&&(l.payload=n),p.domain&&(l.domainId=p.domain),d&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return o(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return o(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return o(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return o(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i){return o(this,null,function*(){let r={joinLink:e,isVideo:t,protocolVersion:p.protocolVersion};return(i==null?void 0:i.length)&&(r.observedIds=i.join(",")),p.anonymToken&&(r.anonymToken=p.anonymToken),this._call("vchat.joinConversationByLink",r)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=he.fromIds(e),i=[],r={methods:[]},n=[],s=Object.keys(this._externalUidsCache),d=Object.values(this._externalUidsCache);for(let h of t){let C=he.toString(h),P=d.indexOf(C);P>-1?i.push(Number(s[P])):(n.push(C),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:h.id,anonym:h.type===tt.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((h,C)=>{if(h.ok){let P=Number(h.ok.ok_id);this._externalUidsCache[P]=n[C],i.push(P)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(he.fromString(this._externalUidsCache[n])):i.push(n);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let n of i)r.hasOwnProperty(n)&&t.push(he.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=he.toString(e),n=i.indexOf(r);return n>-1?_.composeUserId(t[n],Y.USER):null}cacheExternalId(e,t){let i=_.decomposeId(e).id;this._externalUidsCache[i]=he.toString(t)}getConversationParams(e){return o(this,null,function*(){let t={};return p.anonymToken&&(t.anonymToken=p.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:A.HUNGUP};p.anonymToken&&(t.anonymToken=p.anonymToken),Zi("vchat.hangupConversation",t)}removeHistoryRecords(e){return o(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return o(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,n]of Object.entries(i.external_ids))t[r]=he.fromIdToString(n,tt.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=he.fromIdToString(n,tt.ANONYM);return t}catch(i){return t}})}};var G=Ye(require("messagepack"));var Sa=(M=>(M.RECOVER="recover",M.ACCEPT_CALL="accept-call",M.ADD_PARTICIPANT="add-participant",M.REMOVE_PARTICIPANT="remove-participant",M.HANGUP="hangup",M.TRANSMIT_DATA="transmit-data",M.ACCEPT_PRODUCER="accept-producer",M.ALLOCATE_CONSUMER="allocate-consumer",M.CHANGE_MEDIA_SETTINGS="change-media-settings",M.CHANGE_PARTICIPANT_STATE="change-participant-state",M.CHANGE_STREAM_PRIORITIES="change-streams-priorities",M.UPDATE_DISPLAY_LAYOUT="update-display-layout",M.REPORT_PERF_STAT="report-perf-stat",M.RECORD_START="record-start",M.RECORD_STOP="record-stop",M.RECORD_SET_ROLE="record-set-role",M.RECORD_GET_STATUS="record-get-status",M.SWITCH_MICRO="switch-micro",M.SWITCH_TOPOLOGY="switch-topology",M.REQUEST_REALLOC="request-realloc",M.CHAT_MESSAGE="chat-message",M.CHAT_HISTORY="chat-history",M.CUSTOM_DATA="custom-data",M.GRANT_ROLES="grant-roles",M.MUTE_PARTICIPANT="mute-participant",M.PIN_PARTICIPANT="pin-participant",M.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",M.CHANGE_OPTIONS="change-options",M.GET_WAITING_HALL="get-waiting-hall",M.GET_PARTICIPANT_LIST_CHUNK="get-participant-list-chunk",M.GET_PARTICIPANTS="get-participants",M.PROMOTE_PARTICIPANT="promote-participant",M.REQUEST_TEST_MODE="request-test-mode",M.ADD_MOVIE="add-movie",M.UPDATE_MOVIE="update-movie",M.REMOVE_MOVIE="remove-movie",M))(Sa||{}),U=Sa;function li(){let a=new DataView(new ArrayBuffer(64)),e=0;function t(i){if(e+i>a.byteLength){let r=new Uint8Array(Math.max(e+i,a.byteLength+64));r.set(new Uint8Array(a.buffer.slice(0,e))),a=new DataView(r.buffer)}}return{put(i){if(t(i.byteLength),Hn(i)){let r=i.buffer;new Uint8Array(a.buffer).set(new Uint8Array(r),e)}else new Uint8Array(a.buffer).set(new Uint8Array(i),e);e+=i.byteLength},putI8(i){t(1),a.setInt8(e,i),++e},putI16(i){t(2),a.setInt16(e,i),e+=2},putI32(i){t(4),a.setInt32(e,i),e+=4},putI64(i){t(8);let r=i<0;r&&(i=-i);let n=i/4294967296|0,s=i%4294967296|0;r&&(s=~s+1|0,n=s===0?~n+1|0:~n),a.setUint32(e,n),a.setUint32(e+4,s),e+=8},putUi8(i){t(1),a.setUint8(e,i),++e},putUi16(i){t(2),a.setUint16(e,i),e+=2},putUi32(i){t(4),a.setUint32(e,i),e+=4},putUi64(i){t(8),a.setUint32(e,i/4294967296|0),a.setUint32(e+4,i%4294967296),e+=8},putF(i){t(8),a.setFloat64(e,i),e+=8},ui8array(){return new Uint8Array(a.buffer.slice(0,e))}}}function Hn(a){return a.buffer!==void 0}function er(a){let e=ArrayBuffer.isView(a)?new DataView(a.buffer,a.byteOffset,a.byteLength):new DataView(a),t=0;return{peek(){return e.getUint8(t)},get(i){t+=i;let r=e.byteOffset;return e.buffer.slice(r+t-i,r+t)},getI8(){return e.getInt8(t++)},getI16(){return t+=2,e.getInt16(t-2)},getI32(){return t+=4,e.getInt32(t-4)},getI64(){t+=8;let i=e.getInt32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getUi8(){return e.getUint8(t++)},getUi16(){return t+=2,e.getUint16(t-2)},getUi32(){return t+=4,e.getUint32(t-4)},getUi64(){t+=8;let i=e.getUint32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getF32(){return t+=4,e.getFloat32(t-4)},getF64(){return t+=8,e.getFloat64(t-8)}}}var va=0,Ea=1,Wn=0,jn=1,Kn=2,tr=0,qn=0,$n=0,Jn=1,ir=class{constructor(){this.participantIdRegistry=null}setParticipantIdRegistry(e){this.participantIdRegistry=e}serializeUpdateDisplayLayout(e,t){let i=li();G.Int.enc(i,va),G.Int.enc(i,tr),G.Int.enc(i,e),G.Nil.enc(i,null);let r=[];for(let n in t)t.hasOwnProperty(n)&&this.writeLayout(t,n,r);return G.Arr.enc(i,r),G.Nil.enc(i,null),i.ui8array()}writeLayout(e,t,i){let r=e[t],n=li();if(this.writeStreamDesc(t,n),kt(r))G.Int.enc(n,jn);else if(ji(r))G.Int.enc(n,Kn);else if(G.Int.enc(n,Wn),r.priority!==void 0?G.Int.enc(n,r.priority):G.Nil.enc(n,null),r.width!==void 0&&r.height!==void 0?(G.Int.enc(n,Math.round(r.width)),G.Int.enc(n,Math.round(r.height))):(G.Nil.enc(n,null),G.Nil.enc(n,null)),r.fit!==void 0)switch(r.fit){case"cv":G.Int.enc(n,$n);break;case"cn":G.Int.enc(n,Jn);break;default:G.Nil.enc(n,null)}else G.Nil.enc(n,null);i.push(n.ui8array())}writeStreamDesc(e,t){if(this.participantIdRegistry){let i=this.participantIdRegistry.getCompactId(e);if(i!==void 0){G.Int.enc(t,i);return}}G.Str.enc(t,e)}serializePerfStatReport(e,t){let i=li();return G.Int.enc(i,Ea),G.Int.enc(i,tr),G.Int.enc(i,e),G.Int.enc(i,t.framesDecoded),G.Int.enc(i,t.framesReceived),i.ui8array()}deserializeCommandResponse(e){let t=er(e),i=G.Int.dec(t),r=G.Int.dec(t);if(r!==tr){c.warn("Unsupported version for command type: "+i+", version "+r);return}if(G.Int.dec(t)!==qn){c.warn("Error code: "+i+"received for command type: "+i+", version "+r);return}switch(i){case va:return this.deserializeUpdateDisplayLayoutResponse(t);case Ea:return this.deserializeReportPerfStatResponse(t);default:return c.warn("unsupported command response commandType: "+i),null}}deserializeUpdateDisplayLayoutResponse(e){let t=G.Int.dec(e),i=G.Arr.dec(e),r={};return i.forEach(n=>{let s=er(n),d=G.Any.dec(s);if(typeof d=="string")r[d]=G.Int.dec(s);else{let l=d,h=He(this.participantIdRegistry.getStreamDescription(l));r[h]=G.Int.dec(s)}}),{type:"response",sequence:t,response:U.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:r}}deserializeReportPerfStatResponse(e){let t=G.Int.dec(e),i=G.Int.dec(e);return{type:"response",sequence:t,response:U.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:i}}};var Ta="open",Ia=[()=>p.producerScreenTrack,()=>p.videoTracksCount>0,()=>!0,()=>p.filteredMessages,()=>p.consumerScreenTrack,()=>!0,()=>p.movieShare,()=>p.useParticipantListChunk],Yn=10,be=class extends dt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+p.platform+"&appVersion="+p.appVersion+"&version="+p.protocolVersion+"&device="+p.device+"&capabilities="+be._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.producerCommandDataChannelEnabled=!1;this.producerCommandSerializationService=new ir}static _getCapabilityFlags(){let e=0;for(let t=0;t<Ia.length;t++)Ia[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 r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=t=>{let i=this.producerCommandSerializationService.deserializeCommandResponse(t.data);i&&this._handleMessage(i)},this._handleCommandsQueue(this.datachannelCommandsQueue)}useCommandDataChannel(e){this.producerCommandDataChannelEnabled=e}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return o(this,null,function*(){return this.postfix+=`&clientType=${p.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){m.log(v.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return o(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=_.decomposeParticipantId(t.participantId),s=_.decomposeId(n.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),n.deviceIdx&&(t.deviceIdx=n.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return o(this,arguments,function*(e,t={},i=0){let n=s=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===Ta&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){m.log(v.SOCKET_ACTION,"not_opened"),c.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(m.log(v.SOCKET_ACTION,"invalid_state"),c.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,d)=>{let l=(C,P=!1)=>{!i||P?d(C):(c.debug("Resending a signaling message",e,h.sequence),i--,n(h))},h={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};n(h)})})}_isDataChannelCommand(e){return this.producerCommandDataChannelEnabled?e===U.UPDATE_DISPLAY_LAYOUT||e===U.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===U.UPDATE_DISPLAY_LAYOUT||e===U.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(U.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(U.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e,t){return o(this,null,function*(){return this._send(U.REQUEST_TEST_MODE,{consumer:e,producer:t})})}sendSdp(e,t){return o(this,null,function*(){return this._send(U.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(U.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(U.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},Yn)})}changeParticipantState(e){return o(this,null,function*(){return this._send(U.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(U.ADD_PARTICIPANT,st({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(U.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return o(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(U.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(U.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(U.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(U.UPDATE_DISPLAY_LAYOUT,e)})}addMovie(e){return o(this,null,function*(){return this._send(U.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(U.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(U.REMOVE_MOVIE,e)})}startStream(e){return o(this,null,function*(){return this._send(U.RECORD_START,e)})}stopStream(){return o(this,null,function*(){return this._send(U.RECORD_STOP)})}recordSetRole(e,t){return o(this,null,function*(){return this._send(U.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return o(this,null,function*(){return this._send(U.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(U.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(U.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(U.REPORT_PERF_STAT,e)})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(U.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(U.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(U.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return o(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(U.GRANT_ROLES,r)})}muteParticipant(e,t,i){return o(this,null,function*(){return this._sendRaw(U.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return o(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(U.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(U.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(U.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return o(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(U.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(U.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}getParticipantListChunk(e){return o(this,null,function*(){return this._send(U.GET_PARTICIPANT_LIST_CHUNK,e)})}getParticipants(e){return o(this,null,function*(){return this._send(U.GET_PARTICIPANTS,{externalIds:e})})}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ve.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),t=i(t),c.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor();function i(r){if(!p.useParticipantListChunk)return r;r+=`&partIdx=${p.participantListChunkInitIndex}`;let s=p.participantListChunkInitCount;return s!==null&&(r+=`&partCount=${s}`),r}}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){c.debug("Socket opened"),m.log(v.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){m.log(v.SOCKET_ACTION,"parse_error"),c.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(c.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(ge.RECONNECT,e),e.conversation.topology&&this._triggerEvent(ge.NOTIFICATION,{type:"notification",notification:w.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(ge.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(m.log(v.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(m.log(v.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new x(A.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(ge.NOTIFICATION,{notification:w.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new x(ee.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(m.log(v.SOCKET_ACTION,"unknown_message"),c.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(ge.FAILED,e)}_onError(e){m.log(v.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){m.log(v.SOCKET_ACTION,"closed"),c.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<be.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(be.RECONNECT_MAX_DELAY,be.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),m.log(v.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ve.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],m.log(v.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),be.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift();if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==Ta){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}be._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:r.name,sequence:r.sequence}),be.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r);let s=this._serializeBinary(r);s!==null&&this.producerCommandDataChannel.send(s)}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:r.name,sequence:r.sequence}),be.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(this._serializeJson(r))}}}_serializeBinary(e){switch(e.name){case U.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case U.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params)}return c.warn("cannot get binary data for data channel command: "+e.name),null}_serializeJson(e){let t;e.name===U.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 r in t)t.hasOwnProperty(r)&&(i[r]=sa(t[r]));return{layouts:i}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new x(ee.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},be.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{c.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Ve.RETRY)},be.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},xe=be;xe.RECONNECT_DELAY=p.signalingReconnectDelay,xe.RECONNECT_MAX_DELAY=p.signalingReconnectMaxDelay,xe.RECONNECT_MAX_COUNT=p.signalingReconnectMaxCount,xe.WAIT_CONNECTION_DELAY=p.waitConnectionDelay,xe.WAIT_RESPONSE_DELAY=p.waitResponseDelay,xe.WAIT_MESSAGE_DELAY=p.waitMessageDelay;var Ca=(t=>(t.KING="KING",t.PAWN="PAWN",t))(Ca||{}),ya=Ca;var Et,re,Vt=null,zn={getCameras:y.getCameras,getMicrophones:y.getMicrophones,getOutput:y.getOutput,hasCamera:y.hasCamera,hasMicrophone:y.hasMicrophone,getSavedCamera:y.getSavedCamera,getSavedMicrophone:y.getSavedMicrophone,getSavedOutput:y.getSavedOutput,hasCameraPermission:y.hasCameraPermission,hasMicrophonePermission:y.hasMicrophonePermission,hasPermissions:y.hasPermissions,getUserMedia:y.getUserMedia,getUserVideo:y.getUserVideo,getUserAudio:y.getUserAudio,saveDeviceId:y.saveDeviceId,isBrowserSupported:y.isBrowserSupported,isScreenCapturingSupported:y.isScreenCapturingSupported,os:y.os,isMobile:y.isMobile,browserName:y.browserName,browserVersion:y.browserVersion,baseChromeVersion:y.baseChromeVersion,getAudioContext:y.getAudioContext};function Pa(a){re=a}function Ra(a){Et=a}function Qn(a){Vt=a}function Xn(a){p.videoEffects=a}function Zn(a){return o(this,null,function*(){if(p.set(a),y.browserName()==="Sferum"&&(p.platform=`SFERUM:${y.browserVersion()}`),re||Pa(new Bt),Et||Ra(()=>new xe),p.debug&&(rr.default.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${p.sdkVersion}`,a),yield y.init(),!y.isBrowserSupported())throw new x(ee.UNSUPPORTED);re.init()})}function es(n){return o(this,arguments,function*(a,e=[ne.AUDIO],t="",i=!1,r=!1){let s=[],d=[];if(Array.isArray(a)?s=a.length?a:[]:a&&(s=[a]),s.length&&(d=yield re.getOkIdsByExternalIds(s),!d.length))throw new x(A.CALLEE_IS_OFFLINE);return ba(d,Be.USER,e,t,i,r)})}function ba(s){return o(this,arguments,function*(a,e=Be.USER,t,i="",r=!1,n=!1){if(N.current())throw c.error("There is already active call"),new x(A.FAILED);return new N(re,Et(),Vt).onStart(a,e,t,i,r,n)})}function ts(a){return o(this,null,function*(){return Ma(a)})}function Ma(i){return o(this,arguments,function*(a,e=Y.USER,t){if(a===N.id())throw new Error("Push has already been processed");return new N(re,Et(),Vt).onPush(a,e,t)})}function is(a){return o(this,null,function*(){return a&&(p.authToken=a),re.authorize()})}function rs(){return o(this,arguments,function*(a=[ne.AUDIO]){return Ft().accept(a)})}function as(){return o(this,null,function*(){let a=N.current();if(a)return a.decline()})}function ns(t){return o(this,arguments,function*(a,e=[ne.AUDIO]){return Da(a,e)})}function Da(a,e,t){return o(this,null,function*(){if(N.current())throw c.error("There is already active call"),new x(A.FAILED);return new N(re,Et(),Vt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function ss(r){return o(this,arguments,function*(a,e=[ne.AUDIO],t,i){if(N.current())throw c.error("There is already active call"),new x(A.FAILED);return t&&(p.anonymToken=t),new N(re,Et(),Vt).onJoin({joinLink:a,mediaOptions:e,observedIds:i})})}function os(){return o(this,null,function*(){let a=N.current();if(a)return a.hangup();N.hangupAfterInit()})}function cs(a,e){return o(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return Aa(t[0],e)})}function Aa(a,e){return o(this,null,function*(){let t=N.current();t&&(yield t.addParticipant(_.composeUserId(a,Y.USER),e))})}function ds(a,e=!1){return o(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);return ka(t[0],e)})}function ka(a,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.removeParticipant(_.composeUserId(a,Y.USER),e))})}function ps(a,e){return o(this,null,function*(){let t=yield y.saveDeviceId(a,e),i=N.current();return t&&i?i.changeDevice(a):Promise.reject()})}function ls(a){return o(this,null,function*(){let e=N.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function us(a,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.setVideoStream(a,e))})}function ms(a){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalVideo(a))})}function hs(a){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalAudio(a))})}function _s(a,e,t){return o(this,null,function*(){let i=N.current();if(i)return i.setLocalResolution(a,e,t)})}function gs(a){return o(this,null,function*(){let e=N.current();e&&(yield e.changePriorities(a))})}function fs(a){return o(this,null,function*(){let e=N.current();e&&(yield e.changeParticipantState(a))})}function Ss(a){return o(this,null,function*(){let e=N.current();e&&(yield e.updateDisplayLayout(a))})}function vs(a,e,t=!1){return o(this,null,function*(){let i=yield re.getOkIdsByExternalIds([a]);return Oa(i[0],e,t)})}function Oa(a,e,t=!1){return o(this,null,function*(){let i=N.current();i&&(yield i.grantRoles(_.composeUserId(a,Y.USER),e,t))})}function Es(){return o(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield re.getOkIdsByExternalIds([a]))[0]),wa(i,e,t,le.getDeviceIdx(a))})}function wa(){return o(this,arguments,function*(a=null,e,t=[],i=0){let r=N.current();if(r){let n=a?_.composeParticipantId(a,Y.USER,i):null;yield r.muteParticipant(n,e,t)}})}function Ts(a,e=!1){return o(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);return xa(t[0],e,le.getDeviceIdx(a))})}function xa(a,e=!1,t=0){return o(this,null,function*(){let i=N.current();i&&(yield i.pinParticipant(_.composeParticipantId(a,Y.USER,t),e))})}function Is(a){return o(this,null,function*(){let e=N.current();e&&(yield e.updateMediaModifiers(a))})}function Cs(a){return o(this,null,function*(){let e=N.current();e&&(yield e.changeOptions(a))})}function ys(a,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield re.getOkIdsByExternalIds([e]))[0]),La(a,t)})}function La(a,e=null){return o(this,null,function*(){let t=N.current();if(t){let i=e?_.composeUserId(e,Y.USER):null;yield t.chatMessage(a,i)}})}function Ps(a=10){return o(this,null,function*(){let e=N.current();if(e)return e.chatHistory(a)})}function Rs(a,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield re.getOkIdsByExternalIds([e]))[0]),Na(a,t,le.getDeviceIdx(e))})}function Na(a,e=null,t=0){return o(this,null,function*(){let i=N.current();if(i){let r=e?_.composeParticipantId(e,Y.USER,t):null;yield i.customData(a,r)}})}function bs(a="",e=!1){return o(this,null,function*(){return(yield re.createConversation(_.uuid(),a,e)).join_link})}function Ms(){return o(this,null,function*(){let a=N.current();return a?a.createJoinLink():Promise.reject()})}function Ds(){return o(this,null,function*(){let a=N.current();return a?a.removeJoinLink():Promise.reject()})}function As(a,e){return o(this,null,function*(){return re.getAnonymTokenByLink(a,e)})}function ks(a){let e=N.current();e&&e.setVolume(a)}function Os(a){p.forceRelayPolicy=a}function ws(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return o(this,null,function*(){let n=N.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function xs(){return o(this,null,function*(){let a=N.current();return a?a.stopStream():Promise.reject()})}function Ls(a,e){return o(this,null,function*(){let t=N.current();if(t){let i=yield re.getOkIdsByExternalIds([a]),r=le.getDeviceIdx(a);return t.recordSetRole(_.composeParticipantId(i[0],Y.USER,r),e)}return Promise.reject()})}function Ns(){return o(this,null,function*(){let a=N.current();return a?a.getStreamInfo():Promise.reject()})}function Us(a){return o(this,null,function*(){let e=N.current();return e?e.addMovie(a):Promise.reject()})}function Bs(a,e,t,i){return o(this,null,function*(){let r=N.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function Vs(a){return o(this,null,function*(){let e=N.current();return e?e.removeMovie(a):Promise.reject()})}function Fs(a){p.statisticsInterval=a;let e=N.current();if(e)return e.updateStatisticsInterval()}function Gs(a){rr.default.disableLog(!a),c.toggle(a)}function Hs(a,...e){!p.debugLog||c.send(a,"[external]",...e)}function Ws(a){return o(this,null,function*(){let e=N.current();if(e)return e.videoEffect(a)})}function js(a){return o(this,null,function*(){let e=N.current();e&&(yield e.setAudioStream(a))})}function Ks(a=null,e,t=!1){return o(this,null,function*(){return Ft().getWaitingHall(a,e,t)})}function qs(a,e=!1){return o(this,null,function*(){let t=Ft(),i=yield re.getOkIdsByExternalIds([a]);return t.promoteParticipant(_.composeUserId(i[0],Y.USER),e)})}function $s(a){return o(this,null,function*(){return Ft().getParticipantListChunk(a)})}function Js(a){return o(this,null,function*(){return Ft().getParticipants(a)})}function Ft(){let a=N.current();if(!a)throw new Error("Conversation not found");return a}function Ys(a){return o(this,null,function*(){yield re.removeHistoryRecords(a)})}function zs(){return p.sdkVersion}
|
|
7
|
+
var Fa=Object.create;var Ct=Object.defineProperty,Ga=Object.defineProperties,Ha=Object.getOwnPropertyDescriptor,Wa=Object.getOwnPropertyDescriptors,ja=Object.getOwnPropertyNames,dr=Object.getOwnPropertySymbols,Ka=Object.getPrototypeOf,pr=Object.prototype.hasOwnProperty,qa=Object.prototype.propertyIsEnumerable;var lr=Math.pow,ur=(a,e,t)=>e in a?Ct(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,ct=(a,e)=>{for(var t in e||(e={}))pr.call(e,t)&&ur(a,t,e[t]);if(dr)for(var t of dr(e))qa.call(e,t)&&ur(a,t,e[t]);return a},_i=(a,e)=>Ga(a,Wa(e)),mr=a=>Ct(a,"__esModule",{value:!0});var $a=(a,e)=>{mr(a);for(var t in e)Ct(a,t,{get:e[t],enumerable:!0})},Ja=(a,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ja(e))!pr.call(a,i)&&i!=="default"&&Ct(a,i,{get:()=>e[i],enumerable:!(t=Ha(e,i))||t.enumerable});return a},ze=a=>Ja(mr(Ct(a!=null?Fa(Ka(a)):{},"default",a&&a.__esModule&&"default"in a?{get:()=>a.default,enumerable:!0}:{value:a,enumerable:!0})),a);var o=(a,e,t)=>new Promise((i,r)=>{var n=l=>{try{p(t.next(l))}catch(m){r(m)}},s=l=>{try{p(t.throw(l))}catch(m){r(m)}},p=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,s);p((t=t.apply(a,e)).next())});$a(exports,{Api:()=>Vt,BaseApi:()=>dt,BaseLogger:()=>pt,BaseSignaling:()=>lt,CallDirection:()=>je,CallType:()=>Ve,ChatRoomEventType:()=>Ht,ConversationOption:()=>Wt,DebugMessageType:()=>Gi,ExternalIdType:()=>rt,FacingMode:()=>Ni,FatalError:()=>ie,HangupReason:()=>x,HangupType:()=>M,MediaOption:()=>ce,MediaTrackKind:()=>ae,MediaType:()=>Te,MuteState:()=>Ke,ParticipantState:()=>j,ParticipantStatus:()=>J,RecordRole:()=>ya,Signaling:()=>Le,SignalingCommandType:()=>B,SignalingConnectionType:()=>Fe,SignalingNotification:()=>w,UserRole:()=>Qe,UserType:()=>z,Utils:()=>S,acceptCall:()=>ns,addMovie:()=>Vs,addParticipant:()=>ps,addParticipantInternal:()=>Aa,authorize:()=>as,browser:()=>Xn,callInternal:()=>ba,callTo:()=>is,captureScreen:()=>ms,changeConversationOptions:()=>Ps,changeDevice:()=>us,changeParticipantState:()=>vs,changePriorities:()=>Ss,changeVideoEffect:()=>Ks,chatHistory:()=>bs,chatMessage:()=>Rs,chatMessageInternal:()=>La,createJoinLink:()=>As,customData:()=>Ms,customDataInternal:()=>Na,debug:()=>Ws,debugMessage:()=>js,declineCall:()=>ss,forceRelayPolicy:()=>xs,getAnonymTokenByLink:()=>Os,getParticipantListChunk:()=>Ys,getParticipants:()=>zs,getStreamInfo:()=>Bs,getWaitingHall:()=>$s,grantRoles:()=>Ts,grantRolesInternal:()=>Oa,hangup:()=>ds,init:()=>ts,joinCall:()=>os,joinCallByLink:()=>cs,joinCallInternal:()=>Da,muteParticipant:()=>Is,muteParticipantInternal:()=>wa,pinParticipant:()=>Cs,pinParticipantInternal:()=>xa,processPush:()=>rs,processPushInternal:()=>Ma,promoteParticipant:()=>Js,recordSetRole:()=>Us,removeHistoryRecords:()=>Qs,removeJoinLink:()=>ks,removeMovie:()=>Gs,removeParticipant:()=>ls,removeParticipantInternal:()=>ka,setApi:()=>Pa,setAudioStream:()=>qs,setLocalResolution:()=>fs,setLogger:()=>Zn,setMediaModifiers:()=>ys,setSignalingFactory:()=>Ra,setStatisticsInterval:()=>Hs,setVideoEffects:()=>es,setVideoStream:()=>hs,setVolume:()=>ws,startConversation:()=>Ds,startStream:()=>Ls,stopStream:()=>Ns,toggleLocalAudio:()=>gs,toggleLocalVideo:()=>_s,updateDisplayLayout:()=>Es,updateMovie:()=>Fs,version:()=>Xs});var ir=ze(require("webrtc-adapter"));var dt=class{createJoinLink(e){return o(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return o(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return o(this,null,function*(){return""})}log(e){}prepareUserIds(e){return o(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return o(this,null,function*(){})}cleanup(){}};var pt=class{log(e,t,i=!1){}destroy(){}};var X=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var lt=class extends X{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e,t){}getNextCommandSequenceNumber(){return 0}};var hr=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(hr||{}),je=hr;var _r=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(_r||{}),Ve=_r;var gr=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(gr||{}),Ht=gr;var fr=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(fr||{}),Sr=fr;var vr=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(vr||{}),Wt=vr;function Er(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function Tr(a,e){let t=new Set(a);for(let[i,r]of Object.entries(e))r?t.add(i):t.delete(i);return Array.from(t)}var Ir=($=>($.CAMERA_PERMISSION="camera",$.MIC_PERMISSION="mic",$.CAMERA_ACCESS="cameralock",$.MIC_ACCESS="miclock",$.MIC_NOT_FOUND="nomic",$.SCREEN_PERMISSION="screenpermission",$.SCREEN_ACCESS="screenlock",$.CONNECTION="connection",$.NETWORK="network",$.UNKNOWN="unknown",$.UNSUPPORTED="unsupported",$.SIGNALING_FAILED="signalingfailed",$.API="api",$.AUTH="auth",$))(Ir||{}),ie=Ir;var Cr=(Y=>(Y.CANCELED="CANCELED",Y.REJECTED="REJECTED",Y.REMOVED="REMOVED",Y.HUNGUP="HUNGUP",Y.MISSED="MISSED",Y.BUSY="BUSY",Y.FAILED="FAILED",Y.NETWORK_ERROR="NETWORK_ERROR",Y.KILLED="KILLED",Y.BANNED="BANNED",Y.HAS_ACTIVE_CALL="HAS_ACTIVE_CALL",Y.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",Y.NOT_FRIENDS="NOT_FRIENDS",Y.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",Y.UNKNOWN_ERROR="UNKNOWN_ERROR",Y.UNSUPPORTED="UNSUPPORTED",Y.OLD_VERSION="OLD_VERSION",Y.SERVICE_DISABLED="SERVICE_DISABLED",Y.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",Y.SOCKET_CLOSED="SOCKET_CLOSED",Y.ENDED="ENDED",Y.KILLED_WITHOUT_DELETE="KILLED_WITHOUT_DELETE",Y))(Cr||{}),M=Cr;var yr=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(yr||{}),ce=yr;var Pr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(Pr||{}),Ke=Pr;var Rr=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(Rr||{}),j=Rr;var br=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(br||{}),Fe=br;var Mr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(Mr||{}),Se=Mr;var Dr=(D=>(D.TRANSMITTED_DATA="transmitted-data",D.ACCEPTED_CALL="accepted-call",D.HUNGUP="hungup",D.PARTICIPANT_ADDED="participant-added",D.PARTICIPANT_JOINED="participant-joined",D.CLOSED_CONVERSATION="closed-conversation",D.MEDIA_SETTINGS_CHANGED="media-settings-changed",D.PARTICIPANT_STATE_CHANGED="participant-state-changed",D.RATE_CALL_DATA="rate-call-data",D.FEATURE_SET_CHANGED="feature-set-changed",D.TOPOLOGY_CHANGED="topology-changed",D.PRODUCER_UPDATED="producer-updated",D.CONSUMER_ANSWERED="consumer-answered",D.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",D.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",D.SETTINGS_UPDATE="settings-update",D.VIDEO_QUALITY_UPDATE="video-quality-update",D.REGISTERED_PEER="registered-peer",D.SWITCH_MICRO="switch-micro",D.RECORD_STARTED="record-started",D.RECORD_STOPPED="record-stopped",D.REALLOC_CON="realloc-con",D.AUDIO_ACTIVITY="audio-activity",D.SPEAKER_CHANGED="speaker-changed",D.STALLED_ACTIVITY="stalled-activity",D.CHAT_MESSAGE="chat-message",D.CUSTOM_DATA="custom-data",D.ROLES_CHANGED="roles-changed",D.MUTE_PARTICIPANT="mute-participant",D.PIN_PARTICIPANT="pin-participant",D.OPTIONS_CHANGED="options-changed",D.NETWORK_STATUS="network-status",D.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",D.PROMOTE_PARTICIPANT="promote-participant",D.CHAT_ROOM_UPDATED="chat-room-updated",D.PROMOTION_APPROVED="promotion-approved",D.JOIN_LINK_CHANGED="join-link-changed",D))(Dr||{}),w=Dr;var Ar=(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))(Ar||{}),g=Ar;var kr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(kr||{}),we=kr;var Or=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(Or||{}),wr=Or;function xr(a){switch(a){case 1:return"no-available-tracks";default:return"unknown-error"}}var Lr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(Lr||{}),Qe=Lr;function yt(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var Nr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(Nr||{}),z=Nr;var gi=class{constructor(){this._items=[]}get length(){return this._items.length}push(e){this._items.push(e)}shift(){return this._items.shift()||null}bisect(){let e=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(e)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(e,t)=>t instanceof Error?String(t):t):""}};var Ur=2*1024*1024,Ya=512*1024,Pt=100*1024,za=5,fi="_okcls_logs_session_",Qa=3e4,Br=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=Ur;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(fi)!==0)continue;let i=e.getItem(t);if(!i){Gr(t);continue}let r=Fr(i);this.add(t,r)}}catch(e){console.error("Storage is blocked",e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(Pt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(fi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Gr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>Ur||this.length>za-1||this.size+e>this.available);)this.deleteOldestItem()}};function Vr(){return`${fi}${Date.now()}`}function Fr(a){return new Blob([a]).size}function Gr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function Si(){let a=Xe.toString();if(!Ee.available||!a)return;let e=Fr(a);Ee.cleanup(e);try{window.localStorage.setItem(jt,a)}catch(t){if(console.warn("Failed to write log to storage",t),Ee.storageSize=Ee.size+e,Ee.cleanup(Pt+e),Ee.available>=Pt+e){Si();return}if(e>Pt){Xe.bisect(),Si();return}Ee.storageSize=0;return}e>Ya&&(Ee.add(jt,e),jt=Vr(),Xe.clear(),Ee.cleanup(Pt))}function vi(){!Ee.available||!Xe.length||Si()}function Xa(a=!1){let e=[];try{let r=window.localStorage;for(let s of Ee.items){let p=r.getItem(s.key);e.push(p)}let n=Xe.toString();n&&e.push(n)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(a)return t;let i=`logs_${Date.now()}.json`;return Za(t,i),i}function Za(a,e){let t=document.createElement("a"),i=new Blob([a],{type:"text/json"});t.href=URL.createObjectURL(i),t.download=e,t.click()}function Hr(a,e){!Ee.available||(Xe.push({t:Date.now(),l:a,d:e}),Ti||(Ti=window.setTimeout(()=>{Ti=null,vi()},Qa)))}function Ei(){Ee||(Ee=new Br,Xe=new gi,jt=Vr(),window.addEventListener("beforeunload",vi))}var Ee,Xe,jt,Ti=null;window.__VKCallsSDKLogs__=(a=!1)=>(Ee||Ei(),vi(),Xa(a));var Ii=ze(require("@vkontakte/libvpx"));var ve=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(ve||{});var u=class extends pt{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={};typeof t!="undefined"&&(r.param=t),this._logInternal(e,r,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){u._instance||(u._instance=new u(e,t))}static log(e,t,i=!1){u._instance&&u._instance.log(e,t,i)}static logCustom(e,t,i=!1){u._instance&&u._instance.logCustom(e,t,i)}static destroy(){u._instance&&u._instance.destroy(),u._instance=null}};var Ge=class{constructor(){this._worker=null}_createWorker(s,p){return o(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((l,m)=>{let I=i.join(","),R=new Blob([e,`exports.default(${I});`],{type:"application/javascript; charset=utf-8"}),O=window.URL.createObjectURL(R);this._worker=new Worker(O),this._worker.onmessage=L=>{switch(L.data.type){case ve.READY:l();break;case ve.ERROR:m(L.data.error);break;case ve.FRAME:t(L.data);break;case ve.DEBUG:c.debug(L.data.message);break;case ve.LOG_ERROR:u.log(g.ERROR,L.data.message);break}},this._sendToWorker(ve.INIT,r,n)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var ut=class extends Ge{init(e){return o(this,null,function*(){c.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var b=Object.defineProperty;var E=a=>b(a,"__esModule",{value:!0});var M=(a,p)=>{E(a);for(var e in p)b(a,e,{get:p[e],enumerable:!0})};var V={};M(V,{default:()=>D});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var D=(a,p)=>{let e=null,n=null,g=!0;function y(){return a({locateFile:p}).then(r=>n=r)}function s(r,m,l,R,x){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(x),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let d=e.getImageBuffer();if(!d){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let c=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(d.byteLength);if(i.set(d),R){let o=new ImageData(i,c,f);createImageBitmap(o,0,0,c,f).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:i.buffer,width:c,height:f},[i.buffer])}y().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return V;})();\n',t=>{if(t.error)c.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i)}else e(t.data)},[Ii.default,Ii.default.getUrl])})}decodeFrame(e,t,i,r){let n="ImageBitmap"in window;this._sendToWorker(ve.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:n,debug:c.enabled()},[t.buffer])}destroy(){this._removeWorker(),c.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var Ci="_okcls_",mt=(()=>{try{let a=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(a,a),t=e.getItem(a)===a,e.removeItem(a),t?e:null}catch(a){return null}})();function tn(a){let e=mt?mt.getItem(Ci+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function rn(a,e){try{mt&&mt.setItem(Ci+a,JSON.stringify(e))}catch(t){}}function an(a){mt&&mt.removeItem(Ci+a)}var yi;(i=>{function a(r){return tn(r)||null}i.get=a;function e(r,n){rn(r,n)}i.set=e;function t(r){an(r)}i.remove=t})(yi||(yi={}));var $e=yi;function Wr(a,e){if(a.isAudioEnabled!==e.isAudioEnabled||a.isVideoEnabled!==e.isVideoEnabled||a.isScreenSharingEnabled!==e.isScreenSharingEnabled||a.videoStreams.length!==e.videoStreams.length)return!1;for(let t of a.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function ge(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}var jr=a=>a.stop(),Kr=a=>a.getTracks().forEach(jr),Pi=a=>a.getVideoTracks().forEach(jr),qr=a=>a.getVideoTracks()[0].clone();var x=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(M).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,x)}};var Pe=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(Pe||{}),ae=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(ae||{}),Ri=class extends X{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=ge();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return o(this,arguments,function*(e=[ce.AUDIO],t=!0){if(this._stream)return;let i=e.includes(ce.VIDEO),r=e.includes(ce.AUDIO);if(!C.isBrowserSupported())throw new x(ie.UNSUPPORTED);try{this._stream=yield C.getUserMedia(i,r,t),this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(n=>n.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=r&&this._stream.getAudioTracks().filter(n=>n.enabled).length>0||!1}catch(n){throw new x(n)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t,i,r){let n=this.getStream(),s=this._getSendAudioTrack(),p=this.getSendVideoTrack(i);if(!n||!s&&!p&&!t)throw new Error("No local stream found");if(s&&!t){if(r){let{codecs:l}=RTCRtpSender.getCapabilities("audio"),m="audio/red",I=48e3,R=l.findIndex(O=>O.mimeType===m&&O.clockRate===I);if(R>=0){let O=[];O.push(l[R]);for(let L=0;L<l.length;L++)L!==R&&O.push(l[L]);e.getTransceivers().forEach(L=>L.setCodecPreferences(O))}}e.addTrack(s,n)}p&&!t&&e.addTrack(p,n)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return o(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return o(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=S.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);this._onDeviceChange=()=>o(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),s=n&&n.deviceId,p=this._stream.getVideoTracks()[0],l=p&&p.enabled&&p.getSettings(),m=l&&l.deviceId;if(!s&&!m)return;let I=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!I.find(R=>R.deviceId===s)),!t&&m&&(t=!I.find(R=>R.deviceId===m)),i()}),navigator.mediaDevices.addEventListener("devicechange",this._onDeviceChange)}_destroyDeviceChangeListener(){this._onDeviceChange&&navigator.mediaDevices.removeEventListener("devicechange",this._onDeviceChange)}_changeVideoInput(e=null){return o(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield C.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{d.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),n=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),u.log(g.DEVICE_CHANGED,t),c.log("Video stream changed"),yield this._replaceLocalTrack(n),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(g.ERROR,"change_video"),c.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=qr(e)),t=this._trackVideoStreamBackup.clone(),Pi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),Pi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return o(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return o(this,null,function*(){try{if(e=e||(yield C.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),u.log(g.DEVICE_CHANGED,"audio"),c.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(g.ERROR,"change_audio"),c.error("Microphone change failed",t),t}})}_changeScreen(e){return o(this,null,function*(){try{if(e=e||(yield C.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=d.consumerScreenTrack?t:yield this._videoEffect(null,t);u.log(g.DEVICE_CHANGED,"screen"),c.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,d.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=d.consumerScreenDataChannel?C.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(g.ERROR,"screen"),c.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return o(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,n;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(n=this._stream)==null||n.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return o(this,null,function*(){if(!d.videoEffects)return t;try{return u.log(g.DEVICE_CHANGED,`effect_${e}`),d.videoEffects.setEffect(e,t)}catch(i){return c.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){this._destroyDeviceChangeListener(),d.videoEffects&&(this._effect=null,d.videoEffects.destroy()),this._stream&&(Kr(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return o(this,null,function*(){return e?this._changeScreen():d.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return o(this,null,function*(){if(!this._stream)return;d.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield C.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=C.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return o(this,null,function*(){if(!this._stream)return;let t;e?t=(yield C.getUserAudio()).getAudioTracks()[0]:t=C.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return o(this,null,function*(){if(!d.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return o(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks()[0];if(!e)throw new Error("Local audio track not found");if(!!e.enabled)return e.applyConstraints({noiseSuppression:d.noiseSuppression})})}videoEffect(e){return o(this,null,function*(){if(!d.videoEffects)throw new Error("Video Effects library is not set");if(!d.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var ht=":",Kt="d",bi;(q=>{function a(f,T,P,N,A=!1,y=!1){let H=/[\r\n]+/,b=`\r
|
|
8
|
+
`;if(!T&&!P&&!N&&!y)return A?D(f.split(H)).join(b):f;function D(oe){let Be=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],me="a=rtcp-fb:111",re=oe.findIndex(Z=>Z.startsWith(me));return~re&&(oe[re]=oe[re]+b+Be.join(b)),oe}function Ce(oe,Be,me){let re=oe.split(" "),Z=re.slice(0,3),h;for(h=3;h<re.length;h++)me.includes(re[h])&&Z.push(re[h]);for(h=3;h<re.length;h++)!me.includes(re[h])&&!Be.includes(re[h])&&Z.push(re[h]);return Z.join(" ")}function se(oe,Be){let me=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),re,Z=[];for(re=0;re<oe.length;++re){let h=oe[re].match(me);h&&h.length===3&&h[2]===Be&&Z.push(h[1])}return Z}function ye(oe,Be,me,re){let Z,h="m="+Be;for(Z=0;Z<oe.length;++Z)if(oe[Z].startsWith(h)){oe[Z]=Ce(oe[Z],me,re);break}}let Ue=[],te=f.split(H);(P||T)&&(Ue=se(te,"H264"));let ke=[];N&&(ke=se(te,"VP9"));let Oe=[];if(y&&(Oe=se(te,"red")),P){let oe=Ue.slice(0),Be=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),me;for(me=0;me<te.length;++me){let Z=te[me].match(Be);Z&&Z.length===3&&oe.includes(Z[2])&&oe.push(Z[1])}let re=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(me=te.length;me--;){let Z=te[me].match(re);Z&&Z.length===3&&oe.includes(Z[2])&&te.splice(me,1)}ye(te,"video",oe,[])}else T&&ye(te,"video",[],Ue);return N&&ye(te,"video",[],ke),y&&Oe.length>0&&ye(te,"audio",[],Oe),A&&D(te),te.join(b)}q.patchSDP=a;function e(f){return f?`${f.type||"WEB_SOCKET"}_${f.id}`:"_"}q.getPeerIdString=e;function t(f,T){return f&&f.id===T.id&&(f.type||"WEB_SOCKET")===(T.type||"WEB_SOCKET")}q.comparePeerId=t;function i(f){return o(this,null,function*(){return!f||!f.getStats?Promise.resolve(null):f.getStats(null).then(T=>{let P=null,N=null;if(T.forEach(A=>{A.type==="transport"&&A.selectedCandidatePairId?N=T.get(A.selectedCandidatePairId):A.type==="candidate-pair"&&A.state==="succeeded"&&!N&&(!A.hasOwnProperty("selected")||A.selected)&&(N=A)}),N&&N.localCandidateId){let A=T.get(N.localCandidateId);A&&(P={type:A.candidateType,ip:A.ip||A.ipAddress,port:A.port||A.portNumber})}return P}).catch(()=>null)})}q.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function s(f,T){let P=String(f);return n.test(P)?(c.warn(`Already composite id [${f}] type supplied [${T}]`),P):T===z.GROUP?"g"+P:T===z.USER?"u"+P:(c.warn(`Unknown type [${T}] for id [${f}]`),P.match(r)?"u"+P:P)}q.composeUserId=s;function p(f,T,P){let N=s(f,T);return l(N,P)}q.composeParticipantId=p;function l(f,T){return T?f+ht+Kt+T:f}q.compose=l;function m(f){return p(f.id,f.idType||z.USER,f.deviceIdx||0)}q.composeId=m;function I(f){return f.participant?m(f.participant):p(f.participantId,f.participantType||z.USER,f.deviceIdx||0)}q.composeMessageId=I;function R(f){let T=String(f),P=T.match(n);return P?{id:Number(P[2]),type:P[1]==="g"?z.GROUP:z.USER}:(c.warn(`Unsupported compositeId [${f}]`),{id:Number(T),type:z.USER})}q.decomposeId=R;function O(f){let T=f.split(ht+Kt);return{compositeUserId:T[0],deviceIdx:T.length>1?parseInt(T[1],10):0}}q.decomposeParticipantId=O;function L(){var H,b;let f=(b=(H=window.crypto)==null?void 0:H.randomUUID)==null?void 0:b.call(H);if(f)return f;let T="0123456789abcdefghijklmnopqrstuvwxyz".split(""),P=new Array(36),N=0,A,y;for(y=0;y<36;y++)y===8||y===13||y===18||y===23?P[y]="-":y===14?P[y]="4":(N<=2&&(N=33554432+Math.random()*16777216|0),A=N&15,N=N>>4,P[y]=T[y===19?A&3|8:A]);return P.join("")}q.uuid=L;function $(f,T){let P;function N(){let A=this,y=arguments;P&&window.clearTimeout(P),P=window.setTimeout(()=>{f.apply(A,y)},T)}return N}q.throttle=$;function _e(f){if(!window.BigInt)return null;let T="",P=f.split(`
|
|
9
|
+
`);for(let y of P)if(y.startsWith("a=fingerprint")){let H=y.split(" ");if(H.length===2){T=H[1];break}}if(!T)return BigInt(-1);let N=T.split(":"),A=BigInt(0);for(let y=Math.min(7,N.length-1);y>=0;y--){let H=BigInt(parseInt(N[y],16));A<<=BigInt(8),A|=H}return BigInt.asIntN(64,A)}q.sdpFingerprint=_e;function Ne(f){return o(this,null,function*(){return new Promise(T=>window.setTimeout(T,f))})}q.delay=Ne;function ue(f,T,P){let N=[];return f.getSenders().forEach(A=>Ye(T,A,A.track,P,N)),N}q.applySettings=ue;function Ye(f,T,P,N,A){var y;if(f&&P&&P.kind===ae.video){let H=P.getSettings();if(H){let b=f.maxBitrateK?f.maxBitrateK*1024:null,D=H.width,Ce=H.height,se=D&&Ce&&f.maxDimension?Math.max(1,Math.max(D,Ce)/f.maxDimension):null,ye=f.maxFramerate?f.maxFramerate:null,Ue=f.degradationPreference?f.degradationPreference:"balanced",te=N[P.id];if(te&&te.bitrate===b&&te.scaleResolutionDownBy===se&&te.maxFramerate===ye&&te.degradationPreference===Ue){A[P.id]=te;return}A[P.id]={bitrate:b,scaleResolutionDownBy:se,maxFramerate:ye,degradationPreference:Ue};let ke=T.getParameters();ke.encodings||(ke.encodings=[{}]),ke.encodings.forEach(Oe=>{b?Oe.maxBitrate=b:delete Oe.maxBitrate,se?Oe.scaleResolutionDownBy=se:delete Oe.scaleResolutionDownBy,ye?Oe.maxFramerate=ye:delete Oe.maxFramerate}),ke.degradationPreference=Ue,(y=T.setParameters)==null||y.call(T,ke)}}}q.applyVideoTrackSettings=Ye;function le(f,T){Array.isArray(T)||(T=[T]);for(let P of T)if(f.includes(P))return!0;return!1}q.includesOneOf=le;function De(f){var T;return Object.entries(((T=f.participantState)==null?void 0:T.state)||{}).reduce((P,[N,A])=>(f.participantState&&(P[N]={ts:f.participantState.stateUpdateTs[N],state:A}),P),{})}q.mapParticipantState=De;function Ae(f){let T=f.map(P=>({uid:P.externalId,mediaSettings:P.mediaSettings,status:P.status,muteStates:P.muteStates,unmuteOptions:P.unmuteOptions,participantState:P.participantState,markers:P.markers}));return d.filterObservers?T.filter(P=>!P.uid.observer):T}q.mapSharedParticipants=Ae;function Y(f,T){let P=Object.keys(f),N=Object.keys(T);if(P.length!==N.length)return!1;for(let A of P)if(!N.hasOwnProperty(A)||f[A].state!==T[A].state||f[A].ts!==T[A].ts)return!1;return!0}q.isEqualParticipantState=Y;function rr(f,T){let P=Object.keys(f),N=Object.keys(T);if(P.length!==N.length)return!1;for(let A of P)if(!T.hasOwnProperty(A)||f[A]!==T[A])return!1;return!0}q.isObjectsEquals=rr;function ar(f,T){if(f.length!==T.length)return!1;for(let P of f)if(T.indexOf(P)<0)return!1;return!0}q.isArraysEquals=ar;function nr(f){return!Object.keys(f).length}q.isEmptyObject=nr;function sr(f,T){if(!f&&!T)return 0;if(!f||!T)return f?-1:1;return N(T.rank,f.rank)||N(f.ts,T.ts)||P(f,T);function P(A,y){let H={[z.USER]:0,[z.GROUP]:1},{compositeUserId:b,deviceIdx:D}=O(A.id),{compositeUserId:Ce,deviceIdx:se}=O(y.id),{id:ye,type:Ue}=R(b),{id:te,type:ke}=R(Ce);return N(H[Ue],H[ke])||N(ye,te)||N(D,se)}function N(A,y){return A<y?-1:A===y?0:1}}q.participantMarkerCompare=sr;function or(f,T){let P=Object.entries(f).filter(([,N])=>Array.isArray(T)?!T.includes(N):N!==T);return Object.fromEntries(P)}q.objectFilterOutValues=or})(bi||(bi={}));var S=bi;var Ze=null,Mi=null,qt=[],$t=[],Di=[],Rt=null,bt=null,Ai=null,ki=!1,Oi=!1,Jt,_t,Yt,$r=!1,Jr=!1,wi=null,xi="",zt=[],Li=null,Yr=navigator.appVersion,nn=navigator.appName,Re=navigator.userAgent,Ni=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(Ni||{}),Mt=class{constructor(e,t=!1,i=d.videoMaxWidth,r=d.videoMaxHeight){let n=!1;if(e){n={noiseSuppression:d.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let p;bt&&(p=bt.deviceId),typeof e=="string"&&(p=e),p&&(n.deviceId={ideal:p})}let s=!1;if(t){s={width:{min:d.videoMinWidth,max:i,ideal:i},height:{min:d.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:d.videoAspectRatio},frameRate:{ideal:d.videoFrameRate}};let p;Rt&&(p=Rt.deviceId),typeof t=="string"&&(p=t),p&&(s.deviceId={ideal:p}),d.videoFacingMode&&(s.facingMode={ideal:d.videoFacingMode})}this.audio=n,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},zr=class extends Mt{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=d.screenFrameRate}};function sn(){return o(this,null,function*(){Ze=null,yield Qt()})}function on(){Ze=null,Qt().then(()=>v.onDeviceChange())}function Qt(){return o(this,null,function*(){return Ze||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Mi&&navigator.mediaDevices.addEventListener&&(Mi=S.throttle(on,1e3),navigator.mediaDevices.addEventListener("devicechange",Mi)),Ze=navigator.mediaDevices.enumerateDevices().then(a=>{qt=a.filter(r=>r.kind==="videoinput"?(r.label&&(ki=!0),!0):!1),$t=a.filter(r=>r.kind==="audioinput"?(r.label?Oi=!0:et.isMobile()&&et.browserName()==="Firefox"&&(Oi=ki),!0):!1),Di=a.filter(r=>r.kind==="audiooutput");let e=$e.get("videoinput"),t=$e.get("audioinput"),i=$e.get("audiooutput");return Rt=qt.find(r=>r.deviceId===e)||null,bt=$t.find(r=>r.deviceId===t)||null,Ai=Di.find(r=>r.deviceId===i)||null,Ze=Promise.resolve(a),a}).catch(()=>(Ze=null,[]))))})}function cn(){return o(this,null,function*(){return et.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&($r=!0),/^a=mid:0$/m.test(t.sdp)&&(Jr=!0),a()}).catch(a)}):Promise.resolve()})}function Xt(a,e){return o(this,null,function*(){c.debug("Try to get media",a.getNative());let t=et.hasPermissions(a.isVideo());!t&&!e&&v.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield sn()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?ie.CAMERA_PERMISSION:ie.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?ie.CAMERA_ACCESS:ie.MIC_ACCESS;break}if(a.canSimplify())return Xt(a.simplify(),e);let r=e||ie.UNKNOWN;throw v.onPermissionsError(r),r}})}function dn(a){return o(this,null,function*(){c.debug("Try to get screen",a.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(a.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(c.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw ie.SCREEN_PERMISSION;default:throw ie.SCREEN_ACCESS}}})}function Zt(){return zt.length||(zt=(()=>{let a,e=!1,t=0,i="0",r=Re.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return a=/\brv[ :]+(\d+)/g.exec(Re),["IE",a&&a[1]||"Unknown",e,t,i];if(r[1]==="Safari"){if(a=Re.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(a=Re.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,Number(a[1]),i];if(a=Re.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t,i];if(a=Re.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t,i];if(a=Re.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t,i]}if(r[1]==="Chrome"){if(e=!0,t=Number(r[2]),a=Re.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t,i];if(a=Re.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t,i];if(a=Re.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t,i];if(a=Re.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t,i]}return a=Re.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),a&&a[2]!==void 0&&(i=a[2]),[r[2]?r[1]:nn,a&&a[1]||r[2]||Yr,e,t,i]})()),zt}var et;(A=>{function a(){return o(this,null,function*(){return yield cn(),Qt()})}A.init=a;function e(){return qt}A.getCameras=e;function t(){return $t}A.getMicrophones=t;function i(){return Di}A.getOutput=i;function r(){return qt.length>0}A.hasCamera=r;function n(){return $t.length>0}A.hasMicrophone=n;function s(){return Rt}A.getSavedCamera=s;function p(){return bt}A.getSavedMicrophone=p;function l(){return Ai}A.getSavedOutput=l;function m(){return ki}A.hasCameraPermission=m;function I(){return Oi}A.hasMicrophonePermission=I;function R(y=!1){return I()?r()&&y?m():!0:!1}A.hasPermissions=R;function O(y=!1,H=!0,b=!0){return o(this,null,function*(){let D=n()&&H,Ce=r()&&y,se;if(!D&&!Ce)se=new MediaStream;else try{se=yield Xt(new Mt(D,Ce))}catch(ye){se=new MediaStream}return!se.getVideoTracks().length&&b&&se.addTrack(Ye()),!se.getAudioTracks().length&&b&&se.addTrack(ue()),se})}A.getUserMedia=O;function L(){return o(this,null,function*(){return dn(new zr(window.screen.width,window.screen.height))})}A.getScreenMedia=L;function $(y,H=!1){return o(this,null,function*(){let b=H?d.videoEffectMaxWidth:d.videoMaxWidth,D=H?d.videoEffectMaxHeight:d.videoMaxHeight;return Xt(new Mt(!1,y||!0,b,D))})}A.getUserVideo=$;function _e(y){return o(this,null,function*(){return Xt(new Mt(y||!0,!1))})}A.getUserAudio=_e;function Ne(y,H){return o(this,null,function*(){let D=(yield Qt()).find(Ce=>Ce.kind===y&&Ce.deviceId===H);return D?(y==="videoinput"?Rt=D:y==="audioinput"?bt=D:y==="audiooutput"&&(Ai=D),$e.set(y,H),D):null})}A.saveDeviceId=Ne;function ue(){if(!Yt||Yt.readyState==="ended"){let y=P(),H=y.createMediaStreamDestination(),b=y.createGain();b.gain.value=1e-5,b.connect(H),b.connect(y.destination);let D=y.createOscillator();D.type="sine",D.frequency.value=0,D.connect(b),D.start(),Yt=H.stream.getAudioTracks()[0]}return Object.assign(Yt.clone(),{enabled:!1})}A.getSilentMediaTrack=ue;function Ye(y=d.videoMinWidth,H=d.videoMinHeight){return _t||(_t=document.createElement("canvas"),_t.getContext("2d")),_t.width=y,_t.height=H,(!Jt||Jt.readyState==="ended")&&(Jt=_t.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(Jt.clone(),{enabled:!1})}A.getBlackMediaTrack=Ye;function le(){if(q()==="Edge"&&Number(f())<70)return!1;try{let y=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&y.RTCPeerConnection&&y.RTCIceCandidate&&y.RTCSessionDescription&&y.HTMLCanvasElement&&y.HTMLCanvasElement.prototype.captureStream&&y.RTCRtpSender&&y.RTCRtpSender.prototype.replaceTrack&&y.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(y){return!1}}A.isBrowserSupported=le;function De(){return!!navigator.mediaDevices.getDisplayMedia}A.isScreenCapturingSupported=De;function Ae(){return $r}A.canVP8=Ae;function Y(){return Jr}A.isUnifiedPlan=Y;function rr(){let y=A.browserName()==="Safari"&&A.browserVersion()==="15"&&A.browserSubVersion()==="1",H=A.browserName()==="Opera"&&A.os()==="Windows";return y||H}A.isBrokenH264=rr;function ar(){return!(A.baseChromeVersion()&&A.isMobile())}A.canPreferH264=ar;function nr(){var y;return((y=window.RTCRtpTransceiver)==null?void 0:y.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}A.canPreferRed=nr;function sr(){return xi||(xi=(()=>{let y={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 H in y)if(y.hasOwnProperty(H)&&y[H].test(Re))return H;return"Unknown"})()),xi}A.os=sr;function or(){return wi===null&&(wi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Yr)),wi}A.isMobile=or;function q(){return Zt()[0]}A.browserName=q;function f(){return Zt()[1]}A.browserVersion=f;function T(){return Zt()[3]}A.baseChromeVersion=T;function P(){return Li||(Li=new(window.AudioContext||window.webkitAudioContext)),Li}A.getAudioContext=P;function N(){return Zt()[4]}A.browserSubVersion=N})(et||(et={}));var C=et;var qe=class extends Ge{init(e){return o(this,null,function*(){c.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var i=Object.defineProperty;var E=a=>i(a,"__esModule",{value:!0});var g=(a,e)=>{E(a);for(var t in e)i(a,t,{get:e[t],enumerable:!0})};var V={};g(V,{default:()=>D});var n=(t=>(t.VP9="vp09.00.50.08",t.VP8="vp8",t))(n||{}),o=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(o||{});var D=a=>{let e=null,t=!0;function p(){self.postMessage({type:o.READY})}function f(d,r,s,l=!1){if(!e||t!==s){if(!l){self.postMessage({type:o.DEBUG,message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}t=s,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${s?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${s?"VP9":"VP8"}`}),e=new VideoDecoder({output:c=>{let m=a?[c]:[];self.postMessage({type:o.FRAME,data:c},m),c.close()},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:s?n.VP9:n.VP8})}let u=new EncodedVideoChunk({type:l?"key":"delta",timestamp:d,data:r});e.decode(u)}self.onmessage=d=>{switch(d.data.type){case o.INIT:p();break;case o.FRAME:f(d.data.timestamp,d.data.data,d.data.isVP9,d.data.keyFrame);break}}};return V;})();\n',t=>{t.error?c.warn("WebCodecsDecoder",t.error):e(t.data)},[C.baseChromeVersion()>=92])})}decodeFrame(e,t,i,r=!1){this._sendToWorker(ve.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),c.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window}};var Qr=ze(require("bit-buffer"));var pn=65536,tt=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(c.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%pn!==e.sequence){c.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:n}=tt.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:n})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((n,s)=>n+s.data.byteLength,0),i=new Uint8Array(t),r=0;for(let n of e)i.set(new Uint8Array(n.data),r),r+=n.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new Qr.BitStream(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),s=i.readBits(1)<<1|r;return s===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,s>=2&&i.index++,i.readBits(3)!==7?(i.index++,(s===1||s===3)&&(i.index+=3)):(s===1||s===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var gt=class{constructor(e){this._onStream=e}drawFrame(e){return o(this,null,function*(){throw new Error("Method `drawFrame` is not supported by this implementation")})}drawImage(e){throw new Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Dt=class extends gt{constructor(e){super(e);this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;c.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 o(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(),c.debug("CanvasRenderer destroyed")}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(C.browserName()==="Safari"&&Number(C.browserVersion())===15)}};var ft=class extends gt{constructor(e){super(e);c.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:ae.video}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}drawFrame(e){return o(this,null,function*(){yield this._writer.write(e)})}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),c.debug("TrackGeneratorRenderer destroyed")}static isBrowserSupported(){return"VideoFrame"in window&&"MediaStreamTrackGenerator"in window&&qe.isBrowserSupported()}};var At=class extends tt{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];c.debug(`StreamBuilder started for participant [${e}]`),ft.isBrowserSupported()?this._renderer=new ft(t):this._renderer=new Dt(t),qe.isBrowserSupported()?this._decoder=new qe:this._decoder=new ut;let i=r=>o(this,null,function*(){"VideoFrame"in window&&r instanceof VideoFrame?yield this._renderer.drawFrame(r):this._renderer.drawImage(r)});this._decoder.init(i).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._renderer.destroy(),c.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return Dt.isBrowserSupported()||ft.isBrowserSupported()}};var ei=1,ln=1,Xr=0,ti=11,Zr=1,ea=2,ta=4,ia=8;function ra(a,e,t,i,r,n,s){let p=0;e&&(p|=Zr),t&&(p|=ea),i&&(p|=ta),s||(p|=ia);let l=new ArrayBuffer(ti),m=new DataView(l);if(m.setUint8(0,ei),m.setUint16(1,r),m.setUint32(3,a),m.setUint8(7,n?1:0),m.setUint16(8,Xr),m.setUint8(10,p),!s)return l;let I=new Uint8Array(l.byteLength+s.byteLength);return I.set(new Uint8Array(l),0),I.set(new Uint8Array(s),l.byteLength),I.buffer}function aa(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,s=e.getUint16(8),p=e.getUint8(10),l=!!(p&Zr),m=!!(p&ea),I=!!(p&ta),R=!!(p&ia);if(t!==ei)throw new Error(`Unexpected protocol version. Got ${t}, expected ${ei}`);return{timestamp:r,start:l,end:m,keyframe:I,sequence:i,isVP9:n,ssrc:s,eos:R,data:a.slice(ti)}}function na(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==ei||e.getUint8(1)!==ln||e.getUint16(2)!==Xr)}var E=ze(require("simple-ebml-builder"));var un=lr(2,15)-1,Ui=1,mn=5,hn=5;var ii=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),c.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=ii._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return E.build(e[0])}else return new Uint8Array;let t=e.reduce((n,s)=>n+s.countSize(),0),i=new Uint8Array(t),r=0;for(let n of e){let s=E.build(n);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var n,s,p;((n=this._mediaSource)==null?void 0:n.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let e=(p=this._sourceBuffer)==null?void 0:p.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-mn);r-i>hn&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},xe=class extends tt{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;c.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return E.element(E.ID.EBML,[E.element(E.ID.EBMLVersion,E.number(1)),E.element(E.ID.EBMLReadVersion,E.number(1)),E.element(E.ID.EBMLMaxIDLength,E.number(4)),E.element(E.ID.EBMLMaxSizeLength,E.number(8)),E.element(E.ID.DocType,E.string("webm")),E.element(E.ID.DocTypeVersion,E.number(2)),E.element(E.ID.DocTypeReadVersion,E.number(2))])}static _genSegmentHeader(e,t,i){let r=E.element(E.ID.Info,[E.element(E.ID.TimecodeScale,E.number(1e6)),E.element(E.ID.MuxingApp,E.string("vk-webm-builder")),E.element(E.ID.WritingApp,E.string("vk-webm-builder"))]),n=[E.element(E.ID.PixelWidth,E.number(e)),E.element(E.ID.PixelHeight,E.number(t))],s=E.element(E.ID.Tracks,E.element(E.ID.TrackEntry,[E.element(E.ID.TrackNumber,E.number(Ui)),E.element(E.ID.TrackUID,E.number(Ui)),E.element(E.ID.TrackType,E.number(1)),E.element(E.ID.FlagLacing,E.number(0)),E.element(E.ID.DefaultDuration,E.number(1e9)),E.element(E.ID.CodecID,E.string(`V_${i.toUpperCase()}`)),E.element(E.ID.Video,n)]));return E.unknownSizeElement(E.ID.Segment,[r,s])}static _genClusterHeader(e){return E.unknownSizeElement(E.ID.Cluster,[E.element(E.ID.Timecode,E.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new ii(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){c.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>c.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"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,c.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),c.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=xe._genWebmHeader();this._mediaBuffer.append(s);let p=xe._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(p)}let r=Math.round(i-this._clusterStartTime);if(r>un&&(this._clusterStartTime=i,r=0),r===0){c.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=xe._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let n=E.element(E.ID.SimpleBlock,[E.vintEncodedNumber(Ui),E.bytes(xe._intToU16BE(r)),E.number((e.keyframe?1:0)<<7),E.bytes(e.frameData)]);this._mediaBuffer.append(n,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),c.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var St=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};c.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=n=>this._onDataChannelMessage(n.data)}_onDataChannelMessage(e){var n,s;let t=aa(e),i=(s=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){c.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];if(!r){let p=l=>this._onStream(i,l);d.screenShareWebmBuilder&&xe.isBrowserSupported()?r=new xe(i,p):r=new At(i,p),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,c.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(qe.isBrowserSupported()||ut.isBrowserSupported())&&(At.isBrowserSupported()||xe.isBrowserSupported())}};var Bi=ze(require("@vkontakte/libvpx"));var _n=1e3,kt=class extends Ge{constructor(e,t){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return o(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=p=>t(),r.onerror=()=>i(new Error("Video element error"));let n=r.play(),s=()=>i(new Error("Autoplay is disabled"));n?n.catch(s):s()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");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 o(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return o(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;c.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var u=Object.defineProperty;var b=o=>u(o,"__esModule",{value:!0});var g=(o,n)=>{b(o);for(var t in n)u(o,t,{get:n[t],enumerable:!0})};var y={};g(y,{default:()=>R});var e=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(e||{});var R=(o,n)=>{let t;function m(a,r){return o({locateFile:n}).then(s=>{if(t=new s.VpxEncoder,t.debug(r),!t.init(a?s.VpxType.VP9:s.VpxType.VP8))throw self.postMessage({type:e.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");t.setMaxQuantizer(10),t.setTargetBitrate(1024)})}function E(a,r,s,i){let c=t.allocateImage(a,r);if(!c){self.postMessage({type:e.FRAME,error:"No buffer data"});return}c.set(new Uint8Array(s));let f=Math.round(performance.now()),l=150;if(!t.encode(f,l,i)){self.postMessage({type:e.FRAME,error:"Encode failed"});return}let p=t.readFrame();if(!p){self.postMessage({type:e.FRAME,error:"No encoded data"});return}t.readFrame()&&(self.postMessage({type:e.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:e.LOG_ERROR,message:"LibVPxEncoder-drop"}));let d=new Uint8Array(p.byteLength);d.set(p),self.postMessage({type:e.FRAME,frameType:i?"key":"delta",timestamp:f,duration:l,data:d.buffer},[d.buffer])}self.onmessage=a=>{switch(a.data.type){case e.INIT:m(a.data.isVP9,a.data.debug).then(()=>self.postMessage({type:e.READY})).catch(r=>self.postMessage({type:e.ERROR,error:String(r)}));break;case e.FRAME:E(a.data.width,a.data.height,a.data.imageData,a.data.keyFrame);break}}};return y;})();
|
|
10
|
+
`,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength})},[Bi.default,Bi.default.getUrl],{isVP9:this.isVP9(),debug:c.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(ve.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)},_n),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),c.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var vt=class extends Ge{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return o(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;c.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var E=Object.defineProperty;var g=i=>E(i,"__esModule",{value:!0});var F=(i,l)=>{g(i);for(var r in l)E(i,r,{get:l[r],enumerable:!0})};var A={};F(A,{default:()=>h});var n=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(n||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,l,r,c,s,f,t,a=null,p=0,u=!1;function V(e){l=e.readable,r=l.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&b(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),l.cancel();return}a=R,b(R,e)}}))}function b(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
|
|
11
|
+
`,r=>{var n;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(n=r.data)==null?void 0:n.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:d.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(ve.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),c.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var gn=65536,Vi=0,Et=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;c.debug("ScreenCaptureSender started"),this.DATA_SIZE=d.consumerScreenDataChannelPacketSize-ti,this._datachannel=t;let i=(r,n)=>{if(!this._destroyed){if(!r){c.warn("requestFrame failed, keyFrame: "+this._needKeyframe,n),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{c.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};vt.isBrowserSupported()?this._encoder=new vt(e,i):this._encoder=new kt(e,i),this._datachannel.onmessage=r=>{na(r.data)&&(c.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>c.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,n){let s=ra(e,t,i,r,Vi,this._encoder.isVP9(),n);return Vi=(Vi+1)%gn,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return o(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let n=e.data.slice(t,t+this.DATA_SIZE),s=e.data.byteLength<=t+n.byteLength,p=this._wrapHeader(e.timestamp,!t,s,e.type==="key",n);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(p)}catch(l){c.warn("Error send data to DataChannel",l),r();return}s||window.setTimeout(()=>this._sendChunk(e,t+this.DATA_SIZE,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),c.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return vt.isBrowserSupported()||kt.isBrowserSupported()}};var ee=class{static get sessionKey(){return ee._sessionKey}static set sessionKey(e){ee._sessionKey=e}static get sessionSecretKey(){return ee._sessionSecretKey}static set sessionSecretKey(e){ee._sessionSecretKey=e}static get accessToken(){return ee._accessToken}static set accessToken(e){ee._accessToken=e}static isEmpty(){return!ee._sessionKey||!ee._sessionSecretKey}};var _=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(_._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(_._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(_._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(ee.accessToken=e.apiAuth.accessToken,ee.sessionKey=e.apiAuth.sessionKey,ee.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(_._params,S.objectFilterOutValues(e,void 0))}static get(e){return _._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.6.2-dev.4163bb9.0"}static get debug(){return undefined}static get protocolVersion(){return _._params.joinFromMultipleDevices?6:5}static get platform(){return _._params.platform}static set platform(e){_._params.platform=e}static get clientType(){return _._params.clientType}static set clientType(e){_._params.clientType=e}static get device(){return _._params.device}static get apiKey(){return _._params.apiKey}static get apiEnv(){return _._params.apiEnv}static get apiEndpoint(){switch(_.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 _._params.apiEnv}}static get authToken(){return _._params.authToken}static set authToken(e){_._params.authToken=e}static get anonymToken(){return _._params.anonymToken}static set anonymToken(e){_._params.anonymToken=e}static get domain(){return _._params.domain}static get iceServers(){return _._params.iceServers}static set iceServers(e){_._params.iceServers=e}static get wssBase(){return _._params.wssBase}static set wssBase(e){_._params.wssBase=e}static get wssToken(){return _._params.wssToken}static set wssToken(e){_._params.wssToken=e}static get signalingReconnectDelay(){return _._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return _._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return _._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return _._params.waitConnectionDelay}static get waitResponseDelay(){return _._params.waitResponseDelay}static get waitMessageDelay(){return _._params.waitMessageDelay}static get waitAnotherTabDelay(){return _._params.waitAnotherTabDelay}static get debugLog(){return _._params.debugLog}static get forceRelayPolicy(){return _._params.forceRelayPolicy}static set forceRelayPolicy(e){_._params.forceRelayPolicy=e}static get videoMinWidth(){return _._params.videoMinWidth}static get videoMaxWidth(){return _._params.videoMaxWidth}static set videoMaxWidth(e){_._params.videoMaxWidth=e}static get videoMinHeight(){return _._params.videoMinHeight}static get videoMaxHeight(){return _._params.videoMaxHeight}static set videoMaxHeight(e){_._params.videoMaxHeight=e}static get videoAspectRatio(){return _._params.videoAspectRatio}static get videoFrameRate(){return _._params.videoFrameRate}static get videoFacingMode(){return _._params.videoFacingMode}static get screenFrameRate(){return _._params.screenFrameRate}static get videoEffects(){return _._params.videoEffects}static set videoEffects(e){_._params.videoEffects=e}static get videoEffectMaxWidth(){return _._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){_._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return _._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){_._params.videoEffectMaxHeight=e}static get voiceParams(){return _._params.voiceParams}static get specListenerParams(){return _._params.specListenerParams}static get iceRestartWaitTime(){return _._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return _._params.transportConnectionWaitTime}static get statisticsInterval(){return _._params.statisticsInterval}static set statisticsInterval(e){_._params.statisticsInterval=e}static get networkStatisticsInterval(){return _._params.networkStatisticsInterval}static get perfStatReportEnabled(){return _._params.perfStatReportEnabled}static get callStatReportEnabled(){return _._params.callStatReportEnabled}static get producerNotificationDataChannel(){return _._params.producerNotificationDataChannel}static get producerCommandDataChannel(){return _._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return _._params.consumerScreenDataChannel&&Et.isBrowserSupported()}static get producerScreenDataChannel(){return _._params.producerScreenDataChannel&&_.producerNotificationDataChannel&&St.isBrowserSupported()}static get consumerScreenDataChannelPacketSize(){return _._params.consumerScreenDataChannelPacketSize}static get screenShareWebmBuilder(){return _._params.screenShareWebmBuilder}static get noiseSuppression(){return _._params.noiseSuppression}static set noiseSuppression(e){_._params.noiseSuppression=e}static get preferH264(){return _._params.preferH264}static get preferVP9(){return _._params.preferVP9}static get audioNack(){return _._params.audioNack}static get consumerScreenTrack(){return _._params.consumerScreenTrack&&_.consumerScreenDataChannel}static get producerScreenTrack(){return _._params.producerScreenTrack}static isUnifiedPlanSupported(e,t){let i=_._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return _._params.movieShare&&_.videoTracksCount>0}static get videoTracksCount(){return _.producerNotificationDataChannel?_._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return _._params.breakVideoPayloadTypes}static get filteredMessages(){return _._params.filteredMessages}static get useParticipantListChunk(){return _._params.useParticipantListChunk&&_._params.videoTracksCount>0}static get participantListChunkInitIndex(){var e;return(e=_._params.participantListChunkInitIndex)!=null?e:0}static get participantListChunkInitCount(){var e;return(e=_._params.participantListChunkInitCount)!=null?e:null}static get serverAudioRed(){return _._params.serverAudioRed&&C.canPreferRed()}static get p2pAudioRed(){return _._params.p2pAudioRed&&C.canPreferRed()}static get batchParticipantsOnStart(){return _._params.batchParticipantsOnStart}static get filterObservers(){return _._params.filterObservers}static get muteMode(){return _._params.muteMode}static get preserveAudioTracks(){return _._params.preserveAudioTracks}},d=_;d._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,consumerScreenDataChannelPacketSize:16*1024,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,useParticipantListChunk:!1,participantListChunkInitIndex:0,participantListChunkInitCount:null,serverAudioRed:!1,p2pAudioRed:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1};var J=(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))(J||{});function K(a,...e){let t=d.get(a);t&&setTimeout(t,0,...e)}function Ie(a,e,...t){if(d.filterObservers){if(Array.isArray(e)){if(e=e.filter(i=>!i.observer),!e.length)return}else if(e.observer)return}K(a,e,...t)}function He(a){return Object.assign({},a)}function it(a){return a.slice()}var Fi;(Z=>{function a(h,k){K("onLocalStream",h,He(k))}Z.onLocalStream=a;function e(h,k){K("onScreenStream",h,He(k))}Z.onScreenStream=e;function t(h,k){K("onLocalStreamUpdate",He(h),k)}Z.onLocalStreamUpdate=t;function i(h){K("onLocalStatus",h)}Z.onLocalStatus=i;function r(h,k){Ie("onRemoteStream",h,k)}Z.onRemoteStream=r;function n(h,k,Q){Ie("onRemoteLive",h,k,Q)}Z.onRemoteLive=n;function s(h,k){Ie("onRemoteScreenStream",h,k)}Z.onRemoteScreenStream=s;function p(h,k,Q,It){Ie("onConversation",h,He(k),He(Q),It)}Z.onConversation=p;function l(h){h&&K("onConversationParticipantListChunk",h)}Z.onConversationParticipantListChunk=l;function m(h,k,Q){Ie("onRemoteMediaSettings",h,He(k),Q)}Z.onRemoteMediaSettings=m;function I(h,k){Ie("onParticipantAdded",h,k)}Z.onParticipantAdded=I;function R(h,k){Ie("onParticipantJoined",h,k)}Z.onParticipantJoined=R;function O(h,k,Q){Ie("onRemoteParticipantState",h,He(k),Q)}Z.onRemoteParticipantState=O;function L(h,k,Q=null){Ie("onRemoteStatus",h,k,Q)}Z.onRemoteStatus=L;function $(h,k,Q=null){Ie("onParticipantStatus",h,k,Q)}Z.onParticipantStatus=$;function _e(){K("onPermissionsRequested")}Z.onPermissionsRequested=_e;function Ne(h){K("onPermissionsError",h)}Z.onPermissionsError=Ne;function ue(h,k){Ie("onRemoteRemoved",h,k)}Z.onRemoteRemoved=ue;function Ye(h,k,Q){K("onCallState",h,k,He(Q))}Z.onCallState=Ye;function le(h,k){K("onDeviceSwitched",h,k)}Z.onDeviceSwitched=le;function De(h,k,Q,It=!1,mi=!1,hi=null,Ua=null,Ba,cr){let Va=cr?it(cr):void 0;K("onMuteStates",He(h),it(k),it(Q),It,mi,hi,Ua,Ba,Va)}Z.onMuteStates=De;function Ae(h,k){Ie("onRolesChanged",h,it(k))}Z.onRolesChanged=Ae;function Y(h){K("onLocalRolesChanged",it(h))}Z.onLocalRolesChanged=Y;function rr(h,k,Q){Ie("onPinnedParticipant",h,k,Q)}Z.onPinnedParticipant=rr;function ar(h){K("onLocalPin",h)}Z.onLocalPin=ar;function nr(h){K("onOptionsChanged",it(h))}Z.onOptionsChanged=nr;function sr(){K("onCallAccepted")}Z.onCallAccepted=sr;function or(){K("onRateNeeded")}Z.onRateNeeded=or;function q(h){Ie("onSpeakerChanged",h)}Z.onSpeakerChanged=q;function f(h){K("onVolumesDetected",it(h))}Z.onVolumesDetected=f;function T(h,k){K("onLocalVolume",h,k)}Z.onLocalVolume=T;function P(h,k){K("onJoinStatus",h,k)}Z.onJoinStatus=P;function N(h,k){K("onHangup",h,k)}Z.onHangup=N;function A(h){K("onMultipartyChatCreated",He(h))}Z.onMultipartyChatCreated=A;function y(){K("onDeviceChange")}Z.onDeviceChange=y;function H(h){K("onFingerprintChange",h)}Z.onFingerprintChange=H;function b(){K("onTokenExpired")}Z.onTokenExpired=b;function D(h,k,Q=!1){K("onChatMessage",h,k,Q)}Z.onChatMessage=D;function Ce(h,k,Q=!1){K("onCustomData",h,k,Q)}Z.onCustomData=Ce;function se(h,k,Q,It,mi,hi){K("onRecordStarted",h,k,Q,It,mi,hi)}Z.onRecordStarted=se;function ye(){K("onRecordStopped")}Z.onRecordStopped=ye;function Ue(h){K("onLocalNetworkStatusChanged",h)}Z.onLocalNetworkStatusChanged=Ue;function te(h){K("onNetworkStatusChanged",h)}Z.onNetworkStatusChanged=te;function ke(h,...k){K("onDebugMessage",h,...k)}Z.onDebugMessage=ke;function Oe(h,k){let Q=Object.assign({},h,{memory:k});K("onStatistics",Q)}Z.onStatistics=Oe;function oe(){K("onAutoplayError")}Z.onAutoplayError=oe;function Be(h,k,Q){K("onChatRoomUpdated",h,k,Q)}Z.onChatRoomUpdated=Be;function me(h){K("onRemoteMixedAudioStream",h)}Z.onRemoteMixedAudioStream=me;function re(h){K("onJoinLinkChanged",h)}Z.onJoinLinkChanged=re})(Fi||(Fi={}));var v=Fi;var Gi=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(Gi||{}),Hi;(le=>{let a="📞",e=(De,...Ae)=>{v.onDebugMessage(De,...Ae)},t=!1,i=(De,Ae)=>(...Y)=>{De(...Y),Hr(Ae,Y)},r=console.debug.bind(console,a),n=console.log.bind(console,a),s=console.warn.bind(console,a),p=console.error.bind(console,a),l=e.bind(null,"DEBUG"),m=e.bind(null,"LOG"),I=e.bind(null,"WARN"),R=e.bind(null,"ERROR");le.debug=l,le.log=m,le.warn=I,le.error=R;function Ne(){return t}le.enabled=Ne;function ue(De){t=De,d.debugLog&&Ei(),De?(le.debug=d.debugLog?i(r,"DEBUG"):r,le.log=d.debugLog?i(n,"LOG"):n,le.warn=d.debugLog?i(s,"WARN"):s,le.error=d.debugLog?i(p,"ERROR"):p):(le.debug=d.debugLog?i(l,"DEBUG"):l,le.log=d.debugLog?i(m,"LOG"):m,le.warn=d.debugLog?i(I,"WARN"):I,le.error=d.debugLog?i(R,"ERROR"):R)}le.toggle=ue;function Ye(De,...Ae){switch(De){case"DEBUG":le.debug(...Ae);break;case"LOG":le.log(...Ae);break;case"WARN":le.warn(...Ae);break;case"ERROR":le.error(...Ae);break}}le.send=Ye})(Hi||(Hi={}));var c=Hi;var rt=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(rt||{}),fe;(p=>{function a(l){return l.length?typeof l[0]=="object"?l:l.map(m=>e(m)):[]}p.fromIds=a;function e(l,m="USER"){return{id:l,type:m}}p.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}p.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}p.toString=i;function r(l,m="USER"){return i(e(l,m))}p.fromIdToString=r;function n(l){try{return JSON.parse(l)}catch(m){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}p.fromString=n;function s(l,m){return l.id===m.id&&l.type===m.type}p.compare=s})(fe||(fe={}));var he;(r=>{function a(n,s="USER",p=0){return{id:n,type:s,deviceIdx:p}}r.fromId=a;function e(n){return`{"id":"${n.id}","type":"${n.type}","deviceIdx":"${n.deviceIdx}"}`}r.toString=e;function t(n,s){return Object.assign({deviceIdx:s},fe.fromSignaling(n))}r.fromSignaling=t;function i(n){return n&&typeof n=="object"?n.deviceIdx:0}r.getDeviceIdx=i})(he||(he={}));var fn="kf";function Ot(a){return a.stopStream}function Wi(a){return a.keyFrameRequested}function sa(a){if(Ot(a))return"ss";if(Wi(a))return fn;let e="";return a.priority!==void 0&&(e+="p="+a.priority),a.width!==void 0&&a.height!==void 0&&(e!==""&&(e+=":"),e+="sz="+Math.round(a.width)+"x"+Math.round(a.height)),a.fit!==void 0&&(e!==""&&(e+=":"),e+="fit="+a.fit),e}var Te=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(Te||{}),oa="s",ca="m";function We(a){return a.participantId+(a.mediaType?ht+oa+a.mediaType:"")+(a.streamName?ht+ca+a.streamName:"")}function wt(a){let e=a.split(ht),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i=null,r,n=0;for(let p of e)switch(p.charAt(0)){case oa:i=Sn(p.slice(1));break;case ca:r=p.slice(1);break;case Kt:n=Number.parseInt(p.slice(1),10);break;default:throw new Error("Unexpected parameter type "+p.charAt(0)+" in stream description "+a)}return{participantId:S.compose(t,n),mediaType:i,streamName:r}}function Sn(a){for(let e of Object.keys(Te))if(e===a)return Te[e];return null}function ji(a,e){return a===null||e===null?a===null&&e===null:!(a.maxDimension!==e.maxDimension||a.maxBitrateK!==e.maxBitrateK||a.maxFramerate!==e.maxFramerate||a.degradationPreference!==e.degradationPreference)}function ri(a,e){return!(!ji(a.camera,e.camera)||!ji(a.screenSharing,e.screenSharing))}function Ki(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function da(a){try{return btoa(JSON.stringify(a))}catch(e){c.warn("WaitingParticipant: failed convert to string",a,e)}return null}function pa(a){try{return JSON.parse(atob(a))}catch(e){c.warn("WaitingParticipant: failed convert from string",a,e)}return null}var xt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,u.log(g.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,u.log(g.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(c.log("Failed to fix RV"),u.log(g.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),u.log(g.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,c.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===ae.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var ai=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(d.muteMode||!((s=this._output)==null?void 0:s.audioTrack))return;let e=C.browserName()!=="Safari"||C.isMobile(),t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{c.warn("Error on play audio"),v.onAutoplayError()},r=p=>{t.srcObject=new MediaStream([p]),t.load();let l=t.play();l?l.catch(i):i()},n=()=>{var l;c.debug("Recover audio playback");let p=(l=this._output)==null?void 0:l.audioTrack;p?r(p):c.warn("Broken audio track")};t.onpause=n,t.onstalled=n,t.onerror=n,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return o(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=C.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw u.log(g.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var vn=90,En=3,ni=class extends X{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),v.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>vn?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=En)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var Tn=44100,Lt=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=C.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=Tn/this._fftBins.length,t=Math.ceil(d.voiceParams.minFreq/e),i=Math.floor(d.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((n,s)=>n+s,0)/e.length/255,r=this._lastSmoothedLevel*d.voiceParams.smoothing+i*(1-d.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var si=class extends X{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&v.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,d.voiceParams.interval)};this._interval=window.setTimeout(t,d.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,Pe.SOURCE_CHANGED,r=>{r.kind===ae.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new Lt("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var la="videochat-epi",In=5e3,Cn=3e4,at=class extends X{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,F.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(la)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return o(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&d.perfStatReportEnabled&&this._previousTimestamp+In<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),d.callStatReportEnabled&&this._previousCallStatReportTimestamp+Cn<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return o(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(la,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,n)=>(n.kind==="video"?(n.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+n.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+n.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=n.framesDropped,r.nack_sent+=n.nackCount,r.pli_sent+=n.pliCount,r.fir_sent+=n.firCount):(n.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+n.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+n.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=n.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=n.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=n.removedSamplesForAcceleration,r.concealed_audio_samples+=n.concealedSamples,r.silent_concealed_audio_samples+=n.silentConcealedSamples,r.audio_concealment_events+=n.concealmentEvents),r),t),e.outbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.nack_received+=n.nackCount,r.pli_received+=n.pliCount,r.fir_received+=n.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,n=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,p=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,l=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,m=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=n/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=p/r*1e3,i.concealed_silent_audio_samples=l/r*1e3,i.concealment_audio_avg_size=p/m,i.total_audio_energy=t.total_audio_energy}u.logCustom("callStat",i),c.log("Sent call stats",i),this._previousCallStatReport=t}};var yn=1e3;function de(a,e,t=0){return e in a&&a[e]?a[e]:t}function ua(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function Je(a,e){return t=>t[a]===e}function Pn(a){return(e,t)=>e[a]-t[a]}function oi(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function Rn(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function bn(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function qi(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=bn(t[1])?qi(t[1]):t[1],e),{})}function Mn(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function Dn(a){return o(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...a.getReceivers().map(t=>t.getStats())),e.push(...a.getSenders().map(t=>t.getStats()))):e.push(a.getStats()),Promise.all(e).then(Mn).then(Rn)})}function An(a){let e=a.filter(Je("type","candidate-pair")).sort(Pn("priority")).find(ua(Je("nominated",!0),Je("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=a.find(Je("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=a.find(Je("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),qi(t)}function kn(a,e){let t=oi("id",a),i=a.filter(ua(Je("type","inbound-rtp"),Je("type","outbound-rtp")));C.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,s)=>{if(!n[s.ssrc])n[s.ssrc]=s;else{let p=Object.assign({},n[s.ssrc],s),l=n[s.ssrc].isRemote?s:n[s.ssrc];p.id=l.id,p.type=l.type,delete p.isRemote,delete p.remoteId,n[p.ssrc]=p}return n},{})));let r={};if(C.browserName()==="Safari"){let n=a.filter(Je("type","track"));r=oi("trackIdentifier",n)}return i.map(n=>{let s=Number(n.ssrc),p=n.mediaType||n.kind,l=n.trackId,m=n.type,I=n.codecId;if(C.browserName()==="Safari"){let O=/^.+_([\d]+)$/.exec(n.id);if(O&&(s=parseInt(O[1],10)),p=n.id.indexOf("Audio")>0?"audio":"video",e[s]){let L=p+"-"+e[s];r[L]&&(l=r[L].id)}}if(!m||!s||!p)return null;let R={ssrc:s,type:m,kind:p,bytesReceived:de(n,"bytesReceived"),bytesSent:de(n,"bytesSent"),jitter:de(n,"jitter"),packetsLost:de(n,"packetsLost"),packetsReceived:de(n,"packetsReceived"),packetsSent:de(n,"packetsSent"),fractionLost:de(n,"fractionLost"),pliCount:de(n,"pliCount"),firCount:de(n,"firCount"),nackCount:de(n,"nackCount"),userId:e[s]};if(p==="video"){let O=de(n,"framesDecoded"),L=de(n,"totalInterFrameDelay"),$=de(n,"totalSquaredInterFrameDelay");R.interframeDelayVariance=($-L*L/O)/O}if(p==="audio"&&(R.totalSamplesReceived=de(n,"totalSamplesReceived"),R.concealedSamples=de(n,"concealedSamples"),R.insertedSamplesForDeceleration=de(n,"insertedSamplesForDeceleration"),R.removedSamplesForAcceleration=de(n,"removedSamplesForAcceleration"),R.silentConcealedSamples=de(n,"silentConcealedSamples"),R.concealmentEvents=de(n,"concealmentEvents"),R.totalAudioEnergy=de(n,"totalAudioEnergy")),I&&t[I]){let O=t[I];R.clockRate=O.clockRate,R.mimeType=O.mimeType}if(l&&t[l]){let O=t[l];R.frameHeight=O.frameHeight,R.frameWidth=O.frameWidth,R.framesDecoded=O.framesDecoded,R.framesReceived=O.framesReceived,R.framesDropped=O.framesDropped}return qi(R)}).filter(n=>!!n)}function On(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=oi("ssrc",a.rtps),i=oi("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let s=t[n],p=i[n];if(!(!s||!p)){if(s.bytesReceived&&s.bytesReceived>p.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-p.bytesReceived)/r)),s.bytesSent&&s.bytesSent>p.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-p.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>p.packetsReceived||s.packetsLost>p.packetsLost){let l=s.packetsLost-p.packetsLost,m=s.packetsReceived-p.packetsReceived;s.packetLoss=parseFloat((100*l/(l+m)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&p.framesDropped&&s.framesDropped>p.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-p.framesDropped)/r).toFixed(0)))}}),a}function Nt(i,r){return o(this,arguments,function*(a,e,t={}){let n=yield Dn(a),s={timestamp:Date.now(),transport:An(n),rtps:kn(n,t)};return e?On(s,e):(yield S.delay(yn),Nt(a,s,t))})}var ci=.8,nt=class extends X{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=V.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=n,this._perfStatReporter=new at(this,i,!0),this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Pe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Pe.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:d.iceServers,iceTransportPolicy:d.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,d.p2pAudioRed),this._applySettings()}catch(s){u.log(g.ERROR,"addTrack-direct"),c.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===V.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==V.IDLE&&e!==V.CLOSED&&e!==V.FAILED&&this._startStatInterval()}open(e=null){return o(this,null,function*(){if(this._isOpen){c.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(c.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,d.p2pAudioRed),this._applySettings()}catch(i){u.log(g.ERROR,"addTrack-direct"),c.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(V.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){ri(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(F.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(c.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(V.FAILED)):(c.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(V.CLOSED)),this._triggerEvent(F.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(F.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case w.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case w.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case w.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((n=e.data.sdk)==null?void 0:n.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=S.getPeerIdString(e.peerId);S.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){c.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw u.log(g.ERROR,"addIceCandidate-direct"),c.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else c.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return o(this,null,function*(){if(!this._remoteCandidates[e]){c.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){c.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw u.log(g.ERROR,"setRemoteDescription-direct"),c.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){c.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(F.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(F.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return o(this,null,function*(){e.candidate&&this._signaling.ready&&(c.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(c.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>o(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(c.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===V.IDLE||e===V.OPENED?this._setState(V.CONNECTING):this._setState(V.RECONNECTING);break}}_onConnectionStateChange(){switch(c.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),u.log(g.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(V.CONNECTED),this._stopReconnection(),S.getPeerConnectionHostInfo(this._pc).then(e=>{e&&u.log(g.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(V.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(c.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},d.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(c.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(pe.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(u.log(g.ICE_RESTART),c.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):c.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,c.error("Ice restart failed",{participantId:this._participantId}),u.log(g.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return o(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return c.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw c.error("Unable to create offer",i,{participantId:this._participantId}),u.log(g.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=nt._patchDescription(i),c.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw c.error("Unable to set local description",i,{participantId:this._participantId}),u.log(g.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return o(this,null,function*(){return c.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw c.error("Unable to create answer",e,{participantId:this._participantId}),u.log(g.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=nt._patchDescription(e),c.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw c.error("Unable to set local description",e,{participantId:this._participantId}),u.log(g.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!C.baseChromeVersion();return e.sdp=S.patchSDP(e.sdp,d.preferH264&&C.canPreferH264(),C.isBrokenH264(),d.preferVP9,t&&d.audioNack,d.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{c.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),u.log(g.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Nt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:pe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:pe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(F.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,d.statisticsInterval)})};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=ue=>ue.rtt<=this._networkLimits.goodNet.rtt&&ue.loss<=this._networkLimits.goodNet.loss,i=ue=>ue.rtt>=this._networkLimits.badNet.rtt||ue.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((ue,Ye)=>Math.max(ue,Ye.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-ci)+r*ci,loss:this._lastNetworkStat.loss*(1-ci)+n*ci},p=i(s),l=t(s),m=i(this._remoteNetworkStat),I=t(this._remoteNetworkStat),R=i(this._lastNetworkStat),O=t(this._lastNetworkStat),_e=p||m?.2:l&&I?1:0,Ne=Date.now();if((R!==p||O!==l||Ne-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(ue=>{c.warn("Unable to send [bad-net]",ue)})),_e){let ue={};ue[this._participantId]=ue[""]=_e,this._triggerEvent(F.NETWORK_STATUS,ue)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=S.sdpFingerprint(e);if(t===null){c.warn("Fingerprint calculation is unsupported");return}this._fingerprint===null?this._fingerprint=t:(v.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=S.applySettings(this._pc,e,this._prevConsumerSettings))}};var ma=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(ma||{}),Ut=ma;var st=ze(require("messagepack"));var $i=class{constructor(){this.streamDescriptionByCompactId=new Map;this.compactIdByStreamDescription=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}getCompactId(e){return this.compactIdByStreamDescription.get(e)}handleMessage(e){var n,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let p=(0,st.decode)(r);return Object.entries(p).forEach(([$,_e])=>{let Ne=wt($);this.streamDescriptionByCompactId.set(_e,Ne),this.compactIdByStreamDescription.set($,_e)}),null;case 2:case 4:let l=(0,st.decode)(r),m=[];for(let $ of l){let _e=this.getStreamDescription($);_e&&m.push(_e.participantId)}return i===2?{type:"notification",notification:w.AUDIO_ACTIVITY,activeParticipants:m}:{type:"notification",notification:w.STALLED_ACTIVITY,stalledParticipants:m};case 3:let I=(0,st.decode)(r);return{type:"notification",notification:w.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(I))==null?void 0:n.participantId};case 5:let R=(0,st.decode)(r);return{type:"notification",notification:w.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:R[0],maxDimension:R[1]}};case 6:let O=(0,st.decode)(r),L={};for(let[$,_e]of Object.entries(O)){let Ne=(s=this.getStreamDescription(Number($)))==null?void 0:s.participantId;Ne&&(L[Ne]=_e/100)}return{type:"notification",notification:w.NETWORK_STATUS,statuses:L};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,st.decode)(e),i=[];for(let[r,n]of Object.entries(t)){let s=n[0],p=n[1],l=n[2],m;if(s!==null){if(m=this.getStreamDescription(s),!m){c.error(`could not uncompress participant ID ${s}`);continue}}else m=null;if(l===null){c.error("unexpected null sequenceNumber",r,n);continue}let I=we.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,R=p?p>>>0:null;i.push({participantStreamDescription:m,streamId:I,rtpTimestamp:R,sequenceNumber:l})}return{type:"notification",notification:w.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var wn=90,xn=4294967295,be=class extends X{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=V.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Pe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Pe.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,Pe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new at(this,e),this._serverSettings=i,c.debug("ServerTransport: Created")}getState(){return this._state||V.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==V.IDLE&&e!==V.CLOSED&&e!==V.FAILED&&this._startStatInterval()}open(e=!1){if(this._isOpen){c.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(c.error("ServerTransport: Closed",e),this._setState(V.FAILED)):(c.debug("ServerTransport: Closed"),this._setState(V.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){ri(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,be._closeDataChannel(this._producerNotification),be._closeDataChannel(this._producerCommand),be._closeDataChannel(this._producerScreen),be._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(F.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let n=r.readyState;n==="open"?(c.debug(`[${t}] data channel opened`),r.onerror=s=>{c.error(`[${t}] data channel error`,s)},i(r)):c.error(`[${t}] data channel open failed, state [${n}]`)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection");let t={};C.baseChromeVersion()&&(t.sdpSemantics=be._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=S.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=be._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,Ut.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new $i,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&(this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,Ut.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)})),d.producerScreenDataChannel&&this._createDataChannel(this._pc,Ut.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,d.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){c.error("ServerTransport: Unable to add media source tracks",i),u.log(g.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,Ut.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(V.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==V.OPENED&&(this._setState(V.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(F.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(F.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(F.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(F.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
|
|
12
|
+
`).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${we.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!d.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new Et(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!d.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new St(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(F.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(F.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!d.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==ae.video)return;let r=!this._disabledSenders.has(i),n=e.maxDimension!==0;if(r&&!n){c.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(C.getBlackMediaTrack()).catch(p=>{c.error("Could not disable video upload",p)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&n&&s){c.log("Enabling video upload"),this._disabledSenders.delete(i);let p=i.track;p.enabled=s.enabled,i.replaceTrack(s).then(()=>p.stop()).catch(l=>{c.error("Could not enable video upload",l)})}S.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(F.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,d.statisticsInterval)};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return o(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Nt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(F.REMOTE_DATA_STATS,{inbound:{topology:pe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:pe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=we.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(F.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:at.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:d.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:d.producerCommandDataChannel?3:0,consumerScreenDataChannelVersion:d.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:d.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:be._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount,red:d.serverAudioRed};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return o(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,c.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(c.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw c.error("[single] unable to set remote offer",i),u.log(g.ERROR,"setRemoteDescription-single"),i}).then(()=>o(this,null,function*(){if(c.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw c.error("[single] unable to create answer",i),u.log(g.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=S.patchSDP(i.sdp,!1,C.isBrokenH264(),!1),i)).then(i=>o(this,null,function*(){if(c.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw c.error("[single] unable to set local answer",i),u.log(g.ERROR,"setLocalDescription-single"),i}).then(i=>o(this,null,function*(){c.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),c.debug("[single] remote offer has been processed")})).catch(i=>{c.warn("[single] unable to send local answer",i),u.log(g.ERROR,"acceptProducer")}).then(()=>o(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){c.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return o(this,null,function*(){if(!!this._isOpen)switch(e.notification){case w.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case w.REALLOC_CON:this._reconnect();break;case w.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case w.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case w.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case w.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return o(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),d.breakVideoPayloadTypes&&(c.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes",null)),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){c.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent(F.REMOTE_TRACK_REMOVED,i.id,i,n.track)}),i.getTracks().find(n=>n.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(F.REMOTE_TRACK_ADDED,i.id,i,t.track)):c.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){c.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(c.debug("[single] connection state changed",{state:e.connectionState},t),u.log(g.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===V.IDLE||i===V.OPENED?this._setState(V.CONNECTING):e.iceConnectionState==="checking"&&this._setState(V.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(V.RECONNECTING);break;case"connected":this._setState(V.CONNECTED),S.getPeerConnectionHostInfo(e).then(r=>{r&&u.log(g.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(d.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{c.error("ServerTransport: Unable to replace track",r),u.log(g.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=C.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(C.browserName(),Number(C.browserVersion()))}getStreamWaitingTimeMs(e,t){if(!this._pc)return u.log(g.PAT_WAITING_TIME_ERROR,"noConnection"),c.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return u.log(g.PAT_WAITING_TIME_ERROR,"noReceiver"),c.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return c.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return u.log(g.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),c.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let p=t-s&xn,l=Math.ceil(p/wn);return Math.min(100,Math.max(0,l))}};var F=(L=>(L.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",L.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",L.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",L.REMOTE_ALL_STALL="REMOTE_ALL_STALL",L.REMOTE_DATA_STATS="REMOTE_DATA_STATS",L.STATE_CHANGED="STATE_CHANGED",L.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",L.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",L.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",L.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",L.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",L.NETWORK_STATUS="NETWORK_STATUS",L.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",L))(F||{}),V=(p=>(p.IDLE="IDLE",p.OPENED="OPENED",p.CONNECTING="CONNECTING",p.RECONNECTING="RECONNECTING",p.CONNECTED="CONNECTED",p.CLOSED="CLOSED",p.FAILED="FAILED",p))(V||{}),pe=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(pe||{}),Ji=class extends X{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){c.log("Update transport settings",e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){c.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,r=!1){let n=r;for(let s of e){if(this._opened.indexOf(s)!==-1){c.warn(`The participant [${s}] has already had opened transport`);continue}if(this._allocated.indexOf(s)===-1){c.warn(`The participant [${s}] has no allocated transport`);continue}this._opened.push(s),n=!0}!n||(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())),c.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&c.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}getState(){return this._topology==="SERVER"?this._serverTransport.getState():this._directTransport.getState()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===w.TOPOLOGY_CHANGED)return this._onTopologyChanged(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),u.log(g.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],n=e.offerToDeviceIdxs||[],s=i.length&&r.length?S.composeParticipantId(i[0],r[0],n[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){c.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&c.warn("Topology changed to DIRECT, but the allocated participants count more then one");let p=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=s===p;this._directTransport=this._createDirectTransport(p,l)}this._opened.indexOf(p)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_createDirectTransport(e,t=!1){let i=new nt(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._dtListeners&&this._dtListeners.length>0&&c.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new be(this._signaling,this._mediaSource,this._serverSettings);return this._stListeners&&this._stListeners.length>0&&c.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;d.noiseSuppression!==e&&(d.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(u.log(g.PAT_WAITING_TIME_ERROR,"wrongTopology"),c.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(u.log(g.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var ot=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(ot||{}),Yi=class extends X{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,F.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,F.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,F.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,F.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===ae.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Lt(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,d.voiceParams.interval)};this._interval=window.setTimeout(n,d.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===ae.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===we.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e===pe.DIRECT&&(this._activeParticipants=null)}};var zi=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(zi||{}),Qi=class extends X{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i===pe.SERVER,this.subscribe(e,ot.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,F.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,F.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>d.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*d.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent("SPEAKER_CHANGED",e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e===pe.SERVER}};var di=class extends X{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,F.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,ot.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===V.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),d.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),d.specListenerParams.volumeTimeout))),t===V.FAILED&&this._connectionTimeout&&(c.warn("Transport failed, send callSpecError"),u.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==V.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(c.warn("There is not connected transport, send callSpecError"),u.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),u.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&c.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Ln=1e3,Nn=1e4;var Un=15,W=class extends X{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=j.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;u.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),u.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new ai,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Ln))}static current(){return W._current}static hangupAfterInit(){W._activationMutex&&!W._current&&(W._delayedHangup=!0)}static id(){var e,t;return((t=(e=W._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,s=!1){return o(this,null,function*(){if(W._activationMutex)throw u.log(g.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new x(M.FAILED);W._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let p=this._mediaSource.getMediaSettings();t===Ve.CHAT||e.length>1?this._logWithMediaSettings(g.OUTGOING_MULTIPARTY_CALL,p):this._logWithMediaSettings(g.OUTGOING_CALL,p);let l=yield this._startConversation(e,t,je.OUTGOING,i,r,n,s);if(!this._conversation)throw new x(M.UNKNOWN_ERROR);if(this._participantState=j.ACCEPTED,this._signaling.changeMediaSettings(p),yield this._processConnection(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),W._delayedHangup)throw new x(M.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let m=Object.values(this._participants),I;return d.batchParticipantsOnStart&&(I=S.mapSharedParticipants(m)),v.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),v.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,I),this._onConversationParticipantListChunk(l),v.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),W._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(m,J.WAITING),this._conversation}catch(p){throw this._close(p,"Unable to start conversation"),p}finally{W._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){var t;if(W._activationMutex)throw u.log(g.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new x(M.FAILED);W._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.JOIN_CONVERSATION,r);let n=yield this._joinConversation(e);if(!this._conversation)throw new x(M.UNKNOWN_ERROR);return this._conversation.observer=i,v.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(c.log("In waiting hall"),W._current=this,W._activationMutex=!1,this._signaling.readyToSend(),v.onLocalStatus(J.WAITING_HALL),this._conversation):this._onJoinPart2(n)}catch(i){throw W._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return o(this,null,function*(){c.debug("Join conversation part 2"),W._activationMutex=!0;try{if(this._participantState=j.ACCEPTED,!this._conversation||!this._mediaSource)throw new x(M.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(),W._delayedHangup)throw new x(M.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=S.mapSharedParticipants(t)),v.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),this._onConversationParticipantListChunk(e),v.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),W._current=this,d.batchParticipantsOnStart||this._setParticipantsStatus(t,J.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{W._activationMutex=!1}})}onPush(r){return o(this,arguments,function*(e,t=z.USER,i){if(W._activationMutex)throw c.warn("Conversation: there is already running activation"),new x(M.REJECTED);W._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new x(M.UNKNOWN_ERROR);if(!n.conversation.participants.find(p=>{var l;return p.state===j.CALLED&&p.id===((l=this._conversation)==null?void 0:l.userId)}))throw c.log("Push rejected (there is an active call)"),u.log(g.PUSH,"rejected"),new x(M.REJECTED);if(yield this._processConnection(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),u.log(g.PUSH,"accepted"),W._current=this,W._delayedHangup)throw new x(M.CANCELED);W._activationMutex=!1}catch(n){throw W._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Wt.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>S.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return o(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new x(M.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_CONCURRENT,e),c.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),v.onCallAccepted(),this._state="ACTIVE",this._participantState=j.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return o(this,null,function*(){if(this._state!=="IDLE")throw u.log(g.ERROR,"acceptIncoming"),c.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new x(M.UNKNOWN_ERROR);this._state="PROCESSING",c.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=j.ACCEPTED;let i=Object.values(this._participants),r;if(d.batchParticipantsOnStart&&(r=S.mapSharedParticipants(i)),v.onCallAccepted(),v.onLocalStream(this._mediaSource.getStream(),t),v.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),d.useParticipantListChunk){let s=yield this._getInitialParticiapntListChunk();this._onConversationParticipantListChunk({participants:s})}v.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(Ke.MUTE)||n.includes(Ke.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates),void 0,void 0,void 0,void 0,!0)),this._state="ACTIVE",this._changeFeatureSet(),d.batchParticipantsOnStart||this._setParticipantsStatus(i,J.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return o(this,null,function*(){var e;if(this._state!=="IDLE")throw u.log(g.ERROR,"declineIncoming"),c.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",c.debug("Decline incoming call"),this._logWithMediaSettings(g.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=j.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(M.REJECTED)),this._close(new x(M.REJECTED))})}hangup(){return o(this,null,function*(){c.debug("Hangup");let e=this._state==="ACTIVE"?M.HUNGUP:M.CANCELED;u.log(g.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new x(e))):v.onHangup(new x(M.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new x(M.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=M.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(S.composeId(n),n,r)})}removeParticipant(e,t=!1){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let n of e)(n.state===j.CALLED||n.state===j.ACCEPTED)&&(this._transport.isAllocated(n.id)||this._transport.allocate(n.id,t)),n.state===j.ACCEPTED&&i.push(n.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&c.error(t,e),c.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(M.FAILED):u.log(g.ERROR,e.hangup),W._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([M.CANCELED,M.NOT_FRIENDS,M.CALLEE_IS_OFFLINE,M.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===M.REJECTED&&!e.remote){v.onHangup(e,i),this.destroy();return}if(e.hangup===M.HUNGUP&&(!e.remote||this._participantState===j.CALLED)){v.onHangup(e,i),this.destroy();return}if(e.hangup===M.MISSED&&!e.remote){v.onHangup(e,i),this.destroy();return}if(e.hangup===M.SOCKET_CLOSED&&W._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===M.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=j.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),u.destroy(),this._conversation=null,W._current=null,W._delayedHangup=!1,v.onHangup(e||new x(M.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;c.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),u.destroy(),this._conversation=null,W._current=null,W._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return o(this,null,function*(){let t=yield this._api.getConversationParams(e);c.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let s=r.urls.filter((p,l,m)=>m.indexOf(p)===l);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return d.iceServers=i,d.wssBase=t.endpoint,d.wssToken=t.token,t.client_type&&(d.clientType=t.client_type),t})}_addGeoParamsToEndpoint(e,t){return t.isp_as_no&&(e+=`&ispAsNo=${t.isp_as_no}`),t.isp_as_org&&(e+=`&ispAsOrg=${t.isp_as_org}`),t.loc_cc&&(e+=`&locCc=${t.loc_cc}`),t.loc_reg&&(e+=`&locReg=${t.loc_reg}`),e}_startConversation(e,t,i,r,n="",s=!1,p=!1){return o(this,null,function*(){let l=S.uuid();c.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let m=r.includes(ce.VIDEO),I=yield this._api.startConversation(l,e,t,m,n,s,p);c.debug("Api.startConversation",I);let R=yield this._getConversationParams(I.id);I.endpoint=this._addGeoParamsToEndpoint(I.endpoint,R);let O=yield this._connectSignaling(Fe.START,I);return yield this._setConversation(I,O,i),O})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n,observedIds:s}=e;c.debug("Conversation: join",{conversationId:t,joinLink:n,observedIds:s});let p=i.includes(ce.VIDEO),l;if(t)l=yield this._api.joinConversation(t,p,r);else if(n)l=yield this._api.joinConversationByLink(n,p,s);else throw new x(M.UNKNOWN_ERROR);c.debug("Api.joinConversation",l),yield this._getConversationParams(l.id);let m=yield this._connectSignaling(Fe.JOIN,l);return yield this._setConversation(l,m,je.JOINING),m})}_prepareConversation(r){return o(this,arguments,function*(e,t=z.USER,i){c.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let n=this._api.getUserId();if(!n)throw new x(M.UNKNOWN_ERROR);let s=yield this._getConversationParams(e),p=s.device_idx||0,l=`${d.wssBase}?userId=${n}&entityType=${t}&deviceIdx=${p}&conversationId=${e}&token=${d.wssToken}`;l=this._addGeoParamsToEndpoint(l,s);let m={id:e,peerId:i,endpoint:l,is_concurrent:!1,p2p_forbidden:!1,device_idx:p},I=yield this._connectSignaling(Fe.ACCEPT,m);return W._current&&(W._current._participantState===j.ACCEPTED||W._current._participantState===j.CALLED)?(c.log("Push rejected (busy)"),u.log(g.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(M.BUSY),Promise.reject({hangup:M.BUSY})):(W._current&&(W._current.destroy(),W._current=null),yield this._setConversation(m,I,je.INCOMING,t),I)})}_createParticipant(e){return o(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:ge(),participantState:{},state:j.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[]},e);if(e.externalId){let r=S.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(r,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return((i=t.observedIds)==null?void 0:i.length)&&(t.externalId.observer=!0),this._setParticipantMarkers(t,t.markers),t})}_getParticipantId(e){return o(this,null,function*(){try{let t=S.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new x(M.NETWORK_ERROR),t),t}})}_setConversation(n,s,p){return o(this,arguments,function*(e,t,i,r=z.USER){yield this._prepareParticipants(t.conversation.participants);let l=this._api.getUserId(),m=e.device_idx||0;if(!l){let O=(t.conversation.participants||[]).find(L=>S.comparePeerId(L.peerId,t.peerId));if(!O)throw new x(M.UNKNOWN_ERROR);l=Number(O.id),O.idType&&(r=O.idType),O.deviceIdx&&(m=O.deviceIdx),this._api.setUserId(l)}let I=S.composeParticipantId(l,r,m),R=yield this._getParticipantId(I);this._conversation={userId:l,compositeUserId:I,externalId:R,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||pe.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),u.log(g.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new x(M.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||pe.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 Ri;return this.subscribe(e,Pe.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Pe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new xt(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,Se.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,Se.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_processConnection(e){return o(this,null,function*(){yield this._registerConnectionParticipants(e),this._processConnectionData(e)})}_prepareParticipants(e){return o(this,null,function*(){let t=e.map(i=>i.id);t.length&&(yield this._api.prepareUserIds(t))})}_onConversationParticipantListChunk(e){let t=e.participants;t&&v.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(t))}_participantListChunkToExternalChunk(e){let t=S.mapSharedParticipants(e.participants.map(i=>{let r=S.composeId(i);return this._participants[r]}));return _i(ct({},e),{participants:t})}_registerConnectionParticipants(e){return o(this,null,function*(){var t,i;yield this._registerParticipants(e.conversation.participants),((t=e.participants)==null?void 0:t.participants)&&(yield this._registerParticipants((i=e.participants)==null?void 0:i.participants))})}_registerParticipants(e){return o(this,null,function*(){if(!!this._conversation)for(let t of e){let i=S.composeId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(c.debug(`Local roles changed: ${t.roles}`),v.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===j.HUNGUP||t.state===j.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],M.HUNGUP);continue}this._registerParticipantInCache(yield this._createParticipant({id:i,externalId:t.externalId&&he.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:ge(t.mediaSettings),participantState:S.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?J.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[],markers:this._denormalizeMarkers(i,t.markers)})),t.roles&&t.roles.length&&(c.debug(`Roles for participant [${i}] changed: ${t.roles}`),v.onRolesChanged(this._participants[i].externalId,t.roles))}})}_getClientType(){return d.clientType}_getStatusByTransportState(e){let t;return e===V.CONNECTED?t=J.CONNECTED:e===V.CONNECTING||e===V.OPENED?t=J.CONNECTING:e===V.RECONNECTING&&(t=J.RECONNECT),t}_registerParticipantInCache(e){return this._participants[e.id]=e}_getExistedParticipantByIdOrCreate(e){return o(this,null,function*(){return this._participants[e]||this._createParticipant({id:e})})}_getExternalIdByParticipantId(e){return o(this,null,function*(){var t;return d.useParticipantListChunk?(yield this._getExistedParticipantByIdOrCreate(e)).externalId:(t=this._participants[e])==null?void 0:t.externalId})}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){return o(this,null,function*(){if(d.useParticipantListChunk){let i=this._registerParticipantInCache(yield this._getExistedParticipantByIdOrCreate(e));return this._setParticipantMarkers(i,t),i}return this._participants[e]})}_warnParticipantNotInConversation(e){c.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(r=>"ts"in r&&"rank"in r);return Object.entries(t).reduce((r,[n,s])=>(r[n]=_i(ct(ct({},i),s),{id:e}),r),{})}_processConnectionData(e){return o(this,null,function*(){S.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&(yield this._onPinParticipant(e.conversation.pinnedParticipantId)),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Ht.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)})}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Ji(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new ni,this.subscribe(this._transport,F.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,F.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,F.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,F.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,F.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,F.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,F.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,F.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,F.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,F.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,F.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===je.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===j.ACCEPTED||t.state===j.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new Yi(this._transport),this.subscribe(this._volumesDetector,ot.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Qi(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,zi.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new si(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new di(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=C.getCameras().length,t=C.getMicrophones().length;c.debug("Cameras: "+e+(C.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(C.hasMicrophonePermission()?"✔":"✖")),u.log(g.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){u.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===j.CALLED||e.state===j.ACCEPTED||this._state==="CLOSE"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),!!this._participants[e.id]&&(t===M.HUNGUP?this._setParticipantsStatus([e],J.HANGUP):this._setParticipantsStatus([e],J.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Te.CAMERA,stopStream:!0}]),delete this._participants[e.id],v.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,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){c.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return o(this,null,function*(){c.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===j.ACCEPTED||r.state===j.CALLED)){c.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(r=this._registerParticipantInCache(yield this._createParticipant({id:e,externalId:t.externalId&&he.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([r],J.WAITING),i?(r.state=j.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=j.CALLED,this._transport.allocate(r.id,!0),u.log(g.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){c.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=Un;i++){let r=S.compose(e,i),n=this._participants[r];n&&t.push(n)}if(!t.length){this._warnParticipantNotInConversation(e);return}if(this._transport)for(let i of t)this._transport.close(i.id);u.log(g.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new xt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ie.UNKNOWN)})}toggleScreenCapturing(e){return o(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ie.UNKNOWN)})}setVideoStream(e,t=!1){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return o(this,null,function*(){if(this._mediaSource)return u.log(g.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return u.log(g.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return o(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let n=typeof r.uid=="object"?r.uid:he.fromId(r.uid),s=he.toString(n);i[s]=r.priority}for(let r of Object.values(this._participants)){let n=he.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return o(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return o(this,null,function*(){let t={};return t[We(e)]={keyFrameRequested:!0},this._signaling.updateDisplayLayout(t)})}requestTestMode(e,t){return o(this,null,function*(){return this._signaling.requestTestMode(e,t)})}updateDisplayLayout(e){return o(this,null,function*(){if(e.length<1||!this._signaling.ready)return;c.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:he.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(n);if(!s){let I=he.toString(n);c.log(`Unknown participant external ID ${I}`);continue}let p=S.compose(s,n.deviceIdx),l=We({participantId:p,mediaType:r.mediaType,streamName:r.streamName}),m=this._participants[p];m&&(m.lastRequestedLayouts[l]=r),Ot(r)?this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now()):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&d.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=r)}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>d.videoTracksCount;){let r=i.next();if(r.done){c.error("Cannot accommodate all streaming requests: tracks available "+d.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]={stopStream:!0}}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(c.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=wt(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Te.STREAM||i.mediaType===Te.SCREEN)?v.onRemoteLive(r.externalId,i.streamName,null):v.onRemoteStream(r.externalId,null),u.log(g.PAT_DEALLOCATED)):c.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return o(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,n]of Object.entries(t.errorCodeByParticipantId||{})){let s=wt(r),p=this._participants[s.participantId];if(p){let l;typeof n!="number"?(c.warn(`Unexpected error code ${n} received for participant ${s.participantId}`),l=wr.UNKNOWN_ERROR):l=xr(n),i.push({externalId:p.externalId,errorReason:l})}}if(i&&i.length)throw new pi("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+Nn>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e)}_onParticipantSourcesUpdate(e){if(this._conversation){c.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){c.log("Promoted in waiting hall",!e.demote),e.demote?(c.log("Kicked from waiting hall"),this._close(new x(M.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return o(this,arguments,function*(e,t=0,i=[]){c.log(`Chat room updated: ${e}`);let n=[],s=[];i.length&&(i.forEach(p=>{if(p.externalId){let l=fe.fromSignaling(p.externalId);n.push(l),this._api.cacheExternalId(p.id.id,l)}else s.push(S.decomposeId(p.id.id).id)}),s.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(s))),v.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var p,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenDataChannel&&t.mediaType===Te.SCREEN)return;let i=We(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){c.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),u.log(g.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let m=t.participantId,I=this._participants[m];if(!I){u.log(g.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${m}`);return}let R=this._streamByStreamId.get(n);if(!R){u.log(g.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${n}`);return}u.log(g.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let O=(p=e.participantStreamDescription)==null?void 0:p.mediaType;if(O===Te.STREAM||O===Te.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&v.onRemoteLive(I.externalId,e.participantStreamDescription.streamName,R);else if(d.producerScreenTrack&&O===Te.SCREEN)v.onRemoteScreenStream(I.externalId,R);else{let L=(d.producerScreenTrack?null:I.secondStream)||R;v.onRemoteStream(I.externalId,L)}}else{c.debug(`Waiting for ${s} until stream ${n} for ${i} is switched`);let m=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,m)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(We(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(We(i)))return i}else{let i={participantId:t,mediaType:Te.CAMERA};if(this._streamIdByStreamDescription.has(We(i)))return i;let r={participantId:t,mediaType:Te.SCREEN};if(this._streamIdByStreamDescription.has(We(r)))return r}return c.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?S.includesOneOf(this._conversation.roles,[Qe.ADMIN,Qe.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!S.includesOneOf(this._conversation.roles,[Qe.ADMIN,Qe.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return o(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return o(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return o(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Tr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return o(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=pa(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let s=n.participants||[],p=[],l=[],m=null;return s.length&&(s.forEach(I=>{if(I.externalId){let R=fe.fromSignaling(I.externalId);p.push(R),this._api.cacheExternalId(I.id.id,R)}else l.push(S.decomposeId(I.id.id).id)}),l.length&&!p.length&&(p=yield this._api.getExternalIdsByOkIds(l)),n.hasMore&&(m=da(s[s.length-1].id))),{participants:p,pageMarker:m,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return o(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return o(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return o(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return o(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return o(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return o(this,null,function*(){var p;let n={movieId:e,participantId:(p=this._conversation)==null?void 0:p.compositeUserId};(t||t===0)&&(n.gain=t),i&&(n.offset=i),typeof r!==void 0&&(n.pause=r);let s=yield this._signaling.updateMovie(n);if(s.error)throw new Error(s.error)})}removeMovie(e){return o(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",n=null){return o(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},p=yield this._signaling.startStream(s);return p.error?Promise.reject(p.message):p})}stopStream(){return o(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return o(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return o(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return o(this,null,function*(){var r;if(e<d.videoMinWidth||t<d.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<d.videoMinWidth||i.effect.height<d.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");d.videoEffectMaxHeight=i.effect.height,d.videoEffectMaxWidth=i.effect.width}return d.videoMaxWidth=e,d.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return o(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}getParticipants(e){return o(this,null,function*(){let t=e.externalIds.map(s=>({id:s.id,type:this._getClientType()})),i=yield this._signaling.getParticipants(t);if(i.error)throw new Error(i.error);let r=i.participants,n=this._transport.getState();return Promise.all(r.map(s=>o(this,null,function*(){var l;let p=S.composeId(s);return this._createParticipant({id:p,externalId:s.externalId&&he.fromSignaling(s.externalId,s.deviceIdx||0),mediaSettings:ge(s.mediaSettings),participantState:S.mapParticipantState(s),state:s.state,roles:s.roles||[],status:(l=this._getStatusByTransportState(n))!=null?l:J.WAITING,muteStates:s.muteStates||{},unmuteOptions:s.unmuteOptions||[],observedIds:s.observedIds||[],markers:this._denormalizeMarkers(p,s.markers)})}))).then(S.mapSharedParticipants)})}getParticipantListChunk(e){return o(this,null,function*(){let t=yield this._signaling.getParticipantListChunk(e);if(t.error)throw new Error(t.error);let i=t.chunk,r=i.participants.filter(p=>{let l=S.composeId(p);return!this._participants[l]});yield this._registerParticipants(r);let n=this._transport.getState();return i.participants.forEach(p=>{var I;let l=S.composeId(p),m=this._participants[l];m.status=(I=this._getStatusByTransportState(n))!=null?I:J.WAITING}),this._participantListChunkToExternalChunk(i)})}_getInitialParticiapntListChunk(){return o(this,null,function*(){let e=d.participantListChunkInitIndex,t=d.participantListChunkInitCount,i="GRID";return(yield this._signaling.getParticipantListChunk({listType:i,fromIdx:e,count:t})).chunk})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t,i;!this._conversation||(c.debug("Local media stream changed",e.mediaSettings),v.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return o(this,null,function*(){var t,i;if(c.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;v.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){c.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];if(!i){this._warnParticipantNotInConversation(e);return}i.mediaSettings=t,this._state==="ACTIVE"&&v.onRemoteMediaSettings(i.externalId,t,i.markers),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t)}_changeRemoteParticipantState(e,t){c.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];if(!i){this._warnParticipantNotInConversation(e);return}i.participantState=t||{},this._state==="ACTIVE"&&v.onRemoteParticipantState(i.externalId,i.participantState,i.markers)}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(c.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),v.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case w.ACCEPTED_CALL:return this._onAcceptedCall(e);case w.HUNGUP:return this._onHungup(e);case w.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case w.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case w.CLOSED_CONVERSATION:return this._onClosedConversation(e);case w.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case w.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case w.RATE_CALL_DATA:return this._onNeedRate();case w.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case w.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case w.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case w.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case w.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case w.REGISTERED_PEER:return this._onPeerRegistered(e);case w.SWITCH_MICRO:return this._onMicSwitched(e);case w.CHAT_MESSAGE:return this._onChatMessage(e);case w.CUSTOM_DATA:return this._onCustomData(e);case w.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case w.RECORD_STOPPED:return this._onRecordInfo(null);case w.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case w.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case w.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin,e.markers);case w.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case w.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case w.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case w.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants);case w.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e)}}_onSignalingReconnect(e){return o(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?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),r=[];for(let n of e.conversation.participants){let s=S.composeId(n),p=n.roles||[];if(s===this._conversation.compositeUserId){t=ge(n.mediaSettings),yt(this._conversation.roles,p)||this._onRolesChanged(s,p);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let m=ge(n.mediaSettings);Wr(m,l.mediaSettings)||this._changeRemoteMediaSettings(s,m);let I=S.mapParticipantState(n),R=l.participantState;S.isEqualParticipantState(I,R)||this._changeRemoteParticipantState(s,I),yt(p,l.roles)||this._onRolesChanged(l.id,p)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],M.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){c.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return o(this,null,function*(){let t=S.composeMessageId(e),i=S.getPeerIdString(e.peerId);if(c.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new x(M.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(r=this._registerParticipantInCache(yield this._createParticipant({id:t,mediaSettings:ge(e.mediaSettings)}))),r.state=j.ACCEPTED,r.mediaSettings=ge(e.mediaSettings),this._logWithMediaSettings(g.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===je.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){return o(this,null,function*(){c.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=S.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new x(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===M.REJECTED?j.REJECTED:j.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,M.HUNGUP)})}_onAddedParticipant(e){return o(this,null,function*(){var r,n;c.debug(`Participant added [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state!==j.HUNGUP&&i.state!==j.REJECTED){c.debug(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&he.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}))),i.state=j.CALLED,i.mediaSettings=ge((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=S.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),v.onParticipantAdded(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return o(this,null,function*(){var r,n;c.debug(`Participant joined [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state===j.ACCEPTED){c.warn(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&he.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[],markers:this._denormalizeMarkers(t,e.participant.markers)}))),this._conversation&&this._conversation.direction===je.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=j.ACCEPTED,i.mediaSettings=ge(e.mediaSettings),i.participantState=S.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],J.CONNECTED):this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((n=this._conversation)==null?void 0:n.observer))),v.onParticipantJoined(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new x(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){return o(this,null,function*(){let t=S.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,ge(e.mediaSettings))})}_onParticipantStateChanged(e){return o(this,null,function*(){let t=S.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteParticipantState(t,S.mapParticipantState(e))})}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),v.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ge(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),d.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){c.debug("Got settings update notification",e);let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Ki(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){c.debug("Got video quality update notification",e);let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=Ki(this._serverSettings,r),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=S.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return o(this,null,function*(){v.onDeviceSwitched(ce.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return o(this,null,function*(){let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),v.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return o(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),v.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return o(this,null,function*(){var i;if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let r=yield this._getParticipantId(e.initiator);v.onRecordStarted(r,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else v.onRecordStopped();this._conversation.recordInfo=e,e&&this._transport.getTopology()===pe.SERVER&&this._participantState!==j.CALLED&&this._transport.open(this._transport.allocated(),null,!!((i=this._conversation)==null?void 0:i.observer),!0)})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!yt(this._conversation.roles,t)){c.debug(`Local roles changed: ${t}`),this._conversation.roles=t,v.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates),void 0,void 0,void 0,void 0,!0);return}let i=this._participants[e];i&&!yt(i.roles,t)&&(c.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,v.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){c.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let p=this._participants[e.participantId];p&&(c.debug(`Mute states for participant [${e.participantId}] changed`,i),v.onMuteStates(i,r,n,e.muteAll,e.unmute,p.externalId,s==null?void 0:s.externalId,e.stateUpdated,e.requestedMedia));return}if(!(S.isObjectsEquals(this._conversation.muteStates,i)&&S.isArraysEquals(this._conversation.unmuteOptions,r)&&!n.length)){if(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId===this._conversation.compositeUserId){e.muteAll&&v.onMuteStates(i,r,n,e.muteAll,e.unmute,null,this._conversation.externalId,e.stateUpdated,e.requestedMedia);return}yield this._processMuteState(n,e.muteAll,e.unmute,t,s,e.stateUpdated,e.requestedMedia)}})}_processMuteState(){return o(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null,s,p){if(!this._conversation||!this._mediaSource||this._participantState!==j.ACCEPTED)return;let l=Object.assign({},this._conversation.muteStates),m=this._conversation.unmuteOptions,I=this._mediaSource.getMediaSettings(),R=Object.entries(l);for(let[O,L]of R)if(!(L!==Ke.MUTE&&L!==Ke.MUTE_PERMANENT)&&(this._isCallAdmin()&&L===Ke.MUTE_PERMANENT&&!t&&(l[O]=Ke.MUTE),!(!e.includes(O)||i)))switch(O){case ce.VIDEO:I.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(v.onDeviceSwitched(ce.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case ce.AUDIO:I.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(v.onDeviceSwitched(ce.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case ce.SCREEN_SHARING:I.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(v.onDeviceSwitched(ce.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}v.onMuteStates(l,m,e,t,i,null,n==null?void 0:n.externalId,s,p)})}_onPinParticipant(e,t=!1,i){return o(this,null,function*(){if(!this._conversation)return;let r=this._conversation.pinnedParticipantId;if(r&&r!==e)if(this._conversation.compositeUserId===r)v.onLocalPin(!0);else{let n=yield this._getExternalIdByParticipantId(r);n&&v.onPinnedParticipant(n,!0,this._denormalizeMarkers(e,i))}if(this._conversation.compositeUserId===e)v.onLocalPin(t);else{let n=yield this._getExternalIdByParticipantId(e);n&&v.onPinnedParticipant(n,t,this._denormalizeMarkers(e,i))}this._conversation.pinnedParticipantId=t?null:e})}_onOptionsChanged(e){this._conversation&&!Er(this._conversation.options,e)&&(this._conversation.options=e,v.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let n;if(i===this._conversation.compositeUserId||i==="")n=this._conversation.networkRating;else if(this._participants[i])n=this._participants[i].networkRating;else continue;if(n!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,v.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;c.log("Received network status update: ",e),v.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){v.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,d.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){c.error("Received remote stream notification for a participant that has no track associated with it",r);return}let n=this._streamIdByStreamDescription.get(r);if(!n||this._streamWaitTimerByStreamDescription.has(r)){c.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(n);if(!s){u.log(g.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${n}`);return}v.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&v.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===pe.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Sr.ADD_PARTICIPANT);v.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&v.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}v.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(v.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){c.debug(`Transport state has changed: ${t}`,e);let i=this._getStatusByTransportState(t);if(!i)return;let r=e.reduce((n,s)=>{if(s in this._participants){let p=this._participants[s];n.push(p),t===V.CONNECTED&&(p.remoteStream||(p.mediaSettings&&this._changeRemoteMediaSettings(s,p.mediaSettings),this._changeRemoteParticipantState(s,p.participantState)),this._updateDisplayLayoutFromCache(s))}else this._warnParticipantNotInConversation(s);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){c.debug(`Local transport state has changed: ${e}`),e===V.CONNECTED&&v.onLocalStatus(J.CONNECTED),e===V.CONNECTING&&v.onLocalStatus(J.CONNECTING),e===V.RECONNECTING&&v.onLocalStatus(J.RECONNECT),e===V.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(M.FAILED)),this._close(new x(M.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(we.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i),v.onRemoteMixedAudioStream(t);else if(e.startsWith(we.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))c.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{c.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(c.warn(`Conversation: track added before participant [${e}]`),r=this._registerParticipantInCache(yield this._createParticipant({id:e})),this._setParticipantsStatus([r],J.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(v.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===ae.audio&&(this._audioOutput.add(i),d.preserveAudioTracks||t.removeTrack(i)),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;v.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),d.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(c.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case ae.audio:this._removeAudioTrack(e,t,i);break;case ae.video:case ae.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==we.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e===pe.DIRECT&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let n=this._participants[r];e||this._lastStalled[r]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,J.RECONNECT),i.length&&this._setParticipantsStatus(i,J.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let s=this._participants[n];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let s=this._participants[n];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,J.RECONNECT),r.length&&this._setParticipantsStatus(r,J.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!C.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(c.debug("Toggle join availability",{available:t,chatId:e}),v.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==pe.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,s)=>(s.status!==t&&(s.status=t,d.batchParticipantsOnStart?n.push(s.externalId):v.onParticipantStatus(s.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&v.onRemoteStatus(r,t,i)}_onJoinLinkChanged(e){v.onJoinLinkChanged(e.joinLink)}},U=W;U._delayedHangup=!1;var pi=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,pi.prototype),this.participantErrors=t}};var Bt,li=null;function Bn(){return o(this,null,function*(){var a;if(d.apiEnv!=="AUTO")return d.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(a=i==null?void 0:i.Answer[0])==null?void 0:a.data;if(!r)throw new Error("Wrong DNS response");return c.debug("Resolved API endpoint",r),r}catch(e){return c.warn("Failed to resolve API endpoint using DNS, default is used",e),d.apiEndpoint}})}function ha(){return Bt?Promise.resolve(Bt):li||(li=Bn().then(a=>Bt=a).finally(()=>li=null))}function _a(){if(!d.apiKey)throw new x(ie.API,{message:"Required argument apiAppKey not passed"})}function Xi(i){return o(this,arguments,function*(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;yield ha();let r=fa(a,e,t),n=new window.Blob([r],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${Bt}/fb.do`,n)})}function ga(i){return o(this,arguments,function*(a,e={},t=!1){yield ha();let r=fa(a,e,t);return Vn(r)})}function Vn(a){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${Bt}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(n){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(a)})})}function fa(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=d.apiKey),t||(ee.sessionKey?e.session_key=ee.sessionKey:ee.accessToken&&(e.access_token=ee.accessToken));for(let[r,n]of Object.entries(e))typeof n=="object"&&(e[r]=JSON.stringify(n));let i="";for(let[r,n]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(n)}`;return i}var Gn=10,Hn=700,Wn=3e3,Vt=class extends dt{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return o(this,arguments,function*(e,t={},i=!1){let n=s=>o(this,null,function*(){try{return yield ga(e,t,i)}catch(p){if(!p.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<Gn))return yield S.delay(Math.min(s*Hn,Wn)),n(s);throw c.warn(e,"error",p),p}});return n(0)})}_call(r){return o(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){c.warn("Api call error",n);let s=ie.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=M.SERVICE_DISABLED;break;case 1102:s=M.CALLEE_IS_OFFLINE;break;case 1103:s=M.NOT_FRIENDS;break;case 1104:case 1106:s=M.EXTERNAL_API_ERROR;break}throw new x(s,{message:n.error_msg,code:n.error_code})}})}userId(e){return o(this,null,function*(){let t=S.decomposeId(e).id;return ee.isEmpty()?fe.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),fe.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return o(this,null,function*(){ee.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return o(this,null,function*(){if(!this._uuid){let t=$e.get("uuid");t||(t=S.uuid(),$e.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:d.appVersion,client_type:"SDK_JS"}};return d.authToken&&(e.session_data.auth_token=d.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),ee.sessionKey=t.session_key,ee.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&v.onTokenExpired(),new x(ie.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${d.appName}:${d.sdkVersion}`,platform:d.platform,items:e})};Xi("log.externalLog",t)}init(){_a()}joinConversation(e,t=!1,i){return o(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:d.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return o(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1,protocolVersion:d.protocolVersion};return t&&(r.payload=t),d.domain&&(r.domainId=d.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,n="",s=!1,p=!1){return o(this,null,function*(){let l={conversationId:e,isVideo:r,protocolVersion:d.protocolVersion};if(t&&t.length)switch(i){case Ve.USER:l.uids=t.join(",");break;case Ve.GROUP:l.gid=t[0];break;case Ve.CHAT:l.chatId=t[0];break}return s&&(l.createJoinLink=!0),n&&(l.payload=n),d.domain&&(l.domainId=d.domain),p&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return o(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return o(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return o(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return o(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i){return o(this,null,function*(){let r={joinLink:e,isVideo:t,protocolVersion:d.protocolVersion};return(i==null?void 0:i.length)&&(r.observedIds=i.join(",")),d.anonymToken&&(r.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",r)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=fe.fromIds(e),i=[],r={methods:[]},n=[],s=Object.keys(this._externalUidsCache),p=Object.values(this._externalUidsCache);for(let m of t){let I=fe.toString(m),R=p.indexOf(I);R>-1?i.push(Number(s[R])):(n.push(I),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:m.id,anonym:m.type===rt.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((m,I)=>{if(m.ok){let R=Number(m.ok.ok_id);this._externalUidsCache[R]=n[I],i.push(R)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(fe.fromString(this._externalUidsCache[n])):i.push(n);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let n of i)r.hasOwnProperty(n)&&t.push(fe.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=fe.toString(e),n=i.indexOf(r);return n>-1?S.composeUserId(t[n],z.USER):null}cacheExternalId(e,t){let i=S.decomposeId(e).id;this._externalUidsCache[i]=fe.toString(t)}getConversationParams(e){return o(this,null,function*(){let t={};return d.anonymToken&&(t.anonymToken=d.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:M.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),Xi("vchat.hangupConversation",t)}removeHistoryRecords(e){return o(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return o(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,n]of Object.entries(i.external_ids))t[r]=fe.fromIdToString(n,rt.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=fe.fromIdToString(n,rt.ANONYM);return t}catch(i){return t}})}};var G=ze(require("messagepack"));var Sa=(b=>(b.RECOVER="recover",b.ACCEPT_CALL="accept-call",b.ADD_PARTICIPANT="add-participant",b.REMOVE_PARTICIPANT="remove-participant",b.HANGUP="hangup",b.TRANSMIT_DATA="transmit-data",b.ACCEPT_PRODUCER="accept-producer",b.ALLOCATE_CONSUMER="allocate-consumer",b.CHANGE_MEDIA_SETTINGS="change-media-settings",b.CHANGE_PARTICIPANT_STATE="change-participant-state",b.CHANGE_STREAM_PRIORITIES="change-streams-priorities",b.UPDATE_DISPLAY_LAYOUT="update-display-layout",b.REPORT_PERF_STAT="report-perf-stat",b.RECORD_START="record-start",b.RECORD_STOP="record-stop",b.RECORD_SET_ROLE="record-set-role",b.RECORD_GET_STATUS="record-get-status",b.SWITCH_MICRO="switch-micro",b.SWITCH_TOPOLOGY="switch-topology",b.REQUEST_REALLOC="request-realloc",b.CHAT_MESSAGE="chat-message",b.CHAT_HISTORY="chat-history",b.CUSTOM_DATA="custom-data",b.GRANT_ROLES="grant-roles",b.MUTE_PARTICIPANT="mute-participant",b.PIN_PARTICIPANT="pin-participant",b.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",b.CHANGE_OPTIONS="change-options",b.GET_WAITING_HALL="get-waiting-hall",b.GET_PARTICIPANT_LIST_CHUNK="get-participant-list-chunk",b.GET_PARTICIPANTS="get-participants",b.PROMOTE_PARTICIPANT="promote-participant",b.REQUEST_TEST_MODE="request-test-mode",b.ADD_MOVIE="add-movie",b.UPDATE_MOVIE="update-movie",b.REMOVE_MOVIE="remove-movie",b))(Sa||{}),B=Sa;function ui(){let a=new DataView(new ArrayBuffer(64)),e=0;function t(i){if(e+i>a.byteLength){let r=new Uint8Array(Math.max(e+i,a.byteLength+64));r.set(new Uint8Array(a.buffer.slice(0,e))),a=new DataView(r.buffer)}}return{put(i){if(t(i.byteLength),jn(i)){let r=i.buffer;new Uint8Array(a.buffer).set(new Uint8Array(r),e)}else new Uint8Array(a.buffer).set(new Uint8Array(i),e);e+=i.byteLength},putI8(i){t(1),a.setInt8(e,i),++e},putI16(i){t(2),a.setInt16(e,i),e+=2},putI32(i){t(4),a.setInt32(e,i),e+=4},putI64(i){t(8);let r=i<0;r&&(i=-i);let n=i/4294967296|0,s=i%4294967296|0;r&&(s=~s+1|0,n=s===0?~n+1|0:~n),a.setUint32(e,n),a.setUint32(e+4,s),e+=8},putUi8(i){t(1),a.setUint8(e,i),++e},putUi16(i){t(2),a.setUint16(e,i),e+=2},putUi32(i){t(4),a.setUint32(e,i),e+=4},putUi64(i){t(8),a.setUint32(e,i/4294967296|0),a.setUint32(e+4,i%4294967296),e+=8},putF(i){t(8),a.setFloat64(e,i),e+=8},ui8array(){return new Uint8Array(a.buffer.slice(0,e))}}}function jn(a){return a.buffer!==void 0}function Zi(a){let e=ArrayBuffer.isView(a)?new DataView(a.buffer,a.byteOffset,a.byteLength):new DataView(a),t=0;return{peek(){return e.getUint8(t)},get(i){t+=i;let r=e.byteOffset;return e.buffer.slice(r+t-i,r+t)},getI8(){return e.getInt8(t++)},getI16(){return t+=2,e.getInt16(t-2)},getI32(){return t+=4,e.getInt32(t-4)},getI64(){t+=8;let i=e.getInt32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getUi8(){return e.getUint8(t++)},getUi16(){return t+=2,e.getUint16(t-2)},getUi32(){return t+=4,e.getUint32(t-4)},getUi64(){t+=8;let i=e.getUint32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getF32(){return t+=4,e.getFloat32(t-4)},getF64(){return t+=8,e.getFloat64(t-8)}}}var va=0,Ea=1,Kn=0,qn=1,$n=2,er=0,Jn=0,Yn=0,zn=1,tr=class{constructor(){this.participantIdRegistry=null}setParticipantIdRegistry(e){this.participantIdRegistry=e}serializeUpdateDisplayLayout(e,t){let i=ui();G.Int.enc(i,va),G.Int.enc(i,er),G.Int.enc(i,e),G.Nil.enc(i,null);let r=[];for(let n in t)t.hasOwnProperty(n)&&this.writeLayout(t,n,r);return G.Arr.enc(i,r),G.Nil.enc(i,null),i.ui8array()}writeLayout(e,t,i){let r=e[t],n=ui();if(this.writeStreamDesc(t,n),Ot(r))G.Int.enc(n,qn);else if(Wi(r))G.Int.enc(n,$n);else if(G.Int.enc(n,Kn),r.priority!==void 0?G.Int.enc(n,r.priority):G.Nil.enc(n,null),r.width!==void 0&&r.height!==void 0?(G.Int.enc(n,Math.round(r.width)),G.Int.enc(n,Math.round(r.height))):(G.Nil.enc(n,null),G.Nil.enc(n,null)),r.fit!==void 0)switch(r.fit){case"cv":G.Int.enc(n,Yn);break;case"cn":G.Int.enc(n,zn);break;default:G.Nil.enc(n,null)}else G.Nil.enc(n,null);i.push(n.ui8array())}writeStreamDesc(e,t){if(this.participantIdRegistry){let i=this.participantIdRegistry.getCompactId(e);if(i!==void 0){G.Int.enc(t,i);return}}G.Str.enc(t,e)}serializePerfStatReport(e,t){let i=ui();return G.Int.enc(i,Ea),G.Int.enc(i,er),G.Int.enc(i,e),G.Int.enc(i,t.framesDecoded),G.Int.enc(i,t.framesReceived),i.ui8array()}deserializeCommandResponse(e){let t=Zi(e),i=G.Int.dec(t),r=G.Int.dec(t);if(r!==er){c.warn("Unsupported version for command type: "+i+", version "+r);return}if(G.Int.dec(t)!==Jn){c.warn("Error code: "+i+"received for command type: "+i+", version "+r);return}switch(i){case va:return this.deserializeUpdateDisplayLayoutResponse(t);case Ea:return this.deserializeReportPerfStatResponse(t);default:return c.warn("unsupported command response commandType: "+i),null}}deserializeUpdateDisplayLayoutResponse(e){let t=G.Int.dec(e),i=G.Arr.dec(e),r={};return i.forEach(n=>{let s=Zi(n),p=G.Any.dec(s);if(typeof p=="string")r[p]=G.Int.dec(s);else{let l=p,m=We(this.participantIdRegistry.getStreamDescription(l));r[m]=G.Int.dec(s)}}),{type:"response",sequence:t,response:B.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:r}}deserializeReportPerfStatResponse(e){let t=G.Int.dec(e),i=G.Int.dec(e);return{type:"response",sequence:t,response:B.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:i}}};var Ta="open",Ia=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0,()=>d.movieShare,()=>d.useParticipantListChunk],Qn=10,Me=class extends lt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+d.platform+"&appVersion="+d.appVersion+"&version="+d.protocolVersion+"&device="+d.device+"&capabilities="+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.producerCommandDataChannelEnabled=!1;this.producerCommandSerializationService=new tr}static _getCapabilityFlags(){let e=0;for(let t=0;t<Ia.length;t++)Ia[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 r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=t=>{let i=this.producerCommandSerializationService.deserializeCommandResponse(t.data);i&&this._handleMessage(i)},this._handleCommandsQueue(this.datachannelCommandsQueue)}useCommandDataChannel(e){this.producerCommandDataChannelEnabled=e}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return o(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){u.log(g.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return o(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=S.decomposeParticipantId(t.participantId),s=S.decomposeId(n.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),n.deviceIdx&&(t.deviceIdx=n.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return o(this,arguments,function*(e,t={},i=0){let n=s=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===Ta&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){u.log(g.SOCKET_ACTION,"not_opened"),c.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(u.log(g.SOCKET_ACTION,"invalid_state"),c.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,p)=>{let l=(I,R=!1)=>{!i||R?p(I):(c.debug("Resending a signaling message",e,m.sequence),i--,n(m))},m={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};n(m)})})}_isDataChannelCommand(e){return this.producerCommandDataChannelEnabled?e===B.UPDATE_DISPLAY_LAYOUT||e===B.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===B.UPDATE_DISPLAY_LAYOUT||e===B.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(B.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(B.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e,t){return o(this,null,function*(){return this._send(B.REQUEST_TEST_MODE,{consumer:e,producer:t})})}sendSdp(e,t){return o(this,null,function*(){return this._send(B.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(B.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(B.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},Qn)})}changeParticipantState(e){return o(this,null,function*(){return this._send(B.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(B.ADD_PARTICIPANT,ct({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(B.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return o(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(B.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(B.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(B.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(B.UPDATE_DISPLAY_LAYOUT,e)})}addMovie(e){return o(this,null,function*(){return this._send(B.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(B.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(B.REMOVE_MOVIE,e)})}startStream(e){return o(this,null,function*(){return this._send(B.RECORD_START,e)})}stopStream(){return o(this,null,function*(){return this._send(B.RECORD_STOP)})}recordSetRole(e,t){return o(this,null,function*(){return this._send(B.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return o(this,null,function*(){return this._send(B.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(B.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(B.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(B.REPORT_PERF_STAT,e)})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(B.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(B.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(B.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return o(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(B.GRANT_ROLES,r)})}muteParticipant(e,t,i){return o(this,null,function*(){return this._sendRaw(B.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return o(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(B.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(B.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(B.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return o(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(B.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(B.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}getParticipantListChunk(e){return o(this,null,function*(){return this._send(B.GET_PARTICIPANT_LIST_CHUNK,e)})}getParticipants(e){return o(this,null,function*(){return this._send(B.GET_PARTICIPANTS,{externalIds:e})})}_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),c.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor();function i(r){if(!d.useParticipantListChunk)return r;r+=`&partIdx=${d.participantListChunkInitIndex}`;let s=d.participantListChunkInitCount;return s!==null&&(r+=`&partCount=${s}`),r}}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){c.debug("Socket opened"),u.log(g.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){u.log(g.SOCKET_ACTION,"parse_error"),c.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(c.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(Se.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Se.NOTIFICATION,{type:"notification",notification:w.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(Se.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(u.log(g.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(u.log(g.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new x(M.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(Se.NOTIFICATION,{notification:w.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new x(ie.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(u.log(g.SOCKET_ACTION,"unknown_message"),c.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(Se.FAILED,e)}_onError(e){u.log(g.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){u.log(g.SOCKET_ACTION,"closed"),c.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));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),u.log(g.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Fe.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],u.log(g.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Me.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift();if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==Ta){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}Me._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:r.name,sequence:r.sequence}),Me.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r);let s=this._serializeBinary(r);s!==null&&this.producerCommandDataChannel.send(s)}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:r.name,sequence:r.sequence}),Me.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(this._serializeJson(r))}}}_serializeBinary(e){switch(e.name){case B.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case B.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params)}return c.warn("cannot get binary data for data channel command: "+e.name),null}_serializeJson(e){let t;e.name===B.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 r in t)t.hasOwnProperty(r)&&(i[r]=sa(t[r]));return{layouts:i}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new x(ie.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(()=>{c.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}},Le=Me;Le.RECONNECT_DELAY=d.signalingReconnectDelay,Le.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,Le.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,Le.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,Le.WAIT_RESPONSE_DELAY=d.waitResponseDelay,Le.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var Ca=(t=>(t.KING="KING",t.PAWN="PAWN",t))(Ca||{}),ya=Ca;var Tt,ne,Ft=null,Xn={getCameras:C.getCameras,getMicrophones:C.getMicrophones,getOutput:C.getOutput,hasCamera:C.hasCamera,hasMicrophone:C.hasMicrophone,getSavedCamera:C.getSavedCamera,getSavedMicrophone:C.getSavedMicrophone,getSavedOutput:C.getSavedOutput,hasCameraPermission:C.hasCameraPermission,hasMicrophonePermission:C.hasMicrophonePermission,hasPermissions:C.hasPermissions,getUserMedia:C.getUserMedia,getUserVideo:C.getUserVideo,getUserAudio:C.getUserAudio,saveDeviceId:C.saveDeviceId,isBrowserSupported:C.isBrowserSupported,isScreenCapturingSupported:C.isScreenCapturingSupported,os:C.os,isMobile:C.isMobile,browserName:C.browserName,browserVersion:C.browserVersion,baseChromeVersion:C.baseChromeVersion,getAudioContext:C.getAudioContext};function Pa(a){ne=a}function Ra(a){Tt=a}function Zn(a){Ft=a}function es(a){d.videoEffects=a}function ts(a){return o(this,null,function*(){if(d.set(a),C.browserName()==="Sferum"&&(d.platform=`SFERUM:${C.browserVersion()}`),ne||Pa(new Vt),Tt||Ra(()=>new Le),d.debug&&(ir.default.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${d.sdkVersion}`,a),yield C.init(),!C.isBrowserSupported())throw new x(ie.UNSUPPORTED);ne.init()})}function is(n){return o(this,arguments,function*(a,e=[ce.AUDIO],t="",i=!1,r=!1){let s=[],p=[];if(Array.isArray(a)?s=a.length?a:[]:a&&(s=[a]),s.length&&(p=yield ne.getOkIdsByExternalIds(s),!p.length))throw new x(M.CALLEE_IS_OFFLINE);return ba(p,Ve.USER,e,t,i,r)})}function ba(s){return o(this,arguments,function*(a,e=Ve.USER,t,i="",r=!1,n=!1){if(U.current())throw c.error("There is already active call"),new x(M.FAILED);return new U(ne,Tt(),Ft).onStart(a,e,t,i,r,n)})}function rs(a){return o(this,null,function*(){return Ma(a)})}function Ma(i){return o(this,arguments,function*(a,e=z.USER,t){if(a===U.id())throw new Error("Push has already been processed");return new U(ne,Tt(),Ft).onPush(a,e,t)})}function as(a){return o(this,null,function*(){return a&&(d.authToken=a),ne.authorize()})}function ns(){return o(this,arguments,function*(a=[ce.AUDIO]){return Gt().accept(a)})}function ss(){return o(this,null,function*(){let a=U.current();if(a)return a.decline()})}function os(t){return o(this,arguments,function*(a,e=[ce.AUDIO]){return Da(a,e)})}function Da(a,e,t){return o(this,null,function*(){if(U.current())throw c.error("There is already active call"),new x(M.FAILED);return new U(ne,Tt(),Ft).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function cs(r){return o(this,arguments,function*(a,e=[ce.AUDIO],t,i){if(U.current())throw c.error("There is already active call"),new x(M.FAILED);return t&&(d.anonymToken=t),new U(ne,Tt(),Ft).onJoin({joinLink:a,mediaOptions:e,observedIds:i})})}function ds(){return o(this,null,function*(){let a=U.current();if(a)return a.hangup();U.hangupAfterInit()})}function ps(a,e){return o(this,null,function*(){let t=yield ne.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return Aa(t[0],e)})}function Aa(a,e){return o(this,null,function*(){let t=U.current();t&&(yield t.addParticipant(S.composeUserId(a,z.USER),e))})}function ls(a,e=!1){return o(this,null,function*(){let t=yield ne.getOkIdsByExternalIds([a]);return ka(t[0],e)})}function ka(a,e=!1){return o(this,null,function*(){let t=U.current();t&&(yield t.removeParticipant(S.composeUserId(a,z.USER),e))})}function us(a,e){return o(this,null,function*(){let t=yield C.saveDeviceId(a,e),i=U.current();return t&&i?i.changeDevice(a):Promise.reject()})}function ms(a){return o(this,null,function*(){let e=U.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function hs(a,e=!1){return o(this,null,function*(){let t=U.current();t&&(yield t.setVideoStream(a,e))})}function _s(a){return o(this,null,function*(){let e=U.current();e&&(yield e.toggleLocalVideo(a))})}function gs(a){return o(this,null,function*(){let e=U.current();e&&(yield e.toggleLocalAudio(a))})}function fs(a,e,t){return o(this,null,function*(){let i=U.current();if(i)return i.setLocalResolution(a,e,t)})}function Ss(a){return o(this,null,function*(){let e=U.current();e&&(yield e.changePriorities(a))})}function vs(a){return o(this,null,function*(){let e=U.current();e&&(yield e.changeParticipantState(a))})}function Es(a){return o(this,null,function*(){let e=U.current();e&&(yield e.updateDisplayLayout(a))})}function Ts(a,e,t=!1){return o(this,null,function*(){let i=yield ne.getOkIdsByExternalIds([a]);return Oa(i[0],e,t)})}function Oa(a,e,t=!1){return o(this,null,function*(){let i=U.current();i&&(yield i.grantRoles(S.composeUserId(a,z.USER),e,t))})}function Is(){return o(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield ne.getOkIdsByExternalIds([a]))[0]),wa(i,e,t,he.getDeviceIdx(a))})}function wa(){return o(this,arguments,function*(a=null,e,t=[],i=0){let r=U.current();if(r){let n=a?S.composeParticipantId(a,z.USER,i):null;yield r.muteParticipant(n,e,t)}})}function Cs(a,e=!1){return o(this,null,function*(){let t=yield ne.getOkIdsByExternalIds([a]);return xa(t[0],e,he.getDeviceIdx(a))})}function xa(a,e=!1,t=0){return o(this,null,function*(){let i=U.current();i&&(yield i.pinParticipant(S.composeParticipantId(a,z.USER,t),e))})}function ys(a){return o(this,null,function*(){let e=U.current();e&&(yield e.updateMediaModifiers(a))})}function Ps(a){return o(this,null,function*(){let e=U.current();e&&(yield e.changeOptions(a))})}function Rs(a,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield ne.getOkIdsByExternalIds([e]))[0]),La(a,t)})}function La(a,e=null){return o(this,null,function*(){let t=U.current();if(t){let i=e?S.composeUserId(e,z.USER):null;yield t.chatMessage(a,i)}})}function bs(a=10){return o(this,null,function*(){let e=U.current();if(e)return e.chatHistory(a)})}function Ms(a,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield ne.getOkIdsByExternalIds([e]))[0]),Na(a,t,he.getDeviceIdx(e))})}function Na(a,e=null,t=0){return o(this,null,function*(){let i=U.current();if(i){let r=e?S.composeParticipantId(e,z.USER,t):null;yield i.customData(a,r)}})}function Ds(a="",e=!1){return o(this,null,function*(){return(yield ne.createConversation(S.uuid(),a,e)).join_link})}function As(){return o(this,null,function*(){let a=U.current();return a?a.createJoinLink():Promise.reject()})}function ks(){return o(this,null,function*(){let a=U.current();return a?a.removeJoinLink():Promise.reject()})}function Os(a,e){return o(this,null,function*(){return ne.getAnonymTokenByLink(a,e)})}function ws(a){let e=U.current();e&&e.setVolume(a)}function xs(a){d.forceRelayPolicy=a}function Ls(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return o(this,null,function*(){let n=U.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function Ns(){return o(this,null,function*(){let a=U.current();return a?a.stopStream():Promise.reject()})}function Us(a,e){return o(this,null,function*(){let t=U.current();if(t){let i=yield ne.getOkIdsByExternalIds([a]),r=he.getDeviceIdx(a);return t.recordSetRole(S.composeParticipantId(i[0],z.USER,r),e)}return Promise.reject()})}function Bs(){return o(this,null,function*(){let a=U.current();return a?a.getStreamInfo():Promise.reject()})}function Vs(a){return o(this,null,function*(){let e=U.current();return e?e.addMovie(a):Promise.reject()})}function Fs(a,e,t,i){return o(this,null,function*(){let r=U.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function Gs(a){return o(this,null,function*(){let e=U.current();return e?e.removeMovie(a):Promise.reject()})}function Hs(a){d.statisticsInterval=a;let e=U.current();if(e)return e.updateStatisticsInterval()}function Ws(a){ir.default.disableLog(!a),c.toggle(a)}function js(a,...e){!d.debugLog||c.send(a,"[external]",...e)}function Ks(a){return o(this,null,function*(){let e=U.current();if(e)return e.videoEffect(a)})}function qs(a){return o(this,null,function*(){let e=U.current();e&&(yield e.setAudioStream(a))})}function $s(a=null,e,t=!1){return o(this,null,function*(){return Gt().getWaitingHall(a,e,t)})}function Js(a,e=!1){return o(this,null,function*(){let t=Gt(),i=yield ne.getOkIdsByExternalIds([a]);return t.promoteParticipant(S.composeUserId(i[0],z.USER),e)})}function Ys(a){return o(this,null,function*(){return Gt().getParticipantListChunk(a)})}function zs(a){return o(this,null,function*(){return Gt().getParticipants(a)})}function Gt(){let a=U.current();if(!a)throw new Error("Conversation not found");return a}function Qs(a){return o(this,null,function*(){yield ne.removeHistoryRecords(a)})}function Xs(){return d.sdkVersion}
|