@vkontakte/calls-sdk 2.4.4-dev.9dfe59f.0 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/calls-sdk.cjs.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
- * @vkontakte/calls-sdk v2.4.4-dev.9dfe59f.0
3
- * Fri, 14 Jan 2022 07:40:53 GMT
4
- * https://st.mycdn.me/static/callssdk/2-4-4/doc/
2
+ * @vkontakte/calls-sdk v2.5.1
3
+ * Wed, 19 Jan 2022 08:58:00 GMT
4
+ * https://st.mycdn.me/static/callssdk/2-5-1/doc/
5
5
  */
6
6
 
7
- var ga=Object.create;var mt=Object.defineProperty;var _a=Object.getOwnPropertyDescriptor;var fa=Object.getOwnPropertyNames,Hi=Object.getOwnPropertySymbols,Sa=Object.getPrototypeOf,Gi=Object.prototype.hasOwnProperty,va=Object.prototype.propertyIsEnumerable;var Wi=Math.pow,ji=(a,e,t)=>e in a?mt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,Ki=(a,e)=>{for(var t in e||(e={}))Gi.call(e,t)&&ji(a,t,e[t]);if(Hi)for(var t of Hi(e))va.call(e,t)&&ji(a,t,e[t]);return a};var $i=a=>mt(a,"__esModule",{value:!0});var Ea=(a,e)=>{$i(a);for(var t in e)mt(a,t,{get:e[t],enumerable:!0})},Ta=(a,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fa(e))!Gi.call(a,i)&&i!=="default"&&mt(a,i,{get:()=>e[i],enumerable:!(t=_a(e,i))||t.enumerable});return a},Fe=a=>Ta($i(mt(a!=null?ga(Sa(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(h){r(h)}},s=l=>{try{p(t.throw(l))}catch(h){r(h)}},p=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,s);p((t=t.apply(a,e)).next())});Ea(exports,{Api:()=>bt,BaseApi:()=>Xe,BaseLogger:()=>Ze,BaseSignaling:()=>et,CallDirection:()=>xe,CallType:()=>Me,ChatRoomEventType:()=>At,ConversationOption:()=>Dt,DebugMessageType:()=>Ri,ExternalIdType:()=>qe,FacingMode:()=>vi,FatalError:()=>Z,HangupReason:()=>O,HangupType:()=>b,MediaOption:()=>re,MediaTrackKind:()=>ne,MediaType:()=>_e,MuteState:()=>Ne,ParticipantState:()=>G,ParticipantStatus:()=>q,RecordRole:()=>ta,Signaling:()=>Re,SignalingCommandType:()=>H,SignalingConnectionType:()=>Ae,SignalingNotification:()=>D,UserRole:()=>He,UserType:()=>Q,Utils:()=>v,acceptCall:()=>Rn,addMovie:()=>ns,addParticipant:()=>Dn,addParticipantInternal:()=>oa,apiCall:()=>Cn,authorize:()=>yn,browser:()=>_n,callInternal:()=>aa,callTo:()=>En,captureScreen:()=>wn,changeConversationOptions:()=>Kn,changeDevice:()=>kn,changeParticipantState:()=>Vn,changePriorities:()=>Bn,changeVideoEffect:()=>ls,chatHistory:()=>qn,chatMessage:()=>$n,chatMessageInternal:()=>ua,createJoinLink:()=>zn,customData:()=>Jn,customDataInternal:()=>ma,debug:()=>ds,debugMessage:()=>ps,declineCall:()=>Pn,forceRelayPolicy:()=>es,getAnonymTokenByLink:()=>Xn,getStreamInfo:()=>as,getTokenForAnonym:()=>In,getWaitingHall:()=>ms,grantRoles:()=>Hn,grantRolesInternal:()=>da,hangup:()=>An,init:()=>vn,joinCall:()=>bn,joinCallByLink:()=>Mn,joinCallInternal:()=>sa,muteParticipant:()=>Gn,muteParticipantInternal:()=>pa,pinParticipant:()=>Wn,pinParticipantInternal:()=>la,processPush:()=>Tn,processPushInternal:()=>na,promoteParticipant:()=>hs,recordSetRole:()=>rs,removeHistoryRecords:()=>gs,removeJoinLink:()=>Qn,removeMovie:()=>os,removeParticipant:()=>On,removeParticipantInternal:()=>ca,setApi:()=>ia,setAudioStream:()=>us,setLocalResolution:()=>Un,setLogger:()=>fn,setMediaModifiers:()=>jn,setSignalingFactory:()=>ra,setStatisticsInterval:()=>cs,setVideoEffects:()=>Sn,setVideoStream:()=>xn,setVolume:()=>Zn,startConversation:()=>Yn,startStream:()=>ts,stopStream:()=>is,toggleLocalAudio:()=>Ln,toggleLocalVideo:()=>Nn,updateDisplayLayout:()=>Fn,updateMovie:()=>ss});var Li=Fe(require("webrtc-adapter"));var Xe=class{createJoinLink(e){return o(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return o(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return o(this,null,function*(){return""})}log(e){}prepareUserIds(e){return o(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return o(this,null,function*(){})}cleanup(){}getTokenForAnonym(e,t){return o(this,null,function*(){return""})}call(i){return o(this,arguments,function*(e,t={}){return null})}};var Ze=class{log(e,t,i=!1){}destroy(){}};var z=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var et=class extends z{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var qi=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(qi||{}),xe=qi;var Ji=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(Ji||{}),Me=Ji;var Yi=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(Yi||{}),At=Yi;var zi=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(zi||{}),Qi=zi;var Xi=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(Xi||{}),Dt=Xi;function Zi(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function er(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 tr=(L=>(L.CAMERA_PERMISSION="camera",L.MIC_PERMISSION="mic",L.CAMERA_ACCESS="cameralock",L.MIC_ACCESS="miclock",L.MIC_NOT_FOUND="nomic",L.SCREEN_PERMISSION="screenpermission",L.SCREEN_ACCESS="screenlock",L.CONNECTION="connection",L.NETWORK="network",L.UNKNOWN="unknown",L.UNSUPPORTED="unsupported",L.SIGNALING_FAILED="signalingfailed",L.API="api",L.AUTH="auth",L))(tr||{}),Z=tr;var ir=(W=>(W.CANCELED="CANCELED",W.REJECTED="REJECTED",W.REMOVED="REMOVED",W.HUNGUP="HUNGUP",W.MISSED="MISSED",W.BUSY="BUSY",W.FAILED="FAILED",W.NETWORK_ERROR="NETWORK_ERROR",W.KILLED="KILLED",W.BANNED="BANNED",W.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",W.NOT_FRIENDS="NOT_FRIENDS",W.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",W.UNKNOWN_ERROR="UNKNOWN_ERROR",W.UNSUPPORTED="UNSUPPORTED",W.OLD_VERSION="OLD_VERSION",W.SERVICE_DISABLED="SERVICE_DISABLED",W.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",W.SOCKET_CLOSED="SOCKET_CLOSED",W.ENDED="ENDED",W))(ir||{}),b=ir;var rr=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(rr||{}),re=rr;var ar=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(ar||{}),Ne=ar;var nr=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(nr||{}),G=nr;var sr=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(sr||{}),Ae=sr;var or=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(or||{}),le=or;var cr=(k=>(k.TRANSMITTED_DATA="transmitted-data",k.ACCEPTED_CALL="accepted-call",k.HUNGUP="hungup",k.PARTICIPANT_ADDED="participant-added",k.PARTICIPANT_JOINED="participant-joined",k.CLOSED_CONVERSATION="closed-conversation",k.MEDIA_SETTINGS_CHANGED="media-settings-changed",k.PARTICIPANT_STATE_CHANGED="participant-state-changed",k.RATE_CALL_DATA="rate-call-data",k.FEATURE_SET_CHANGED="feature-set-changed",k.TOPOLOGY_CHANGED="topology-changed",k.PRODUCER_UPDATED="producer-updated",k.CONSUMER_ANSWERED="consumer-answered",k.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",k.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",k.SETTINGS_UPDATE="settings-update",k.VIDEO_QUALITY_UPDATE="video-quality-update",k.REGISTERED_PEER="registered-peer",k.SWITCH_MICRO="switch-micro",k.RECORD_STARTED="record-started",k.RECORD_STOPPED="record-stopped",k.REALLOC_CON="realloc-con",k.AUDIO_ACTIVITY="audio-activity",k.SPEAKER_CHANGED="speaker-changed",k.STALLED_ACTIVITY="stalled-activity",k.CHAT_MESSAGE="chat-message",k.CUSTOM_DATA="custom-data",k.ROLES_CHANGED="roles-changed",k.MUTE_PARTICIPANT="mute-participant",k.PIN_PARTICIPANT="pin-participant",k.OPTIONS_CHANGED="options-changed",k.NETWORK_STATUS="network-status",k.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",k.PROMOTE_PARTICIPANT="promote-participant",k.CHAT_ROOM_UPDATED="chat-room-updated",k.PROMOTION_APPROVED="promotion-approved",k.JOIN_LINK_CHANGED="join-link-changed",k))(cr||{}),D=cr;var dr=(u=>(u.ERROR="callError",u.DEVICES="callDevices",u.CALL_SPEC_ERROR="callSpecError",u.ICE_CONNECTION_STATE="callIceConnectionState",u.ICE_CONNECTION_TYPE="callIceConnectionType",u.ICE_RESTART="callIceRestart",u.PUSH="callPush",u.OUTGOING_CALL="callStart",u.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",u.JOIN_CONVERSATION="callJoinConversation",u.ACCEPTED_OUTGOING="callAcceptedOutgoing",u.ACCEPT_INCOMING="callAcceptIncoming",u.DECLINE_INCOMING="callDeclineIncoming",u.ACCEPT_CONCURRENT="callAcceptConcurrent",u.HANGUP="callHangup",u.MEDIA_STATUS="callMediaStatus",u.DEVICE_CHANGED="callDeviceChanged",u.SOCKET_ACTION="callSocketAction",u.ADD_PARTICIPANT="callAddParticipant",u.REMOVE_PARTICIPANT="callRemoveParticipant",u.POOR_CONNECTION="callPoorConnection",u.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",u.RELAY_POLICY="callForceRelay",u.PAT_ALLOCATED="patAllocate",u.PAT_DEALLOCATED="patDeallocate",u.PAT_ERROR="patError",u.PAT_WAITING_TIME_ERROR="patWaitingTimeError",u.PAT_OUTDATED_RESPONSE="patOutdatedResponse",u))(dr||{}),_=dr;var pr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(pr||{}),Ce=pr;var lr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(lr||{}),ur=lr;function mr(a){switch(a){case 1:return"no-available-tracks";default:return"unknown-error"}}var hr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(hr||{}),He=hr;function ht(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var gr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(gr||{}),Q=gr;var Zt=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 _r=2*1024*1024,Ia=512*1024,gt=100*1024,Ca=5,ei="_okcls_logs_session_",ya=3e4,fr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=_r;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(ei)!==0)continue;let i=e.getItem(t);if(!i){Er(t);continue}let r=vr(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(gt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(ei,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Er(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>_r||this.length>Ca-1||this.size+e>this.available);)this.deleteOldestItem()}};function Sr(){return`${ei}${Date.now()}`}function vr(a){return new Blob([a]).size}function Er(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function ti(){let a=Ge.toString();if(!he.available||!a)return;let e=vr(a);he.cleanup(e);try{window.localStorage.setItem(Ot,a)}catch(t){if(console.warn("Failed to write log to storage",t),he.storageSize=he.size+e,he.cleanup(gt+e),he.available>=gt+e){ti();return}if(e>gt){Ge.bisect(),ti();return}he.storageSize=0;return}e>Ia&&(he.add(Ot,e),Ot=Sr(),Ge.clear(),he.cleanup(gt))}function ii(){!he.available||!Ge.length||ti()}function Ra(a=!1){let e=[];try{let r=window.localStorage;for(let s of he.items){let p=r.getItem(s.key);e.push(p)}let n=Ge.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 Pa(t,i),i}function Pa(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 Tr(a,e){!he.available||(Ge.push({t:Date.now(),l:a,d:e}),ai||(ai=window.setTimeout(()=>{ai=null,ii()},ya)))}function ri(){he||(he=new fr,Ge=new Zt,Ot=Sr(),window.addEventListener("beforeunload",ii))}var he,Ge,Ot,ai=null;window.__VKCallsSDKLogs__=(a=!1)=>(he||ri(),ii(),Ra(a));var ni=Fe(require("@vkontakte/libvpx"));var ue=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(ue||{});var m=class extends Ze{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:{},uid:this._api.getUserId()};typeof t!="undefined"&&(r.custom.param=t),this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch(),this._externalLogger&&this._externalLogger.log(e,t,i)}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){m._instance||(m._instance=new m(e,t))}static log(e,t,i=!1){m._instance&&m._instance.log(e,t,i)}static destroy(){m._instance&&m._instance.destroy(),m._instance=null}};var De=class{constructor(){this._worker=null}_createWorker(s,p){return o(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((l,h)=>{let P=i.join(","),A=new Blob([e,`exports.default(${P});`],{type:"application/javascript; charset=utf-8"}),$=window.URL.createObjectURL(A);this._worker=new Worker($),this._worker.onmessage=j=>{switch(j.data.type){case ue.READY:l();break;case ue.ERROR:h(j.data.error);break;case ue.FRAME:t(j.data);break;case ue.DEBUG:c.debug(j.data.message);break;case ue.LOG_ERROR:m.log(_.ERROR,j.data.message);break}},this._sendToWorker(ue.INIT,r,n)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var tt=class extends De{init(e){return o(this,null,function*(){c.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var y=Object.defineProperty;var E=a=>y(a,"__esModule",{value:!0});var M=(a,p)=>{E(a);for(var e in p)y(a,e,{get:p[e],enumerable:!0})};var D={};M(D,{default:()=>V});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var V=(a,p)=>{let e=null,n=null,g=!0;function b(){return a({locateFile:p}).then(r=>n=r)}function s(r,m,l,R,x){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(x),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let d=e.getImageBuffer();if(!d){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let c=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(d.byteLength);if(i.set(d),R){let o=new ImageData(i,c,f);createImageBitmap(o,0,0,c,f).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:i.buffer,width:c,height:f},[i.buffer])}b().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return D;})();\n',t=>{if(t.error)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(ue.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:n,debug:c.enabled()},[t.buffer])}destroy(){this._removeWorker(),c.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var We=class extends De{init(e){return o(this,null,function*(){c.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var i=Object.defineProperty;var f=e=>i(e,"__esModule",{value:!0});var E=(e,d)=>{f(e);for(var a in d)i(e,a,{get:d[a],enumerable:!0})};var g={};E(g,{default:()=>V});var s=(a=>(a.VP9="vp09.00.50.08",a.VP8="vp8",a))(s||{}),o=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(o||{});var V=()=>{let e=null,d=!0;function a(){self.postMessage({type:o.READY})}function l(r,p,t,m=!1){(!e||d!==t)&&(d=t,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${t?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${t?"VP9":"VP8"}`}),e=new VideoDecoder({output:c=>{("createImageBitmap"in c?c.createImageBitmap():createImageBitmap(c)).then(n=>{self.postMessage({type:o.FRAME,data:n}),n.close()}).finally(()=>c.close())},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:t?s.VP9:s.VP8}));let u=new EncodedVideoChunk({type:m?"key":"delta",timestamp:r,data:p});e.decode(u)}self.onmessage=r=>{switch(r.data.type){case o.INIT:a();break;case o.FRAME:l(r.data.timestamp,r.data.data,r.data.isVP9,r.data.keyFrame);break}}};return g;})();\n',t=>{t.error?c.warn("WebCodecsDecoder",t.error):e(t.data)})})}decodeFrame(e,t,i,r=!1){this._sendToWorker(ue.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),c.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window&&"ImageBitmap"in window&&"createImageBitmap"in window}};var si="_okcls_",it=(()=>{try{let a=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(a,a),t=e.getItem(a)===a,e.removeItem(a),t?e:null}catch(a){return null}})();function Ma(a){let e=it?it.getItem(si+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function Aa(a,e){try{it&&it.setItem(si+a,JSON.stringify(e))}catch(t){}}function Da(a){it&&it.removeItem(si+a)}var oi;(i=>{function a(r){return Ma(r)||null}i.get=a;function e(r,n){Aa(r,n)}i.set=e;function t(r){Da(r)}i.remove=t})(oi||(oi={}));var Ue=oi;var rt=Fe(require("big-integer"));function Ir(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 Cr=a=>a.stop(),yr=a=>a.getTracks().forEach(Cr),ci=a=>a.getVideoTracks().forEach(Cr),Rr=a=>a.getVideoTracks()[0].clone();var O=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(b).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,O)}};var fe=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(fe||{}),ne=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(ne||{}),di=class extends z{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=[re.AUDIO]){if(this._stream)return;let t=e.includes(re.VIDEO),i=e.includes(re.AUDIO);if(!y.isBrowserSupported())throw new O(Z.UNSUPPORTED);try{this._stream=yield y.getUserMedia(t,i),this._mediaSettings.isVideoEnabled=t&&this._stream.getVideoTracks().filter(r=>r.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=i&&this._stream.getAudioTracks().filter(r=>r.enabled).length>0||!1}catch(r){throw new O(r)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t=!1){let i=this.getStream(),r=this._getSendAudioTrack(),n=this.getSendVideoTrack(t);if(!i||!r&&!n)throw new Error("No local stream found");r&&e.addTrack(r,i),n&&e.addTrack(n,i)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return o(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return o(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=v.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);navigator.mediaDevices.addEventListener("devicechange",()=>o(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),s=n&&n.groupId,p=this._stream.getVideoTracks()[0],l=p&&p.enabled&&p.getSettings(),h=l&&l.groupId;if(!s&&!h)return;let P=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!P.find(A=>A.groupId===s)),!t&&h&&(t=!P.find(A=>A.groupId===h)),i()}))}_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{d.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),n=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),m.log(_.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(_.ERROR,"change_video"),c.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=Rr(e)),t=this._trackVideoStreamBackup.clone(),ci(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),ci(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(_.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(_.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=d.consumerScreenTrack?t:yield this._videoEffect(null,t);m.log(_.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?y.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 m.log(_.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 m.log(_.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(){d.videoEffects&&(this._effect=null,d.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():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 y.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=y.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("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(!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 at=":",kt="d",pi;(zt=>{function a(u,I,M,V,f=!1){let J=/[\r\n]+/,R=`\r
8
- `;if(!I&&!M&&!V)return f?K(u.split(J)).join(R):u;function K(Y){let be=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],oe="a=rtcp-fb:111",g=Y.findIndex(C=>C.startsWith(oe));return~g&&(Y[g]=Y[g]+R+be.join(R)),Y}function te(Y,be,oe){let g=Y.split(" "),C=g.slice(0,3),F;for(F=3;F<g.length;F++)oe.includes(g[F])&&C.push(g[F]);for(F=3;F<g.length;F++)!oe.includes(g[F])&&!be.includes(g[F])&&C.push(g[F]);return C.join(" ")}function k(Y,be){let oe=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),g,C=[];for(g=0;g<Y.length;++g){let F=Y[g].match(oe);F&&F.length===3&&F[2]===be&&C.push(F[1])}return C}function ge(Y,be,oe,g){let C,F="m="+be;for(C=0;C<Y.length;++C)if(Y[C].startsWith(F)){Y[C]=te(Y[C],oe,g);break}}let Le=[],ie=u.split(J);(M||I)&&(Le=k(ie,"H264"));let we=[];if(V&&(we=k(ie,"VP9")),M){let Y=Le.slice(0),be=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),oe;for(oe=0;oe<ie.length;++oe){let C=ie[oe].match(be);C&&C.length===3&&Y.includes(C[2])&&Y.push(C[1])}let g=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(oe=ie.length;oe--;){let C=ie[oe].match(g);C&&C.length===3&&Y.includes(C[2])&&ie.splice(oe,1)}ge(ie,"video",Y,[])}else I&&ge(ie,"video",[],Le);return V&&ge(ie,"video",[],we),f&&K(ie),ie.join(R)}zt.patchSDP=a;function e(u){return u?`${u.type||"WEB_SOCKET"}_${u.id}`:"_"}zt.getPeerIdString=e;function t(u,I){return u&&u.id===I.id&&(u.type||"WEB_SOCKET")===(I.type||"WEB_SOCKET")}zt.comparePeerId=t;function i(u){return o(this,null,function*(){return!u||!u.getStats?Promise.resolve(null):u.getStats(null).then(I=>{let M=null,V=null;if(I.forEach(f=>{f.type==="transport"&&f.selectedCandidatePairId?V=I.get(f.selectedCandidatePairId):f.type==="candidate-pair"&&f.state==="succeeded"&&!V&&(!f.hasOwnProperty("selected")||f.selected)&&(V=f)}),V&&V.localCandidateId){let f=I.get(V.localCandidateId);f&&(M={type:f.candidateType,ip:f.ip||f.ipAddress,port:f.port||f.portNumber})}return M}).catch(()=>null)})}zt.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function s(u,I){let M=String(u);return n.test(M)?(c.warn(`Already composite id [${u}] type supplied [${I}]`),M):I===Q.GROUP?"g"+M:I===Q.USER?"u"+M:(c.warn(`Unknown type [${I}] for id [${u}]`),M.match(r)?"u"+M:M)}zt.composeUserId=s;function p(u,I,M){let V=s(u,I);return l(V,M)}zt.composeParticipantId=p;function l(u,I){return I?u+at+kt+I:u}zt.compose=l;function h(u){return p(u.id,u.idType||Q.USER,u.deviceIdx||0)}zt.composeId=h;function P(u){return u.participant?h(u.participant):p(u.participantId,u.participantType||Q.USER,u.deviceIdx||0)}zt.composeMessageId=P;function A(u){let I=String(u),M=I.match(n);return M?{id:Number(M[2]),type:M[1]==="g"?Q.GROUP:Q.USER}:(c.warn(`Unsupported compositeId [${u}]`),{id:Number(I),type:Q.USER})}zt.decomposeId=A;function $(u){let I=u.split(at+kt);return{compositeUserId:I[0],deviceIdx:I.length>1?parseInt(I[1],10):0}}zt.decomposeParticipantId=$;function j(){let u="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),I=new Array(36),M=0,V,f;for(f=0;f<36;f++)f===8||f===13||f===18||f===23?I[f]="-":f===14?I[f]="4":(M<=2&&(M=33554432+Math.random()*16777216|0),V=M&15,M=M>>4,I[f]=u[f===19?V&3|8:V]);return I.join("")}zt.uuid=j;function L(u,I){let M;function V(){let f=this,J=arguments;M&&window.clearTimeout(M),M=window.setTimeout(()=>{u.apply(f,J)},I)}return V}zt.throttle=L;function pe(u){let I="",M=u.split(`
9
- `);for(let R of M)if(R.startsWith("a=fingerprint")){let K=R.split(" ");if(K.length===2){I=K[1];break}}if(!I)return rt.default.minusOne;let V=I.split(":"),f=rt.default.zero;for(let R=Math.min(7,V.length-1);R>=0;R--){let K=(0,rt.default)(V[R],16);f=f.shiftLeft(8).or(K)}return((R,K)=>{let te=K.value;if(typeof te=="bigint")return(0,rt.default)(BigInt.asIntN(R,te));let k=rt.default.one.shiftLeft(R),ge=K.and(k.subtract(1));return ge.greaterOrEquals(k.subtract(ge))?ge.subtract(k):ge})(64,f)}zt.sdpFingerprint=pe;function Pe(u){return o(this,null,function*(){return new Promise(I=>window.setTimeout(I,u))})}zt.delay=Pe;function se(u,I,M){let V=[];return u.getSenders().forEach(f=>Ve(I,f,f.track,M,V)),V}zt.applySettings=se;function Ve(u,I,M,V,f){if(u&&M&&M.kind===ne.video){let J=M.getSettings();if(J){let R=u.maxBitrateK?u.maxBitrateK*1024:null,K=J.width,te=J.height,k=K&&te&&u.maxDimension?Math.max(1,Math.max(K,te)/u.maxDimension):null,ge=u.maxFramerate?u.maxFramerate:null,Le=u.degradationPreference?u.degradationPreference:"balanced",ie=V[M.id];if(ie&&ie.bitrate===R&&ie.scaleResolutionDownBy===k&&ie.maxFramerate===ge&&ie.degradationPreference===Le){f[M.id]=ie;return}f[M.id]={bitrate:R,scaleResolutionDownBy:k,maxFramerate:ge,degradationPreference:Le};let we=I.getParameters();we.encodings||(we.encodings=[{}]),we.encodings.forEach(Y=>{R?Y.maxBitrate=R:delete Y.maxBitrate,k?Y.scaleResolutionDownBy=k:delete Y.scaleResolutionDownBy,ge?Y.maxFramerate=ge:delete Y.maxFramerate}),we.degradationPreference=Le,I.setParameters(we)}}}zt.applyVideoTrackSettings=Ve;function ae(u,I){Array.isArray(I)||(I=[I]);for(let M of I)if(u.includes(M))return!0;return!1}zt.includesOneOf=ae;function W(u){var I;return Object.entries(((I=u.participantState)==null?void 0:I.state)||{}).reduce((M,[V,f])=>(u.participantState&&(M[V]={ts:u.participantState.stateUpdateTs[V],state:f}),M),{})}zt.mapParticipantState=W;function Ie(u){return Object.entries(u).reduce((I,[M,{state:V}])=>(I[M]=V,I),{})}zt.mapLegacyParticipantState=Ie;function lt(u){return u.map(I=>{let M={uid:I.externalId,mediaSettings:I.mediaSettings,status:I.status,muteStates:I.muteStates,unmuteOptions:I.unmuteOptions};return d.participantStateMapped&&(M.participantState=I.participantState),M})}zt.mapSharedParticipants=lt;function Ui(u,I){let M=Object.keys(u),V=Object.keys(I);if(M.length!==V.length)return!1;for(let f of M)if(!V.hasOwnProperty(f)||u[f].state!==I[f].state||u[f].ts!==I[f].ts)return!1;return!0}zt.isEqualParticipantState=Ui;function Bi(u,I){let M=Object.keys(u),V=Object.keys(I);if(M.length!==V.length)return!1;for(let f of M)if(!I.hasOwnProperty(f)||u[f]!==I[f])return!1;return!0}zt.isObjectsEquals=Bi;function Vi(u,I){if(u.length!==I.length)return!1;for(let M of u)if(I.indexOf(M)<0)return!1;return!0}zt.isArraysEquals=Vi;function Fi(u){return!Object.keys(u).length}zt.isEmptyObject=Fi})(pi||(pi={}));var v=pi;var je=null,li=null,wt=[],xt=[],ui=[],_t=null,ft=null,mi=null,hi=!1,gi=!1,Nt,nt,Lt,Pr=!1,br=!1,_i=null,fi="",Ut=[],Si=null,Mr=navigator.appVersion,Oa=navigator.appName,Se=navigator.userAgent,vi=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(vi||{}),St=class{constructor(e,t=!1,i=d.videoMaxWidth,r=d.videoMaxHeight){let n=!1;if(e){n={noiseSuppression:d.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let p;ft&&(p=ft.deviceId),typeof e=="string"&&(p=e),p&&(n.deviceId={exact: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;_t&&(p=_t.deviceId),typeof t=="string"&&(p=t),p&&(s.deviceId={exact:p}),d.videoFacingMode&&(s.facingMode={exact: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}},Ar=class extends St{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=d.screenFrameRate}};function ka(){return o(this,null,function*(){je=null,yield Bt()})}function wa(){je=null,Bt().then(()=>T.onDeviceChange())}function Bt(){return o(this,null,function*(){return je||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!li&&navigator.mediaDevices.addEventListener&&(li=v.throttle(wa,1e3),navigator.mediaDevices.addEventListener("devicechange",li)),je=navigator.mediaDevices.enumerateDevices().then(a=>{wt=a.filter(r=>r.kind==="videoinput"?(r.label&&(hi=!0),!0):!1),xt=a.filter(r=>r.kind==="audioinput"?(r.label?gi=!0:Ke.isMobile()&&Ke.browserName()==="Firefox"&&(gi=hi),!0):!1),ui=a.filter(r=>r.kind==="audiooutput");let e=Ue.get("videoinput"),t=Ue.get("audioinput"),i=Ue.get("audiooutput");return _t=wt.find(r=>r.deviceId===e)||null,ft=xt.find(r=>r.deviceId===t)||null,mi=ui.find(r=>r.deviceId===i)||null,je=Promise.resolve(a),a}).catch(()=>(je=null,[]))))})}function xa(){return o(this,null,function*(){return Ke.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(Pr=!0),/^a=mid:0$/m.test(t.sdp)&&(br=!0),a()}).catch(a)}):Promise.resolve()})}function Vt(a,e){return o(this,null,function*(){c.debug("Try to get media",a.getNative());let t=Ke.hasPermissions(a.isVideo());!t&&!e&&T.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield ka()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?Z.CAMERA_PERMISSION:Z.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?Z.CAMERA_ACCESS:Z.MIC_ACCESS;break}if(a.canSimplify())return Vt(a.simplify(),e);let r=e||Z.UNKNOWN;throw T.onPermissionsError(r),r}})}function Na(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 Z.SCREEN_PERMISSION;default:throw Z.SCREEN_ACCESS}}})}function Ei(){return Ut.length||(Ut=(()=>{let a,e=!1,t=0,i=Se.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return a=/\brv[ :]+(\d+)/g.exec(Se),["IE",a&&a[1]||"Unknown",e,t];if(i[1]==="Safari"){if(a=Se.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(a=Se.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,a[1]];if(a=Se.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t];if(a=Se.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t];if(a=Se.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),a=Se.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t];if(a=Se.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t];if(a=Se.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t];if(a=Se.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t]}return a=Se.match(/version\/(\d+)/i),[i[2]?i[1]:Oa,a&&a[1]||i[2]||Mr,e,t]})()),Ut}var Ke;(V=>{function a(){return o(this,null,function*(){return yield xa(),Bt()})}V.init=a;function e(){return wt}V.getCameras=e;function t(){return xt}V.getMicrophones=t;function i(){return ui}V.getOutput=i;function r(){return wt.length>0}V.hasCamera=r;function n(){return xt.length>0}V.hasMicrophone=n;function s(){return _t}V.getSavedCamera=s;function p(){return ft}V.getSavedMicrophone=p;function l(){return mi}V.getSavedOutput=l;function h(){return hi}V.hasCameraPermission=h;function P(){return gi}V.hasMicrophonePermission=P;function A(f=!1){return P()?r()&&f?h():!0:!1}V.hasPermissions=A;function $(f=!1,J=!0){return o(this,null,function*(){let R=n()&&J,K=r()&&f,te;if(!R&&!K)te=new MediaStream;else try{te=yield Vt(new St(R,K))}catch(k){te=new MediaStream}return te.getVideoTracks().length||te.addTrack(Ve()),te.getAudioTracks().length||te.addTrack(se()),te})}V.getUserMedia=$;function j(){return o(this,null,function*(){return Na(new Ar(window.screen.width,window.screen.height))})}V.getScreenMedia=j;function L(f,J=!1){return o(this,null,function*(){let R=J?d.videoEffectMaxWidth:d.videoMaxWidth,K=J?d.videoEffectMaxHeight:d.videoMaxHeight;return Vt(new St(!1,f||!0,R,K))})}V.getUserVideo=L;function pe(f){return o(this,null,function*(){return Vt(new St(f||!0,!1))})}V.getUserAudio=pe;function Pe(f,J){return o(this,null,function*(){let K=(yield Bt()).find(te=>te.kind===f&&te.deviceId===J);return K?(f==="videoinput"?_t=K:f==="audioinput"?ft=K:f==="audiooutput"&&(mi=K),Ue.set(f,J),K):null})}V.saveDeviceId=Pe;function se(){if(!Lt||Lt.readyState==="ended"){let f=M(),J=f.createMediaStreamDestination(),R=f.createGain();R.gain.value=1e-5,R.connect(J),R.connect(f.destination);let K=f.createOscillator();K.type="sine",K.frequency.value=0,K.connect(R),K.start(),Lt=J.stream.getAudioTracks()[0]}return Object.assign(Lt.clone(),{enabled:!1})}V.getSilentMediaTrack=se;function Ve(f=d.videoMinWidth,J=d.videoMinHeight){return nt||(nt=document.createElement("canvas"),nt.getContext("2d")),nt.width=f,nt.height=J,(!Nt||Nt.readyState==="ended")&&(Nt=nt.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(Nt.clone(),{enabled:!1})}V.getBlackMediaTrack=Ve;function ae(){if(zt()==="Edge"&&u()<70)return!1;try{let f=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&f.RTCPeerConnection&&f.RTCIceCandidate&&f.RTCSessionDescription&&f.HTMLCanvasElement&&f.HTMLCanvasElement.prototype.captureStream&&f.RTCRtpSender&&f.RTCRtpSender.prototype.replaceTrack&&f.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(f){return!1}}V.isBrowserSupported=ae;function W(){return!!navigator.mediaDevices.getDisplayMedia}V.isScreenCapturingSupported=W;function Ie(){return Pr}V.canVP8=Ie;function lt(){return br}V.isUnifiedPlan=lt;function Ui(){return V.browserName()==="Opera"&&V.os()==="Windows"}V.isBrokenH264=Ui;function Bi(){return!(V.baseChromeVersion()&&V.isMobile())}V.canPreferH264=Bi;function Vi(){return fi||(fi=(()=>{let f={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 J in f)if(f.hasOwnProperty(J)&&f[J].test(Se))return J;return"Unknown"})()),fi}V.os=Vi;function Fi(){return _i===null&&(_i=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Mr)),_i}V.isMobile=Fi;function zt(){return Ei()[0]}V.browserName=zt;function u(){return Ei()[1]}V.browserVersion=u;function I(){return Ei()[3]}V.baseChromeVersion=I;function M(){return Si||(Si=new(window.AudioContext||window.webkitAudioContext)),Si}V.getAudioContext=M})(Ke||(Ke={}));var y=Ke;var Dr=Fe(require("bit-buffer"));var La=65536,$e=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)%La!==e.sequence){c.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:n}=$e.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 Dr.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 vt=class extends $e{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;c.debug(`StreamBuilder started for participant [${e}]`),this._useImageBitmap="ImageBitmap"in window,We.isBrowserSupported()?this._decoder=new We:this._decoder=new tt,this._decoder.init(i=>this._drawImage(i)).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}_drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._removeStream(),c.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(y.browserName()==="Safari"&&y.browserVersion()>=15)}};var Ft=1,Ua=1,Or=0,kr=11,wr=1,xr=2,Nr=4,Lr=8;function Ur(a,e,t,i,r,n,s){let p=0;e&&(p|=wr),t&&(p|=xr),i&&(p|=Nr),s||(p|=Lr);let l=new ArrayBuffer(kr),h=new DataView(l);if(h.setUint8(0,Ft),h.setUint16(1,r),h.setUint32(3,a),h.setUint8(7,n?1:0),h.setUint16(8,Or),h.setUint8(10,p),!s)return l;let P=new Uint8Array(l.byteLength+s.byteLength);return P.set(new Uint8Array(l),0),P.set(new Uint8Array(s),l.byteLength),P.buffer}function Br(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&wr),h=!!(p&xr),P=!!(p&Nr),A=!!(p&Lr);if(t!==Ft)throw new Error(`Unexpected protocol version. Got ${t}, expected ${Ft}`);return{timestamp:r,start:l,end:h,keyframe:P,sequence:i,isVP9:n,ssrc:s,eos:A,data:a.slice(kr)}}function Vr(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==Ft||e.getUint8(1)!==Ua||e.getUint16(2)!==Or)}var S=Fe(require("simple-ebml-builder"));var Ba=Wi(2,15)-1,Ti=1,Va=5,Fa=5;var Ht=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),c.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=Ht._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return S.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=S.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;let e=(n=this._sourceBuffer)==null?void 0:n.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-Va);r-i>Fa&&(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}},ye=class extends $e{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 S.element(S.ID.EBML,[S.element(S.ID.EBMLVersion,S.number(1)),S.element(S.ID.EBMLReadVersion,S.number(1)),S.element(S.ID.EBMLMaxIDLength,S.number(4)),S.element(S.ID.EBMLMaxSizeLength,S.number(8)),S.element(S.ID.DocType,S.string("webm")),S.element(S.ID.DocTypeVersion,S.number(2)),S.element(S.ID.DocTypeReadVersion,S.number(2))])}static _genSegmentHeader(e,t,i){let r=S.element(S.ID.Info,[S.element(S.ID.TimecodeScale,S.number(1e6)),S.element(S.ID.MuxingApp,S.string("vk-webm-builder")),S.element(S.ID.WritingApp,S.string("vk-webm-builder"))]),n=[S.element(S.ID.PixelWidth,S.number(e)),S.element(S.ID.PixelHeight,S.number(t))],s=S.element(S.ID.Tracks,S.element(S.ID.TrackEntry,[S.element(S.ID.TrackNumber,S.number(Ti)),S.element(S.ID.TrackUID,S.number(Ti)),S.element(S.ID.TrackType,S.number(1)),S.element(S.ID.FlagLacing,S.number(0)),S.element(S.ID.DefaultDuration,S.number(1e9)),S.element(S.ID.CodecID,S.string(`V_${i.toUpperCase()}`)),S.element(S.ID.Video,n)]));return S.unknownSizeElement(S.ID.Segment,[r,s])}static _genClusterHeader(e){return S.unknownSizeElement(S.ID.Cluster,[S.element(S.ID.Timecode,S.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new Ht(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){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,c.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=ye._genWebmHeader();this._mediaBuffer.append(s);let p=ye._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(p),this._mediaBuffer.cleanup()}let r=Math.round(i-this._clusterStartTime);if(r>Ba&&(this._clusterStartTime=i,r=0),r===0){c.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=ye._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let n=S.element(S.ID.SimpleBlock,[S.vintEncodedNumber(Ti),S.bytes(ye._intToU16BE(r)),S.number((e.keyframe?1:0)<<7),S.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=Br(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&&ye.isBrowserSupported()?r=new ye(i,p):r=new vt(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(We.isBrowserSupported()||tt.isBrowserSupported())&&(vt.isBrowserSupported()||ye.isBrowserSupported())}};var Ii=Fe(require("@vkontakte/libvpx"));var Ha=1e3,Et=class extends De{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");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})},[Ii.default,Ii.default.getUrl],{isVP9:this.isVP9(),debug:c.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(ue.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},Ha),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),c.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var ot=class extends De{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 b=Object.defineProperty;var g=i=>b(i,"__esModule",{value:!0});var F=(i,n)=>{g(i);for(var r in n)b(i,r,{get:n[r],enumerable:!0})};var A={};F(A,{default:()=>h});var l=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(l||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,n,r,c,s,f,t,a=null,p=0,u=!1;function V(e){n=e.readable,r=n.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&E(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),n.cancel();return}a=R,E(R,e)}}))}function E(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
11
- `,r=>{var n;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(n=r.data)==null?void 0:n.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:d.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(ue.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),c.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var Ga=16*1024,Wa=11,Fr=Ga-Wa,ja=65536,Ci=0,ct=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;c.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,n)=>{if(!this._destroyed){if(!r){c.warn("requestFrame failed, keyFrame: "+this._needKeyframe,n),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{c.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};ot.isBrowserSupported()?this._encoder=new ot(e,i):this._encoder=new Et(e,i),this._datachannel.onmessage=r=>{Vr(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=Ur(e,t,i,r,Ci,this._encoder.isVP9(),n);return Ci=(Ci+1)%ja,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+Fr),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+Fr,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),c.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return ot.isBrowserSupported()||Et.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 E=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(E._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(E._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(E._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(X.accessToken=e.apiAuth.accessToken,X.sessionKey=e.apiAuth.sessionKey,X.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(E._params,e)}static get(e){return E._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.4.4-dev.9dfe59f.0"}static get debug(){return!1}static get protocolVersion(){return E._params.joinFromMultipleDevices?6:5}static get platform(){return E._params.platform}static set platform(e){E._params.platform=e}static get clientType(){return E._params.clientType}static set clientType(e){E._params.clientType=e}static get device(){return E._params.device}static get apiAppId(){return 42}static get apiKey(){return E._params.apiKey}static get apiEnv(){switch(E._params.apiEnv){case"TEST":return{api:"https://apitest.ok.ru/api/",connect:"https://test.ok.ru/"};case"VIDEOTEST":return{api:"https://videotestapi.ok.ru/api/",connect:"https://test.ok.ru/"};case"DEV":return{api:"https://1.api.an-eremeev.devdc.odkl.ru/api/",connect:"https://1.web.an-eremeev.devdc.odkl.ru/"};default:return{api:"https://api.ok.ru/",connect:"https://connect.ok.ru/"}}}static get authToken(){return E._params.authToken}static set authToken(e){E._params.authToken=e}static get anonymToken(){return E._params.anonymToken}static set anonymToken(e){E._params.anonymToken=e}static get domain(){return E._params.domain}static get iceServers(){return E._params.iceServers}static set iceServers(e){E._params.iceServers=e}static get wssBase(){return E._params.wssBase}static set wssBase(e){E._params.wssBase=e}static get wssToken(){return E._params.wssToken}static set wssToken(e){E._params.wssToken=e}static get signalingReconnectDelay(){return E._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return E._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return E._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return E._params.waitConnectionDelay}static get waitResponseDelay(){return E._params.waitResponseDelay}static get waitMessageDelay(){return E._params.waitMessageDelay}static get debugLog(){return E._params.debugLog}static get forceRelayPolicy(){return E._params.forceRelayPolicy}static set forceRelayPolicy(e){E._params.forceRelayPolicy=e}static get videoMinWidth(){return E._params.videoMinWidth}static get videoMaxWidth(){return E._params.videoMaxWidth}static set videoMaxWidth(e){E._params.videoMaxWidth=e}static get videoMinHeight(){return E._params.videoMinHeight}static get videoMaxHeight(){return E._params.videoMaxHeight}static set videoMaxHeight(e){E._params.videoMaxHeight=e}static get videoAspectRatio(){return E._params.videoAspectRatio}static get videoFrameRate(){return E._params.videoFrameRate}static get videoFacingMode(){return E._params.videoFacingMode}static get screenFrameRate(){return E._params.screenFrameRate}static get videoEffects(){return E._params.videoEffects}static set videoEffects(e){E._params.videoEffects=e}static get videoEffectMaxWidth(){return E._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){E._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return E._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){E._params.videoEffectMaxHeight=e}static get voiceParams(){return E._params.voiceParams}static get specListenerParams(){return E._params.specListenerParams}static get iceRestartWaitTime(){return E._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return E._params.transportConnectionWaitTime}static get statisticsInterval(){return E._params.statisticsInterval}static set statisticsInterval(e){E._params.statisticsInterval=e}static get networkStatisticsInterval(){return E._params.networkStatisticsInterval}static get perfStatReportEnabled(){return E._params.perfStatReportEnabled}static get producerNotificationDataChannel(){return E._params.producerNotificationDataChannel&&st.isBrowserSupported()}static get producerCommandDataChannel(){return E._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return E._params.consumerScreenDataChannel&&ct.isBrowserSupported()}static get producerScreenDataChannel(){return E._params.producerScreenDataChannel&&E.producerNotificationDataChannel}static get screenShareWebmBuilder(){return E._params.screenShareWebmBuilder}static get noiseSuppression(){return E._params.noiseSuppression}static set noiseSuppression(e){E._params.noiseSuppression=e}static get preferH264(){return E._params.preferH264}static get preferVP9(){return E._params.preferVP9}static get audioNack(){return E._params.audioNack}static get consumerScreenTrack(){return E._params.consumerScreenTrack&&E.consumerScreenDataChannel}static get producerScreenTrack(){return E._params.producerScreenTrack&&E.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=E._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return E._params.movieShare&&E.videoTracksCount>0}static get videoTracksCount(){return E.producerNotificationDataChannel?E._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return E._params.breakVideoPayloadTypes}static get filteredMessages(){return E._params.filteredMessages}static get batchParticipantsOnStart(){return E._params.batchParticipantsOnStart}static get participantStateMapped(){return E._params.participantStateMapped}},d=E;d._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"PROD",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!1,producerScreenTrack:!1,videoTracksCount:0,movieShare:!1,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!1,joinFromMultipleDevices:!0};var q=(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))(q||{});function U(a,...e){let t=d.get(a);t&&setTimeout(t,0,...e)}function Oe(a){return Object.assign({},a)}function dt(a){return a.slice()}var yi;(oe=>{function a(g,C){U("onLocalStream",g,Oe(C))}oe.onLocalStream=a;function e(g,C){U("onScreenStream",g,Oe(C))}oe.onScreenStream=e;function t(g,C){U("onLocalStreamUpdate",Oe(g),C)}oe.onLocalStreamUpdate=t;function i(g){U("onLocalStatus",g)}oe.onLocalStatus=i;function r(g,C){U("onRemoteStream",g,C)}oe.onRemoteStream=r;function n(g,C,F){U("onRemoteLive",g,C,F)}oe.onRemoteLive=n;function s(g,C){U("onRemoteScreenStream",g,C)}oe.onRemoteScreenStream=s;function p(g,C,F,ut){U("onConversation",g,Oe(C),Oe(F),ut)}oe.onConversation=p;function l(g,C){U("onRemoteMediaSettings",g,Oe(C))}oe.onRemoteMediaSettings=l;function h(g,C){U("onRemoteParticipantState",g,Oe(C))}oe.onRemoteParticipantState=h;function P(g,C,F=null){U("onRemoteStatus",g,C,F)}oe.onRemoteStatus=P;function A(g,C,F=null){U("onParticipantStatus",g,C,F)}oe.onParticipantStatus=A;function $(){U("onPermissionsRequested")}oe.onPermissionsRequested=$;function j(g){U("onPermissionsError",g)}oe.onPermissionsError=j;function L(g){U("onRemoteRemoved",g)}oe.onRemoteRemoved=L;function pe(g,C,F){U("onCallState",g,C,Oe(F))}oe.onCallState=pe;function Pe(g,C){U("onDeviceSwitched",g,C)}oe.onDeviceSwitched=Pe;function se(g,C,F,ut=!1,Qt=!1,Xt=null,ha=null){U("onMuteStates",Oe(g),dt(C),dt(F),ut,Qt,Xt,ha)}oe.onMuteStates=se;function Ve(g,C){U("onRolesChanged",g,dt(C))}oe.onRolesChanged=Ve;function ae(g){U("onLocalRolesChanged",dt(g))}oe.onLocalRolesChanged=ae;function W(g,C){U("onPinnedParticipant",g,C)}oe.onPinnedParticipant=W;function Ie(g){U("onLocalPin",g)}oe.onLocalPin=Ie;function lt(g){U("onOptionsChanged",dt(g))}oe.onOptionsChanged=lt;function Ui(){U("onCallAccepted")}oe.onCallAccepted=Ui;function Bi(){U("onRateNeeded")}oe.onRateNeeded=Bi;function Vi(g){U("onSpeakerChanged",g)}oe.onSpeakerChanged=Vi;function Fi(g){U("onVolumesDetected",dt(g))}oe.onVolumesDetected=Fi;function zt(g,C){U("onLocalVolume",g,C)}oe.onLocalVolume=zt;function u(g,C){U("onJoinStatus",g,C)}oe.onJoinStatus=u;function I(g,C){U("onHangup",g,C)}oe.onHangup=I;function M(g){U("onMultipartyChatCreated",Oe(g))}oe.onMultipartyChatCreated=M;function V(){U("onDeviceChange")}oe.onDeviceChange=V;function f(g){U("onFingerprintChange",g)}oe.onFingerprintChange=f;function J(){U("onTokenExpired")}oe.onTokenExpired=J;function R(g,C,F=!1){U("onChatMessage",g,C,F)}oe.onChatMessage=R;function K(g,C,F=!1){U("onCustomData",g,C,F)}oe.onCustomData=K;function te(g,C,F,ut,Qt,Xt){U("onRecordStarted",g,C,F,ut,Qt,Xt)}oe.onRecordStarted=te;function k(){U("onRecordStopped")}oe.onRecordStopped=k;function ge(g){U("onLocalNetworkStatusChanged",g)}oe.onLocalNetworkStatusChanged=ge;function Le(g){U("onNetworkStatusChanged",g)}oe.onNetworkStatusChanged=Le;function ie(g,...C){U("onDebugMessage",g,...C)}oe.onDebugMessage=ie;function we(g,C){let F=Object.assign({},g,{memory:C});U("onStatistics",F)}oe.onStatistics=we;function Y(){U("onAutoplayError")}oe.onAutoplayError=Y;function be(g,C,F){U("onChatRoomUpdated",g,C,F)}oe.onChatRoomUpdated=be})(yi||(yi={}));var T=yi;var Ri=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(Ri||{}),Pi;(ae=>{let a="📞",e=(W,...Ie)=>{T.onDebugMessage(W,...Ie)},t=!1,i=(W,Ie)=>(...lt)=>{W(...lt),Tr(Ie,lt)},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"),h=e.bind(null,"LOG"),P=e.bind(null,"WARN"),A=e.bind(null,"ERROR");ae.debug=l,ae.log=h,ae.warn=P,ae.error=A;function Pe(){return t}ae.enabled=Pe;function se(W){t=W,d.debugLog&&ri(),W?(ae.debug=d.debugLog?i(r,"DEBUG"):r,ae.log=d.debugLog?i(n,"LOG"):n,ae.warn=d.debugLog?i(s,"WARN"):s,ae.error=d.debugLog?i(p,"ERROR"):p):(ae.debug=d.debugLog?i(l,"DEBUG"):l,ae.log=d.debugLog?i(h,"LOG"):h,ae.warn=d.debugLog?i(P,"WARN"):P,ae.error=d.debugLog?i(A,"ERROR"):A)}ae.toggle=se;function Ve(W,...Ie){switch(W){case"DEBUG":ae.debug(...Ie);break;case"LOG":ae.log(...Ie);break;case"WARN":ae.warn(...Ie);break;case"ERROR":ae.error(...Ie);break}}ae.send=Ve})(Pi||(Pi={}));var c=Pi;var qe=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(qe||{}),ce;(p=>{function a(l){return l.length?typeof l[0]=="object"?l:l.map(h=>e(h)):[]}p.fromIds=a;function e(l,h="USER"){return{id:l,type:h}}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,h="USER"){return i(e(l,h))}p.fromIdToString=r;function n(l){try{return JSON.parse(l)}catch(h){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}p.fromString=n;function s(l,h){return l.id===h.id&&l.type===h.type}p.compare=s})(ce||(ce={}));var de;(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},ce.fromSignaling(n))}r.fromSignaling=t;function i(n){return n&&typeof n=="object"?n.deviceIdx:0}r.getDeviceIdx=i})(de||(de={}));var _e=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(_e||{}),Hr="s",Gr="m";function Je(a){return a.participantId+(a.mediaType?at+Hr+a.mediaType:"")+(a.streamName?at+Gr+a.streamName:"")}function Tt(a){let e=a.split(at),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 Hr:i=Ka(p.slice(1));break;case Gr: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:v.compose(t,n),mediaType:i,streamName:r}}function Ka(a){for(let e of Object.keys(_e))if(e===a)return _e[e];return null}function bi(a,e){return a===null||e===null?a===null&&e===null:!(a.maxDimension!==e.maxDimension||a.maxBitrateK!==e.maxBitrateK||a.maxFramerate!==e.maxFramerate||a.degradationPreference!==e.degradationPreference)}function Gt(a,e){return!(!bi(a.camera,e.camera)||!bi(a.screenSharing,e.screenSharing))}function Mi(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function Wr(a){try{return btoa(JSON.stringify(a))}catch(e){c.warn("WaitingParticipant: failed convert to string",a,e)}return null}function jr(a){try{return JSON.parse(atob(a))}catch(e){c.warn("WaitingParticipant: failed convert from string",a,e)}return null}var It=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,m.log(_.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,m.log(_.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(_.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),m.log(_.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===ne.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Wt=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(!((s=this._output)==null?void 0:s.audioTrack))return;let e=y.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{c.warn("Error on play audio"),T.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=y.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw m.log(_.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var $a=90,qa=3,jt=class extends z{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),T.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>$a?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=qa)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var Ja=44100,Ct=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=Ja/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 Kt=class extends z{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&T.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,d.voiceParams.interval)};this._interval=window.setTimeout(t,d.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,fe.SOURCE_CHANGED,r=>{r.kind===ne.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new Ct("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 Ya=1e3;function ke(a,e,t=0){return e in a&&a[e]?a[e]:t}function Kr(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function Be(a,e){return t=>t[a]===e}function za(a){return(e,t)=>e[a]-t[a]}function $t(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function Qa(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Xa(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Ai(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=Xa(t[1])?Ai(t[1]):t[1],e),{})}function Za(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function en(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(Za).then(Qa)})}function tn(a){let e=a.filter(Be("type","candidate-pair")).sort(za("priority")).find(Kr(Be("nominated",!0),Be("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(Be("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(Be("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),Ai(t)}function rn(a,e){let t=$t("id",a),i=a.filter(Kr(Be("type","inbound-rtp"),Be("type","outbound-rtp")));y.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(y.browserName()==="Safari"){let n=a.filter(Be("type","track"));r=$t("trackIdentifier",n)}return i.map(n=>{let s=Number(n.ssrc),p=n.mediaType||n.kind,l=n.trackId,h=n.type,P=n.codecId;if(y.browserName()==="Safari"){let $=/^.+_([\d]+)$/.exec(n.id);if($&&(s=parseInt($[1],10)),p=n.id.indexOf("Audio")>0?"audio":"video",e[s]){let j=p+"-"+e[s];r[j]&&(l=r[j].id)}}if(!h||!s||!p)return null;let A={ssrc:s,type:h,kind:p,bytesReceived:ke(n,"bytesReceived"),bytesSent:ke(n,"bytesSent"),jitter:ke(n,"jitter"),packetsLost:ke(n,"packetsLost"),packetsReceived:ke(n,"packetsReceived"),packetsSent:ke(n,"packetsSent"),fractionLost:ke(n,"fractionLost"),pliCount:ke(n,"pliCount"),firCount:ke(n,"firCount"),nackCount:ke(n,"nackCount"),userId:e[s]};if(P&&t[P]){let $=t[P];A.clockRate=$.clockRate,A.mimeType=$.mimeType}if(l&&t[l]){let $=t[l];A.frameHeight=$.frameHeight,A.frameWidth=$.frameWidth,A.framesDecoded=$.framesDecoded,A.framesReceived=$.framesReceived,A.framesDropped=$.framesDropped}return Ai(A)}).filter(n=>!!n)}function an(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=$t("ssrc",a.rtps),i=$t("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let 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,h=s.packetsReceived-p.packetsReceived;s.packetLoss=parseFloat((100*l/(l+h)).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 yt(i,r){return o(this,arguments,function*(a,e,t={}){let n=yield en(a),s={timestamp:Date.now(),transport:tn(n),rtps:rn(n,t)};return e?an(s,e):(yield v.delay(Ya),yt(a,s,t))})}var qt=.8,Ye=class extends z{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=N.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=n,this.subscribe(this._signaling,le.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,fe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,fe.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:d.iceServers,iceTransportPolicy:d.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(s){m.log(_.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===N.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==N.IDLE&&e!==N.CLOSED&&e!==N.FAILED&&this._startStatInterval()}open(e=null){return o(this,null,function*(){if(this._isOpen){c.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(c.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(i){m.log(_.ERROR,"addTrack-direct"),c.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(N.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(x.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Gt(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(x.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(N.FAILED)):(c.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(N.CLOSED)),this._triggerEvent(x.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(x.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case D.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case D.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 D.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=v.getPeerIdString(e.peerId);v.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(_.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(_.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(x.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(x.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===N.IDLE||e===N.OPENED?this._setState(N.CONNECTING):this._setState(N.RECONNECTING);break}}_onConnectionStateChange(){switch(c.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),m.log(_.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(N.CONNECTED),this._stopReconnection(),v.getPeerConnectionHostInfo(this._pc).then(e=>{e&&m.log(_.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(N.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(ve.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(m.log(_.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(_.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}),m.log(_.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=Ye._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(_.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(_.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=Ye._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(_.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=v.patchSDP(e.sdp,d.preferH264&&y.canPreferH264(),y.isBrokenH264(),d.preferVP9,t&&d.audioNack),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{c.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),m.log(_.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}yt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:ve.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:ve.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(x.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=se=>se.rtt<=this._networkLimits.goodNet.rtt&&se.loss<=this._networkLimits.goodNet.loss,i=se=>se.rtt>=this._networkLimits.badNet.rtt||se.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((se,Ve)=>Math.max(se,Ve.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-qt)+r*qt,loss:this._lastNetworkStat.loss*(1-qt)+n*qt},p=i(s),l=t(s),h=i(this._remoteNetworkStat),P=t(this._remoteNetworkStat),A=i(this._lastNetworkStat),$=t(this._lastNetworkStat),pe=p||h?.2:l&&P?1:0,Pe=Date.now();if((A!==p||$!==l||Pe-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(se=>{c.warn("Unable to send [bad-net]",se)})),pe){let se={};se[this._participantId]=se[""]=pe,this._triggerEvent(x.NETWORK_STATUS,se)}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=v.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(T.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=v.applySettings(this._pc,e,this._prevConsumerSettings))}};var $r=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))($r||{}),Rt=$r;var ze=Fe(require("messagepack"));var Di=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var n,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let p=(0,ze.decode)(r);return Object.entries(p).forEach(([L,pe])=>{let Pe=Tt(L);this.streamDescriptionByCompactId.set(pe,Pe)}),null;case 2:case 4:let l=(0,ze.decode)(r),h=[];for(let L of l){let pe=this.getStreamDescription(L);pe&&h.push(pe.participantId)}return i===2?{type:"notification",notification:D.AUDIO_ACTIVITY,activeParticipants:h}:{type:"notification",notification:D.STALLED_ACTIVITY,stalledParticipants:h};case 3:let P=(0,ze.decode)(r);return{type:"notification",notification:D.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(P))==null?void 0:n.participantId};case 5:let A=(0,ze.decode)(r);return{type:"notification",notification:D.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:A[0],maxDimension:A[1]}};case 6:let $=(0,ze.decode)(r),j={};for(let[L,pe]of Object.entries($)){let Pe=(s=this.getStreamDescription(Number(L)))==null?void 0:s.participantId;Pe&&(j[Pe]=pe/100)}return{type:"notification",notification:D.NETWORK_STATUS,statuses:j};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,ze.decode)(e),i=[];for(let[r,n]of Object.entries(t)){let s=n[0],p=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 P=Ce.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,A=p?p>>>0:null;i.push({participantStreamDescription:h,streamId:P,rtpTimestamp:A,sequenceNumber:l})}return{type:"notification",notification:D.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var qr="videochat-epi",Pt=class extends z{constructor(e,t){super();this._previousTimestamp=0;this._signaling=t,this.subscribe(e,x.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(qr)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return o(this,null,function*(){if(!d.perfStatReportEnabled||!e.inbound||!e.inbound.rtps)return;let t=e.inbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.framesDecoded+=n.framesDecoded||0,r.framesReceived+=n.framesReceived||0),r),{framesDecoded:0,framesReceived:0}),i=Date.now();if(!(this._previousTimestamp+5e3>i)){if(t.framesDecoded)try{let r=yield this._signaling.reportPerfStat(t);localStorage.setItem(qr,r.estimatedPerformanceIndex)}catch(r){}this._previousTimestamp=i}})}};var nn=90,sn=4294967295,Ee=class extends z{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._reconnectionPrevented=!1;this._state=N.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,le.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,fe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,fe.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,fe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Pt(this,e),this._serverSettings=i,c.debug("ServerTransport: Created")}getState(){return this._state||N.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==N.IDLE&&e!==N.CLOSED&&e!==N.FAILED&&this._startStatInterval()}open(){if(this._isOpen){c.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(c.error("ServerTransport: Closed",e),this._setState(N.FAILED)):(c.debug("ServerTransport: Closed"),this._setState(N.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Gt(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,Ee._closeDataChannel(this._producerNotification),Ee._closeDataChannel(this._producerCommand),Ee._closeDataChannel(this._producerScreen),Ee._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(x.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{c.debug(`[${t}] data channel opened`),r.onerror=n=>{c.error(`[${t}] data channel error`,n)},i(r)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection");let t={};y.baseChromeVersion()&&(t.sdpSemantics=Ee._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=v.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Ee._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,Rt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Di,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,Rt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,Rt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){c.error("ServerTransport: Unable to add media source tracks",i),m.log(_.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,Rt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(N.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==N.OPENED&&(this._setState(N.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(x.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(x.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(x.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(x.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
- `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Ce.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!d.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new ct(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!d.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new st(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(x.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(x.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!==ne.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(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)})}v.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(x.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 yt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(x.REMOTE_DATA_STATS,{inbound:{topology:ve.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:ve.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=Ce.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(x.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Pt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:d.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:d.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:d.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:d.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:Ee._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return o(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,c.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(c.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw c.error("[single] unable to set remote offer",i),m.log(_.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(_.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=v.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(_.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(_.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 D.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case D.REALLOC_CON:this._reconnect();break;case D.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case D.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case D.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case D.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")),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(x.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(x.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(_.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===N.IDLE||i===N.OPENED?this._setState(N.CONNECTING):e.iceConnectionState==="checking"&&this._setState(N.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(N.RECONNECTING);break;case"connected":this._setState(N.CONNECTED),v.getPeerConnectionHostInfo(e).then(r=>{r&&m.log(_.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),m.log(_.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=y.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(y.browserName(),y.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return m.log(_.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(_.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(_.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&sn,l=Math.ceil(p/nn);return Math.min(100,Math.max(0,l))}};var x=(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.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",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))(x||{}),N=(p=>(p.IDLE="IDLE",p.OPENED="OPENED",p.CONNECTING="CONNECTING",p.RECONNECTING="RECONNECTING",p.CONNECTED="CONNECTED",p.CLOSED="CLOSED",p.FAILED="FAILED",p))(N||{}),ve=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(ve||{}),Oi=class extends z{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,le.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){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){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){c.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){c.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),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()}_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===D.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===D.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),m.log(_.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?v.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)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new Ye(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),this._dtListeners&&this._dtListeners.length>0&&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 Ee(this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!1),this._stListeners&&this._stListeners.length>0&&c.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("ACTIVE_PARTICIPANTS_NO_SIGNAL",this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;d.noiseSuppression!==e&&(d.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent("ACTIVE_PARTICIPANTS_NO_SIGNAL")}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(m.log(_.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(_.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Qe=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(Qe||{}),ki=class extends z{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,x.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,x.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,x.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,x.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===ne.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Ct(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===ne.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===Ce.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var wi=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(wi||{}),xi=class extends z{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,Qe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,x.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,x.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,x.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>d.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*d.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent("SPEAKER_CHANGED",e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var Jt=class extends z{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,x.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,Qe.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===N.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===N.FAILED&&this._connectionTimeout&&(c.warn("Transport failed, send callSpecError"),m.log(_.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!==N.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(c.warn("There is not connected transport, send callSpecError"),m.log(_.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(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&c.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var on=1e3,cn=1e4;var dn=15,B=class extends z{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=G.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 Wt,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),on))}static current(){return B._current}static hangupAfterInit(){B._activationMutex&&!B._current&&(B._delayedHangup=!0)}static id(){var e,t;return((t=(e=B._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,s=!1){return o(this,null,function*(){if(B._activationMutex)throw m.log(_.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new O(b.FAILED);B._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let p=this._mediaSource.getMediaSettings();t===Me.CHAT||e.length>1?this._logWithMediaSettings(_.OUTGOING_MULTIPARTY_CALL,p):this._logWithMediaSettings(_.OUTGOING_CALL,p);let l=yield this._startConversation(e,t,xe.OUTGOING,i,r,n,s);if(!this._conversation)throw new O(b.UNKNOWN_ERROR);if(this._participantState=G.ACCEPTED,this._signaling.changeMediaSettings(p),yield this._registerParticipants(l.conversation.participants),this._processConnectionData(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new O(b.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let h=Object.values(this._participants),P;return d.batchParticipantsOnStart&&(P=v.mapSharedParticipants(h)),T.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,P),T.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),B._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(h,q.WAITING),this._conversation}catch(p){throw this._close(p,"Unable to start conversation"),p}finally{B._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){if(B._activationMutex)throw m.log(_.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new O(b.FAILED);B._activationMutex=!0,this._state="PROCESSING";try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new O(b.UNKNOWN_ERROR);return T.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(c.log("In waiting hall"),B._current=this,B._activationMutex=!1,this._signaling.readyToSend(),T.onLocalStatus(q.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw B._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return o(this,null,function*(){c.debug("Join conversation part 2"),B._activationMutex=!0;try{if(this._participantState=G.ACCEPTED,!this._conversation||!this._mediaSource)throw new O(b.UNKNOWN_ERROR);if(this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new O(b.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=v.mapSharedParticipants(t)),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),T.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),B._current=this,d.batchParticipantsOnStart||this._setParticipantsStatus(t,q.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{B._activationMutex=!1}})}onPush(r){return o(this,arguments,function*(e,t=Q.USER,i){if(B._activationMutex)throw c.warn("Conversation: there is already running activation"),new O(b.REJECTED);B._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new O(b.UNKNOWN_ERROR);if(!n.conversation.participants.find(p=>{var l;return p.state===G.CALLED&&p.id===((l=this._conversation)==null?void 0:l.userId)}))throw c.log("Push rejected (there is an active call)"),m.log(_.PUSH,"rejected"),new O(b.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),m.log(_.PUSH,"accepted"),B._current=this,B._delayedHangup)throw new O(b.CANCELED);B._activationMutex=!1}catch(n){throw B._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Dt.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>v.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return o(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new O(b.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_CONCURRENT,e),c.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),T.onCallAccepted(),this._state="ACTIVE",this._participantState=G.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(_.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 O(b.UNKNOWN_ERROR);this._state="PROCESSING",c.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=G.ACCEPTED;let i=Object.values(this._participants),r;d.batchParticipantsOnStart&&(r=v.mapSharedParticipants(i)),T.onCallAccepted(),T.onLocalStream(this._mediaSource.getStream(),t),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),T.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(Ne.MUTE)||n.includes(Ne.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),d.batchParticipantsOnStart||this._setParticipantsStatus(i,q.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return o(this,null,function*(){var e;if(this._state!=="IDLE")throw m.log(_.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(_.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=G.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(b.REJECTED)),this._close(new O(b.REJECTED))})}hangup(){return o(this,null,function*(){c.debug("Hangup");let e=this._state==="ACTIVE"?b.HUNGUP:b.CANCELED;m.log(_.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new O(e))):T.onHangup(new O(b.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new O(b.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=b.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(v.composeId(n),n,r)})}removeParticipant(e,t=!1){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){if(!this._transport)return;let i=[];for(let r of e)(r.state===G.CALLED||r.state===G.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===G.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&c.error(t,e),c.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(b.FAILED):m.log(_.ERROR,e.hangup),B._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([b.CANCELED,b.NOT_FRIENDS,b.CALLEE_IS_OFFLINE,b.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===b.REJECTED&&!e.remote){T.onHangup(e,i),this.destroy();return}if(e.hangup===b.HUNGUP&&(!e.remote||this._participantState===G.CALLED)){T.onHangup(e,i),this.destroy();return}if(e.hangup===b.MISSED&&!e.remote){T.onHangup(e,i),this.destroy();return}if(e.hangup===b.SOCKET_CLOSED&&B._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===b.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=G.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,B._current=null,B._delayedHangup=!1,T.onHangup(e||new O(b.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,B._current=null,B._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return o(this,null,function*(){let t=yield this._api.getConversationParams(e);c.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let s=r.urls.filter((p,l,h)=>h.indexOf(p)===l);s.forEach(p=>s.push(`${p}?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})}_startConversation(e,t,i,r,n="",s=!1,p=!1){return o(this,null,function*(){let l=v.uuid();c.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let h=r.includes(re.VIDEO),P=yield this._api.startConversation(l,e,t,h,n,s,p);c.debug("Api.startConversation",P),yield this._getConversationParams(P.id);let A=yield this._connectSignaling(Ae.START,P);return yield this._setConversation(P,A,i),A})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n}=e;c.debug("Conversation: join",{conversationId:t,joinLink:n});let s=i.includes(re.VIDEO),p;if(t)p=yield this._api.joinConversation(t,s,r);else if(n)p=yield this._api.joinConversationByLink(n,s);else throw new O(b.UNKNOWN_ERROR);c.debug("Api.joinConversation",p),yield this._getConversationParams(p.id);let l=yield this._connectSignaling(Ae.JOIN,p);return yield this._setConversation(p,l,xe.JOINING),l})}_prepareConversation(r){return o(this,arguments,function*(e,t=Q.USER,i){c.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let n=this._api.getUserId();if(!n)throw new O(b.UNKNOWN_ERROR);let s=yield this._getConversationParams(e);c.error("got params",s);let p=s.device_idx||0,l={id:e,peerId:i,endpoint:`${d.wssBase}?userId=${n}&entityType=${t}&deviceIdx=${p}&conversationId=${e}&token=${d.wssToken}`,is_concurrent:!1,p2p_forbidden:!1,device_idx:p},h=yield this._connectSignaling(Ae.ACCEPT,l);return B._current&&(B._current._participantState===G.ACCEPTED||B._current._participantState===G.CALLED)?(c.log("Push rejected (busy)"),m.log(_.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(b.BUSY),Promise.reject({hangup:b.BUSY})):(B._current&&(B._current.destroy(),B._current=null),yield this._setConversation(l,h,xe.INCOMING,t),h)})}_createParticipant(e){return o(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:me(),participantState:{},state:G.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);if(e.externalId){let i=v.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(i,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return t})}_getParticipantId(e){return o(this,null,function*(){try{let t=v.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new O(b.NETWORK_ERROR),t),t}})}_setConversation(n,s,p){return o(this,arguments,function*(e,t,i,r=Q.USER){let l=t.conversation.participants.map(j=>j.id);yield this._api.prepareUserIds(l);let h=this._api.getUserId(),P=e.device_idx||0;if(!h){let j=(t.conversation.participants||[]).find(L=>v.comparePeerId(L.peerId,t.peerId));if(!j)throw new O(b.UNKNOWN_ERROR);h=Number(j.id),j.idType&&(r=j.idType),j.deviceIdx&&(P=j.deviceIdx),this._api.setUserId(h)}let A=v.composeParticipantId(h,r,P),$=yield this._getParticipantId(A);this._conversation={userId:h,compositeUserId:A,externalId:$,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||ve.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),m.log(_.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new O(b.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||ve.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 di;return this.subscribe(e,fe.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,fe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new It(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,le.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,le.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,le.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return o(this,null,function*(){if(!!this._conversation)for(let t of e){let i=v.composeId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(c.debug(`Local roles changed: ${t.roles}`),T.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===G.HUNGUP||t.state===G.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],b.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&de.fromSignaling(t.externalId,t.deviceIdx),mediaSettings:me(t.mediaSettings),participantState:v.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?q.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(c.debug(`Roles for participant [${i}] changed: ${t.roles}`),T.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){v.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(At.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Oi(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new jt,this.subscribe(this._transport,x.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,x.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,x.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,x.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,x.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,x.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,x.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,x.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,x.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,x.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,x.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,x.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===xe.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===G.ACCEPTED||t.state===G.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new ki(this._transport),this.subscribe(this._volumesDetector,Qe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new xi(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,wi.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Kt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Jt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=y.getCameras().length,t=y.getMicrophones().length;c.debug("Cameras: "+e+(y.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(y.hasMicrophonePermission()?"✔":"✖")),m.log(_.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===G.CALLED||e.state===G.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===b.HUNGUP?this._setParticipantsStatus([e],q.HANGUP):this._setParticipantsStatus([e],q.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:_e.CAMERA,stopStream:!0}]),delete this._participants[e.id],T.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){c.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return o(this,null,function*(){c.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===G.ACCEPTED||r.state===G.CALLED)){c.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&de.fromSignaling(t.externalId,t.deviceIdx),mediaSettings:me(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],q.WAITING),i?(r.state=G.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=G.CALLED,this._transport.allocate(r.id,!0),m.log(_.ADD_PARTICIPANT))})}_onRemoveParticipant(e){c.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=dn;i++){let r=v.compose(e,i),n=this._participants[r];n&&t.push(n)}if(!t.length){c.warn(`Participant [${e}] isn't in conversation`);return}if(this._transport)for(let i of t)this._transport.close(i.id);m.log(_.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new It(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(Z.UNKNOWN)})}toggleScreenCapturing(e){return o(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(Z.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(_.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return m.log(_.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:de.fromId(r.uid),s=de.toString(n);i[s]=r.priority}for(let r of Object.values(this._participants)){let n=de.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return o(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}updateDisplayLayout(e){return o(this,null,function*(){if(e.length<1||!this._signaling.ready)return;c.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:de.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(n);if(!s){let P=de.toString(n);c.log(`Unknown participant external ID ${P}`);continue}let p=v.compose(s,n.deviceIdx),l=Je({participantId:p,mediaType:r.mediaType,streamName:r.streamName}),h=this._participants[p];h&&(h.lastRequestedLayouts[l]=r),B._isStopStreaming(r)?this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now()):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&d.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=B._layoutToString(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]=B._layoutToString({stopStream:!0})}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(c.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Tt(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===_e.STREAM||i.mediaType===_e.SCREEN)?T.onRemoteLive(r.externalId,i.streamName,null):T.onRemoteStream(r.externalId,null),m.log(_.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=Tt(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=ur.UNKNOWN_ERROR):l=mr(n),i.push({externalId:p.externalId,errorReason:l})}}if(i&&i.length)throw new Yt("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+cn>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=B._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(B._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),e.keyFrame&&(t!==""&&(t+=":"),t+="kf"),t}_onParticipantSourcesUpdate(e){if(this._conversation){c.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){c.log("Promoted in waiting hall",!e.demote),e.demote?(c.log("Kicked from waiting hall"),this._close(new O(b.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=ce.fromSignaling(p.externalId);n.push(l),this._api.cacheExternalId(p.id.id,l)}else s.push(v.decomposeId(p.id.id).id)}),s.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(s))),T.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var p,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===_e.SCREEN)return;let i=Je(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(_.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,P=this._participants[h];if(!P){m.log(_.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${h}`);return}let A=this._streamByStreamId.get(n);if(!A){m.log(_.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${n}`);return}m.log(_.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let $=(p=e.participantStreamDescription)==null?void 0:p.mediaType;if($===_e.STREAM||$===_e.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&T.onRemoteLive(P.externalId,e.participantStreamDescription.streamName,A);else{let j=(d.producerScreenTrack?null:P.secondStream)||A;T.onRemoteStream(P.externalId,j)}}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(Je(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Je(i)))return i}else{let i={participantId:t,mediaType:_e.CAMERA};if(this._streamIdByStreamDescription.has(Je(i)))return i;let r={participantId:t,mediaType:_e.SCREEN};if(this._streamIdByStreamDescription.has(Je(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?v.includesOneOf(this._conversation.roles,[He.ADMIN,He.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!v.includesOneOf(this._conversation.roles,[He.ADMIN,He.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=er(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=jr(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let s=n.participants||[],p=[],l=[],h=null;return s.length&&(s.forEach(P=>{if(P.externalId){let A=ce.fromSignaling(P.externalId);p.push(A),this._api.cacheExternalId(P.id.id,A)}else l.push(v.decomposeId(P.id.id).id)}),l.length&&!p.length&&(p=yield this._api.getExternalIdsByOkIds(l)),n.hasMore&&(h=Wr(s[s.length-1].id))),{participants:p,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 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)})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t;!this._conversation||(c.debug("Local media stream changed",e.mediaSettings),T.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return o(this,null,function*(){var t;if(c.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;T.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){c.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&T.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){c.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&(d.participantStateMapped?T.onRemoteParticipantState(i.externalId,i.participantState):T.onRemoteParticipantState(i.externalId,v.mapLegacyParticipantState(i.participantState))))}_onSignalingNotification(e){switch(e.notification){case D.ACCEPTED_CALL:return this._onAcceptedCall(e);case D.HUNGUP:return this._onHungup(e);case D.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case D.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case D.CLOSED_CONVERSATION:return this._onClosedConversation(e);case D.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case D.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case D.RATE_CALL_DATA:return this._onNeedRate();case D.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case D.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case D.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case D.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case D.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case D.REGISTERED_PEER:return this._onPeerRegistered(e);case D.SWITCH_MICRO:return this._onMicSwitched(e);case D.CHAT_MESSAGE:return this._onChatMessage(e);case D.CUSTOM_DATA:return this._onCustomData(e);case D.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case D.RECORD_STOPPED:return this._onRecordInfo(null);case D.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case D.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case D.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case D.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case D.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case D.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case D.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return o(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let s=v.composeId(n),p=n.roles||[];if(s===this._conversation.compositeUserId){t=me(n.mediaSettings),ht(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 h=me(n.mediaSettings);Ir(h,l.mediaSettings)||this._changeRemoteMediaSettings(s,h);let P=v.mapParticipantState(n),A=l.participantState;v.isEqualParticipantState(P,A)||this._changeRemoteParticipantState(s,P),ht(p,l.roles)||this._onRolesChanged(l.id,p)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],b.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){c.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return o(this,null,function*(){let t=v.composeMessageId(e),i=v.getPeerIdString(e.peerId);if(c.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new O(b.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:me(e.mediaSettings)}),r=this._participants[t]),r.state=G.ACCEPTED,r.mediaSettings=me(e.mediaSettings),this._logWithMediaSettings(_.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===xe.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){c.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=v.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new O(e.reason));return}let i=this._participants[t];if(!i){c.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===b.REJECTED?G.REJECTED:G.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,b.HUNGUP)}_onAddedParticipant(e){return o(this,null,function*(){var r,n;c.debug(`Participant added [${e.participantId}]`);let t=v.composeMessageId(e),i=this._participants[t];if(i&&i.state!==G.HUNGUP&&i.state!==G.REJECTED){c.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&de.fromSignaling(e.participant.externalId,e.participant.deviceIdx),mediaSettings:me(e.participant.mediaSettings),state:e.participant.state,participantState:v.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=G.CALLED,i.mediaSettings=me((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=v.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],q.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onJoinedParticipant(e){return o(this,null,function*(){var r;c.debug(`Participant joined [${e.participantId}]`);let t=v.composeMessageId(e),i=this._participants[t];if(i&&i.state===G.ACCEPTED){c.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&de.fromSignaling(e.participant.externalId,e.participant.deviceIdx),mediaSettings:me(e.participant.mediaSettings),state:e.participant.state,participantState:v.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===xe.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=G.ACCEPTED,i.mediaSettings=me(e.mediaSettings),i.participantState=v.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],q.CONNECTED):this._setParticipantsStatus([i],q.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id])),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new O(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=v.composeMessageId(e);this._changeRemoteMediaSettings(t,me(e.mediaSettings))}_onParticipantStateChanged(e){let t=v.composeMessageId(e);this._changeRemoteParticipantState(t,v.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),T.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=me(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),d.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Mi(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(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=Mi(this._serverSettings,r),c.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=v.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return o(this,null,function*(){T.onDeviceSwitched(re.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return o(this,null,function*(){let t=v.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),T.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return o(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=v.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),T.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return o(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getParticipantId(e.initiator);T.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else T.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!ht(this._conversation.roles,t)){c.debug(`Local roles changed: ${t}`),this._conversation.roles=t,T.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!ht(i.roles,t)&&(c.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,T.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){c.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let p=this._participants[e.participantId];p&&(c.debug(`Mute states for participant [${e.participantId}] changed`,i),T.onMuteStates(i,r,n,e.muteAll,e.unmute,p.externalId,s==null?void 0:s.externalId));return}v.isObjectsEquals(this._conversation.muteStates,i)&&v.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!==G.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),p=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),h=Object.entries(s);for(let[P,A]of h)if(!(A!==Ne.MUTE&&A!==Ne.MUTE_PERMANENT)&&(this._isCallAdmin()&&A===Ne.MUTE_PERMANENT&&(s[P]=Ne.MUTE),!(!e.includes(P)||i)))switch(P){case re.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(T.onDeviceSwitched(re.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case re.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(T.onDeviceSwitched(re.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case re.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(T.onDeviceSwitched(re.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}T.onMuteStates(s,p,e,t,i,null,n==null?void 0:n.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?T.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&T.onLocalPin(!0)),this._participants[e]?T.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&T.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!Zi(this._conversation.options,e)&&(this._conversation.options=e,T.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let n;if(i===this._conversation.compositeUserId||i==="")n=this._conversation.networkRating;else if(this._participants[i])n=this._participants[i].networkRating;else continue;if(n!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,T.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;c.log("Received network status update: ",e),T.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){T.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){m.log(_.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${n}`);return}T.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&T.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===ve.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Qi.ADD_PARTICIPANT);T.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&T.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}T.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(T.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){c.debug(`Transport state has changed: ${t}`,e);let i;if(t===N.CONNECTED?i=q.CONNECTED:t===N.CONNECTING||t===N.OPENED?i=q.CONNECTING:t===N.RECONNECTING&&(i=q.RECONNECT),!i)return;let r=e.reduce((n,s)=>{if(s in this._participants){let p=this._participants[s];n.push(p),t===N.CONNECTED&&(p.remoteStream||(p.mediaSettings&&this._changeRemoteMediaSettings(s,p.mediaSettings),this._changeRemoteParticipantState(s,p.participantState)),this._updateDisplayLayoutFromCache(s))}else c.warn(`Participant [${s}] isn't in conversation`);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){c.debug(`Local transport state has changed: ${e}`),e===N.CONNECTED&&T.onLocalStatus(q.CONNECTED),e===N.CONNECTING&&T.onLocalStatus(q.CONNECTING),e===N.RECONNECTING&&T.onLocalStatus(q.RECONNECT),e===N.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(b.FAILED)),this._close(new O(b.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(Ce.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(Ce.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))c.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{c.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(c.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],q.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(T.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===ne.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;T.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),d.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(c.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case ne.audio:this._removeAudioTrack(e,t,i);break;case ne.video:case ne.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Ce.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onRemoteActivityNoSignal(){this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)}_onTopologyChanged(e){this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let n=this._participants[r];e||this._lastStalled[r]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,q.RECONNECT),i.length&&this._setParticipantsStatus(i,q.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let 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,q.RECONNECT),r.length&&this._setParticipantsStatus(r,q.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!y.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(c.debug("Toggle join availability",{available:t,chatId:e}),T.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==ve.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):T.onParticipantStatus(s.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&T.onRemoteStatus(r,t,i)}},w=B;w._delayedHangup=!1;var Yt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Yt.prototype),this.participantErrors=t}};function Jr(){if(!d.apiAppId||!d.apiKey)throw new O(Z.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function Ni(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=zr(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${d.apiEnv.api}fb.do`,r)}function Yr(i){return o(this,arguments,function*(a,e={},t=!1){let r=zr(a,e,t);return pn(r)})}function pn(a){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${d.apiEnv.api}fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(n){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(a)})})}function zr(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=d.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 un=10,mn=700,hn=3e3,bt=class extends Xe{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 Yr(e,t,i)}catch(p){if(!p.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<un))return yield v.delay(Math.min(s*mn,hn)),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=Z.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=b.SERVICE_DISABLED;break;case 1102:s=b.CALLEE_IS_OFFLINE;break;case 1103:s=b.NOT_FRIENDS;break;case 1104:case 1106:s=b.EXTERNAL_API_ERROR;break}throw new O(s,{message:n.error_msg,code:n.error_code})}})}userId(e){return o(this,null,function*(){let t=v.decomposeId(e).id;return X.isEmpty()?ce.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),ce.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=Ue.get("uuid");t||(t=v.uuid(),Ue.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)),X.sessionKey=t.session_key,X.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&T.onTokenExpired(),new O(Z.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})};Ni("log.externalLog",t)}init(){Jr()}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};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};if(t&&t.length)switch(i){case Me.USER:l.uids=t.join(",");break;case Me.GROUP:l.gid=t[0];break;case Me.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){return o(this,null,function*(){let i={joinLink:e,isVideo:t,protocolVersion:d.protocolVersion};return d.anonymToken&&(i.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=ce.fromIds(e),i=[],r={methods:[]},n=[],s=Object.keys(this._externalUidsCache),p=Object.values(this._externalUidsCache);for(let h of t){let P=ce.toString(h),A=p.indexOf(P);A>-1?i.push(Number(s[A])):(n.push(P),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:h.id,anonym:h.type===qe.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((h,P)=>{if(h.ok){let A=Number(h.ok.ok_id);this._externalUidsCache[A]=n[P],i.push(A)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(ce.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(ce.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=ce.toString(e),n=i.indexOf(r);return n>-1?v.composeUserId(t[n],Q.USER):null}cacheExternalId(e,t){let i=v.decomposeId(e).id;this._externalUidsCache[i]=ce.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:b.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),Ni("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]=ce.fromIdToString(n,qe.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=ce.fromIdToString(n,qe.ANONYM);return t}catch(i){return t}})}getTokenForAnonym(e,t){return o(this,null,function*(){let i={id:e};return t&&(i.application_key=t),(yield this._callUnsafe("auth.getTokenForAnonym",i,!0)).token})}call(i){return o(this,arguments,function*(e,t={}){return this._call(e,t)})}};var Qr=(R=>(R.RECOVER="recover",R.ACCEPT_CALL="accept-call",R.ADD_PARTICIPANT="add-participant",R.REMOVE_PARTICIPANT="remove-participant",R.HANGUP="hangup",R.TRANSMIT_DATA="transmit-data",R.ACCEPT_PRODUCER="accept-producer",R.ALLOCATE_CONSUMER="allocate-consumer",R.CHANGE_MEDIA_SETTINGS="change-media-settings",R.CHANGE_PARTICIPANT_STATE="change-participant-state",R.CHANGE_STREAM_PRIORITIES="change-streams-priorities",R.UPDATE_DISPLAY_LAYOUT="update-display-layout",R.REPORT_PERF_STAT="report-perf-stat",R.RECORD_START="record-start",R.RECORD_STOP="record-stop",R.RECORD_SET_ROLE="record-set-role",R.RECORD_GET_STATUS="record-get-status",R.SWITCH_MICRO="switch-micro",R.SWITCH_TOPOLOGY="switch-topology",R.REQUEST_REALLOC="request-realloc",R.CHAT_MESSAGE="chat-message",R.CHAT_HISTORY="chat-history",R.CUSTOM_DATA="custom-data",R.GRANT_ROLES="grant-roles",R.MUTE_PARTICIPANT="mute-participant",R.PIN_PARTICIPANT="pin-participant",R.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",R.CHANGE_OPTIONS="change-options",R.GET_WAITING_HALL="get-waiting-hall",R.PROMOTE_PARTICIPANT="promote-participant",R.REQUEST_TEST_MODE="request-test-mode",R.ADD_MOVIE="add-movie",R.UPDATE_MOVIE="update-movie",R.REMOVE_MOVIE="remove-movie",R))(Qr||{}),H=Qr;var Xr="open",Zr=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0,()=>d.movieShare],gn=10,Te=class extends et{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="+Te._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null}static _getCapabilityFlags(){let e=0;for(let t=0;t<Zr.length;t++)Zr[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return o(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){m.log(_.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=v.decomposeParticipantId(t.participantId),s=v.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)===Xr&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){m.log(_.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(_.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=(P,A=!1)=>{!i||A?p(P):(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.producerCommandDataChannel?e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(H.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return o(this,null,function*(){return this._send(H.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return o(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(H.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(H.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},gn)})}changeParticipantState(e){return o(this,null,function*(){return this._send(H.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(H.ADD_PARTICIPANT,Ki({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(H.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(H.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(H.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(H.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(H.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return o(this,null,function*(){return this._send(H.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(H.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(H.REMOVE_MOVIE,e)})}startStream(e){return o(this,null,function*(){return this._send(H.RECORD_START,e)})}stopStream(){return o(this,null,function*(){return this._send(H.RECORD_STOP)})}recordSetRole(e,t){return o(this,null,function*(){return this._send(H.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return o(this,null,function*(){return this._send(H.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(H.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(H.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(H.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(H.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(H.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(H.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(H.GRANT_ROLES,r)})}muteParticipant(e,t,i){return o(this,null,function*(){return this._sendRaw(H.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(H.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(H.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(H.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(H.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(H.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ae.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),c.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){c.debug("Socket opened"),m.log(_.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(_.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(le.RECONNECT,e),e.conversation.topology&&this._triggerEvent(le.NOTIFICATION,{type:"notification",notification:D.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(le.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(m.log(_.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(m.log(_.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new O(b.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(le.NOTIFICATION,{notification:D.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 O(Z.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(m.log(_.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(le.FAILED,e)}_onError(e){m.log(_.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){m.log(_.SOCKET_ACTION,"closed"),c.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Te.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(Te.RECONNECT_MAX_DELAY,Te.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),m.log(_.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ae.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(_.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Te.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),n=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==Xr){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}Te._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Te.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(n))}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Te.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(n))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new O(Z.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Te.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(Ae.RETRY)},Te.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Re=Te;Re.RECONNECT_DELAY=d.signalingReconnectDelay,Re.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,Re.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,Re.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,Re.WAIT_RESPONSE_DELAY=d.waitResponseDelay,Re.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var ea=(t=>(t.KING="KING",t.PAWN="PAWN",t))(ea||{}),ta=ea;var pt,ee,Mt=null,_n={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 ia(a){ee=a}function ra(a){pt=a}function fn(a){Mt=a}function Sn(a){d.videoEffects=a}function vn(a){return o(this,null,function*(){if(d.set(a),y.browserName()==="Sferum"&&(d.platform=`SFERUM:${y.browserVersion()}`),ee||ia(new bt),pt||ra(()=>new Re),d.debug&&(Li.default.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${d.sdkVersion}`,a),yield y.init(),!y.isBrowserSupported())throw new O(Z.UNSUPPORTED);ee.init()})}function En(n){return o(this,arguments,function*(a,e=[re.AUDIO],t="",i=!1,r=!1){let s=[],p=[];if(Array.isArray(a)?s=a.length?a:[]:a&&(s=[a]),s.length&&(p=yield ee.getOkIdsByExternalIds(s),!p.length))throw new O(b.CALLEE_IS_OFFLINE);return aa(p,Me.USER,e,t,i,r)})}function aa(s){return o(this,arguments,function*(a,e=Me.USER,t,i="",r=!1,n=!1){if(w.current())throw c.error("There is already active call"),new O(b.FAILED);return new w(ee,pt(),Mt).onStart(a,e,t,i,r,n)})}function Tn(a){return o(this,null,function*(){return na(a)})}function na(i){return o(this,arguments,function*(a,e=Q.USER,t){if(a===w.id())throw new Error("Push has already been processed");return new w(ee,pt(),Mt).onPush(a,e,t)})}function In(a,e){return o(this,null,function*(){return ee.getTokenForAnonym(a,e)})}function Cn(t){return o(this,arguments,function*(a,e={}){return ee.call(a,e)})}function yn(a){return o(this,null,function*(){return a&&(d.authToken=a),ee.authorize()})}function Rn(){return o(this,arguments,function*(a=[re.AUDIO]){let e=w.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function Pn(){return o(this,null,function*(){let a=w.current();if(a)return a.decline()})}function bn(t){return o(this,arguments,function*(a,e=[re.AUDIO]){return sa(a,e)})}function sa(a,e,t){return o(this,null,function*(){if(w.current())throw c.error("There is already active call"),new O(b.FAILED);return new w(ee,pt(),Mt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function Mn(i){return o(this,arguments,function*(a,e=[re.AUDIO],t){if(w.current())throw c.error("There is already active call"),new O(b.FAILED);return t&&(d.anonymToken=t),new w(ee,pt(),Mt).onJoin({joinLink:a,mediaOptions:e})})}function An(){return o(this,null,function*(){let a=w.current();if(a)return a.hangup();w.hangupAfterInit()})}function Dn(a,e){return o(this,null,function*(){let t=yield ee.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return oa(t[0],e)})}function oa(a,e){return o(this,null,function*(){let t=w.current();t&&(yield t.addParticipant(v.composeUserId(a,Q.USER),e))})}function On(a,e=!1){return o(this,null,function*(){let t=yield ee.getOkIdsByExternalIds([a]);return ca(t[0],e)})}function ca(a,e=!1){return o(this,null,function*(){let t=w.current();t&&(yield t.removeParticipant(v.composeUserId(a,Q.USER),e))})}function kn(a,e){return o(this,null,function*(){let t=yield y.saveDeviceId(a,e),i=w.current();return t&&i?i.changeDevice(a):Promise.reject()})}function wn(a){return o(this,null,function*(){let e=w.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function xn(a,e=!1){return o(this,null,function*(){let t=w.current();t&&(yield t.setVideoStream(a,e))})}function Nn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalVideo(a))})}function Ln(a){return o(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalAudio(a))})}function Un(a,e,t){return o(this,null,function*(){let i=w.current();if(i)return i.setLocalResolution(a,e,t)})}function Bn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.changePriorities(a))})}function Vn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.changeParticipantState(a))})}function Fn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.updateDisplayLayout(a))})}function Hn(a,e,t=!1){return o(this,null,function*(){let i=yield ee.getOkIdsByExternalIds([a]);return da(i[0],e,t)})}function da(a,e,t=!1){return o(this,null,function*(){let i=w.current();i&&(yield i.grantRoles(v.composeUserId(a,Q.USER),e,t))})}function Gn(){return o(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield ee.getOkIdsByExternalIds([a]))[0]),pa(i,e,t,de.getDeviceIdx(a))})}function pa(){return o(this,arguments,function*(a=null,e,t=[],i=0){let r=w.current();if(r){let n=a?v.composeParticipantId(a,Q.USER,i):null;yield r.muteParticipant(n,e,t)}})}function Wn(a,e=!1){return o(this,null,function*(){let t=yield ee.getOkIdsByExternalIds([a]);return la(t[0],e,de.getDeviceIdx(a))})}function la(a,e=!1,t=0){return o(this,null,function*(){let i=w.current();i&&(yield i.pinParticipant(v.composeParticipantId(a,Q.USER,t),e))})}function jn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.updateMediaModifiers(a))})}function Kn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.changeOptions(a))})}function $n(a,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield ee.getOkIdsByExternalIds([e]))[0]),ua(a,t)})}function ua(a,e=null){return o(this,null,function*(){let t=w.current();if(t){let i=e?v.composeUserId(e,Q.USER):null;yield t.chatMessage(a,i)}})}function qn(a=10){return o(this,null,function*(){let e=w.current();if(e)return e.chatHistory(a)})}function Jn(a,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield ee.getOkIdsByExternalIds([e]))[0]),ma(a,t,de.getDeviceIdx(e))})}function ma(a,e=null,t=0){return o(this,null,function*(){let i=w.current();if(i){let r=e?v.composeParticipantId(e,Q.USER,t):null;yield i.customData(a,r)}})}function Yn(a="",e=!1){return o(this,null,function*(){return(yield ee.createConversation(v.uuid(),a,e)).join_link})}function zn(){return o(this,null,function*(){let a=w.current();return a?a.createJoinLink():Promise.reject()})}function Qn(){return o(this,null,function*(){let a=w.current();return a?a.removeJoinLink():Promise.reject()})}function Xn(a,e){return o(this,null,function*(){return ee.getAnonymTokenByLink(a,e)})}function Zn(a){let e=w.current();e&&e.setVolume(a)}function es(a){d.forceRelayPolicy=a}function ts(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return o(this,null,function*(){let n=w.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function is(){return o(this,null,function*(){let a=w.current();return a?a.stopStream():Promise.reject()})}function rs(a,e){return o(this,null,function*(){let t=w.current();if(t){let i=yield ee.getOkIdsByExternalIds([a]),r=de.getDeviceIdx(a);return t.recordSetRole(v.composeParticipantId(i[0],Q.USER,r),e)}return Promise.reject()})}function as(){return o(this,null,function*(){let a=w.current();return a?a.getStreamInfo():Promise.reject()})}function ns(a){return o(this,null,function*(){let e=w.current();return e?e.addMovie(a):Promise.reject()})}function ss(a,e,t,i){return o(this,null,function*(){let r=w.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function os(a){return o(this,null,function*(){let e=w.current();return e?e.removeMovie(a):Promise.reject()})}function cs(a){d.statisticsInterval=a;let e=w.current();if(e)return e.updateStatisticsInterval()}function ds(a){Li.default.disableLog(!a),c.toggle(a)}function ps(a,...e){!d.debugLog||c.send(a,"[external]",...e)}function ls(a){return o(this,null,function*(){let e=w.current();if(e)return e.videoEffect(a)})}function us(a){return o(this,null,function*(){let e=w.current();e&&(yield e.setAudioStream(a))})}function ms(a=null,e,t=!1){return o(this,null,function*(){let i=w.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(a,e,t)})}function hs(a,e=!1){return o(this,null,function*(){let t=w.current();if(!t)throw new Error("Conversation not found");let i=yield ee.getOkIdsByExternalIds([a]);return t.promoteParticipant(v.composeUserId(i[0],Q.USER),e)})}function gs(a){return o(this,null,function*(){yield ee.removeHistoryRecords(a)})}
7
+ var ha=Object.create;var ht=Object.defineProperty;var _a=Object.getOwnPropertyDescriptor;var ga=Object.getOwnPropertyNames,Fi=Object.getOwnPropertySymbols,fa=Object.getPrototypeOf,Hi=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable;var Gi=Math.pow,Wi=(a,e,t)=>e in a?ht(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,ji=(a,e)=>{for(var t in e||(e={}))Hi.call(e,t)&&Wi(a,t,e[t]);if(Fi)for(var t of Fi(e))Sa.call(e,t)&&Wi(a,t,e[t]);return a};var Ki=a=>ht(a,"__esModule",{value:!0});var va=(a,e)=>{Ki(a);for(var t in e)ht(a,t,{get:e[t],enumerable:!0})},Ea=(a,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ga(e))!Hi.call(a,i)&&i!=="default"&&ht(a,i,{get:()=>e[i],enumerable:!(t=_a(e,i))||t.enumerable});return a},He=a=>Ea(Ki(ht(a!=null?ha(fa(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)}},c=l=>{try{p(t.throw(l))}catch(m){r(m)}},p=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,c);p((t=t.apply(a,e)).next())});va(exports,{Api:()=>Mt,BaseApi:()=>et,BaseLogger:()=>tt,BaseSignaling:()=>it,CallDirection:()=>Ue,CallType:()=>ke,ChatRoomEventType:()=>Dt,ConversationOption:()=>Ot,DebugMessageType:()=>Ri,ExternalIdType:()=>Je,FacingMode:()=>vi,FatalError:()=>ie,HangupReason:()=>O,HangupType:()=>y,MediaOption:()=>pe,MediaTrackKind:()=>me,MediaType:()=>ve,MuteState:()=>Be,ParticipantState:()=>G,ParticipantStatus:()=>K,RecordRole:()=>ea,Signaling:()=>De,SignalingCommandType:()=>H,SignalingConnectionType:()=>we,SignalingNotification:()=>D,UserRole:()=>Ge,UserType:()=>Y,Utils:()=>S,acceptCall:()=>yn,addMovie:()=>as,addParticipant:()=>An,addParticipantInternal:()=>sa,apiCall:()=>Cn,authorize:()=>In,browser:()=>_n,callInternal:()=>ra,callTo:()=>vn,captureScreen:()=>kn,changeConversationOptions:()=>jn,changeDevice:()=>On,changeParticipantState:()=>Bn,changePriorities:()=>Un,changeVideoEffect:()=>ps,chatHistory:()=>$n,chatMessage:()=>Kn,chatMessageInternal:()=>la,createJoinLink:()=>Yn,customData:()=>qn,customDataInternal:()=>ua,debug:()=>cs,debugMessage:()=>ds,declineCall:()=>Rn,forceRelayPolicy:()=>Zn,getAnonymTokenByLink:()=>Qn,getStreamInfo:()=>rs,getTokenForAnonym:()=>Tn,getWaitingHall:()=>us,grantRoles:()=>Fn,grantRolesInternal:()=>ca,hangup:()=>Mn,init:()=>Sn,joinCall:()=>bn,joinCallByLink:()=>Pn,joinCallInternal:()=>na,muteParticipant:()=>Hn,muteParticipantInternal:()=>da,pinParticipant:()=>Gn,pinParticipantInternal:()=>pa,processPush:()=>En,processPushInternal:()=>aa,promoteParticipant:()=>ms,recordSetRole:()=>is,removeHistoryRecords:()=>hs,removeJoinLink:()=>zn,removeMovie:()=>ss,removeParticipant:()=>Dn,removeParticipantInternal:()=>oa,setApi:()=>ta,setAudioStream:()=>ls,setLocalResolution:()=>Ln,setLogger:()=>gn,setMediaModifiers:()=>Wn,setSignalingFactory:()=>ia,setStatisticsInterval:()=>os,setVideoEffects:()=>fn,setVideoStream:()=>wn,setVolume:()=>Xn,startConversation:()=>Jn,startStream:()=>es,stopStream:()=>ts,toggleLocalAudio:()=>xn,toggleLocalVideo:()=>Nn,updateDisplayLayout:()=>Vn,updateMovie:()=>ns});var Ui=He(require("webrtc-adapter"));var et=class{createJoinLink(e){return o(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return o(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return o(this,null,function*(){return""})}log(e){}prepareUserIds(e){return o(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return o(this,null,function*(){})}cleanup(){}getTokenForAnonym(e,t){return o(this,null,function*(){return""})}call(i){return o(this,arguments,function*(e,t={}){return null})}};var tt=class{log(e,t,i=!1){}destroy(){}};var J=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var it=class extends J{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var $i=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))($i||{}),Ue=$i;var qi=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(qi||{}),ke=qi;var Ji=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(Ji||{}),Dt=Ji;var Yi=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(Yi||{}),zi=Yi;var Qi=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(Qi||{}),Ot=Qi;function Xi(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function Zi(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 er=(B=>(B.CAMERA_PERMISSION="camera",B.MIC_PERMISSION="mic",B.CAMERA_ACCESS="cameralock",B.MIC_ACCESS="miclock",B.MIC_NOT_FOUND="nomic",B.SCREEN_PERMISSION="screenpermission",B.SCREEN_ACCESS="screenlock",B.CONNECTION="connection",B.NETWORK="network",B.UNKNOWN="unknown",B.UNSUPPORTED="unsupported",B.SIGNALING_FAILED="signalingfailed",B.API="api",B.AUTH="auth",B))(er||{}),ie=er;var tr=(W=>(W.CANCELED="CANCELED",W.REJECTED="REJECTED",W.REMOVED="REMOVED",W.HUNGUP="HUNGUP",W.MISSED="MISSED",W.BUSY="BUSY",W.FAILED="FAILED",W.NETWORK_ERROR="NETWORK_ERROR",W.KILLED="KILLED",W.BANNED="BANNED",W.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",W.NOT_FRIENDS="NOT_FRIENDS",W.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",W.UNKNOWN_ERROR="UNKNOWN_ERROR",W.UNSUPPORTED="UNSUPPORTED",W.OLD_VERSION="OLD_VERSION",W.SERVICE_DISABLED="SERVICE_DISABLED",W.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",W.SOCKET_CLOSED="SOCKET_CLOSED",W.ENDED="ENDED",W))(tr||{}),y=tr;var ir=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(ir||{}),pe=ir;var rr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(rr||{}),Be=rr;var ar=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(ar||{}),G=ar;var nr=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(nr||{}),we=nr;var sr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(sr||{}),_e=sr;var or=(M=>(M.TRANSMITTED_DATA="transmitted-data",M.ACCEPTED_CALL="accepted-call",M.HUNGUP="hungup",M.PARTICIPANT_ADDED="participant-added",M.PARTICIPANT_JOINED="participant-joined",M.CLOSED_CONVERSATION="closed-conversation",M.MEDIA_SETTINGS_CHANGED="media-settings-changed",M.PARTICIPANT_STATE_CHANGED="participant-state-changed",M.RATE_CALL_DATA="rate-call-data",M.FEATURE_SET_CHANGED="feature-set-changed",M.TOPOLOGY_CHANGED="topology-changed",M.PRODUCER_UPDATED="producer-updated",M.CONSUMER_ANSWERED="consumer-answered",M.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",M.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",M.SETTINGS_UPDATE="settings-update",M.VIDEO_QUALITY_UPDATE="video-quality-update",M.REGISTERED_PEER="registered-peer",M.SWITCH_MICRO="switch-micro",M.RECORD_STARTED="record-started",M.RECORD_STOPPED="record-stopped",M.REALLOC_CON="realloc-con",M.AUDIO_ACTIVITY="audio-activity",M.SPEAKER_CHANGED="speaker-changed",M.STALLED_ACTIVITY="stalled-activity",M.CHAT_MESSAGE="chat-message",M.CUSTOM_DATA="custom-data",M.ROLES_CHANGED="roles-changed",M.MUTE_PARTICIPANT="mute-participant",M.PIN_PARTICIPANT="pin-participant",M.OPTIONS_CHANGED="options-changed",M.NETWORK_STATUS="network-status",M.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",M.PROMOTE_PARTICIPANT="promote-participant",M.CHAT_ROOM_UPDATED="chat-room-updated",M.PROMOTION_APPROVED="promotion-approved",M.JOIN_LINK_CHANGED="join-link-changed",M))(or||{}),D=or;var cr=(I=>(I.ERROR="callError",I.DEVICES="callDevices",I.CALL_SPEC_ERROR="callSpecError",I.ICE_CONNECTION_STATE="callIceConnectionState",I.ICE_CONNECTION_TYPE="callIceConnectionType",I.ICE_RESTART="callIceRestart",I.PUSH="callPush",I.OUTGOING_CALL="callStart",I.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",I.JOIN_CONVERSATION="callJoinConversation",I.ACCEPTED_OUTGOING="callAcceptedOutgoing",I.ACCEPT_INCOMING="callAcceptIncoming",I.DECLINE_INCOMING="callDeclineIncoming",I.ACCEPT_CONCURRENT="callAcceptConcurrent",I.HANGUP="callHangup",I.MEDIA_STATUS="callMediaStatus",I.DEVICE_CHANGED="callDeviceChanged",I.SOCKET_ACTION="callSocketAction",I.ADD_PARTICIPANT="callAddParticipant",I.REMOVE_PARTICIPANT="callRemoveParticipant",I.POOR_CONNECTION="callPoorConnection",I.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",I.RELAY_POLICY="callForceRelay",I.PAT_ALLOCATED="patAllocate",I.PAT_DEALLOCATED="patDeallocate",I.PAT_ERROR="patError",I.PAT_WAITING_TIME_ERROR="patWaitingTimeError",I.PAT_OUTDATED_RESPONSE="patOutdatedResponse",I))(cr||{}),h=cr;var dr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(dr||{}),Me=dr;var pr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(pr||{}),lr=pr;function ur(a){switch(a){case 1:return"no-available-tracks";default:return"unknown-error"}}var mr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(mr||{}),Ge=mr;function _t(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var hr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(hr||{}),Y=hr;var Zt=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 _r=2*1024*1024,Ta=512*1024,gt=100*1024,Ca=5,ei="_okcls_logs_session_",Ia=3e4,gr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=_r;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(ei)!==0)continue;let i=e.getItem(t);if(!i){vr(t);continue}let r=Sr(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(gt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(ei,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(vr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>_r||this.length>Ca-1||this.size+e>this.available);)this.deleteOldestItem()}};function fr(){return`${ei}${Date.now()}`}function Sr(a){return new Blob([a]).size}function vr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function ti(){let a=We.toString();if(!Se.available||!a)return;let e=Sr(a);Se.cleanup(e);try{window.localStorage.setItem(kt,a)}catch(t){if(console.warn("Failed to write log to storage",t),Se.storageSize=Se.size+e,Se.cleanup(gt+e),Se.available>=gt+e){ti();return}if(e>gt){We.bisect(),ti();return}Se.storageSize=0;return}e>Ta&&(Se.add(kt,e),kt=fr(),We.clear(),Se.cleanup(gt))}function ii(){!Se.available||!We.length||ti()}function ya(a=!1){let e=[];try{let r=window.localStorage;for(let c of Se.items){let p=r.getItem(c.key);e.push(p)}let n=We.toString();n&&e.push(n)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(a)return t;let i=`logs_${Date.now()}.json`;return Ra(t,i),i}function Ra(a,e){let t=document.createElement("a"),i=new Blob([a],{type:"text/json"});t.href=URL.createObjectURL(i),t.download=e,t.click()}function Er(a,e){!Se.available||(We.push({t:Date.now(),l:a,d:e}),ai||(ai=window.setTimeout(()=>{ai=null,ii()},Ia)))}function ri(){Se||(Se=new gr,We=new Zt,kt=fr(),window.addEventListener("beforeunload",ii))}var Se,We,kt,ai=null;window.__VKCallsSDKLogs__=(a=!1)=>(Se||ri(),ii(),ya(a));var ni=He(require("@vkontakte/libvpx"));var ge=(c=>(c.INIT="init",c.READY="ready",c.FRAME="frame",c.ERROR="error",c.DEBUG="debug",c.LOG_ERROR="log_error",c))(ge||{});var u=class extends tt{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={};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 Ne=class{constructor(){this._worker=null}_createWorker(c,p){return o(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((l,m)=>{let R=i.join(","),k=new Blob([e,`exports.default(${R});`],{type:"application/javascript; charset=utf-8"}),z=window.URL.createObjectURL(k);this._worker=new Worker(z),this._worker.onmessage=se=>{switch(se.data.type){case ge.READY:l();break;case ge.ERROR:m(se.data.error);break;case ge.FRAME:t(se.data);break;case ge.DEBUG:s.debug(se.data.message);break;case ge.LOG_ERROR:u.log(h.ERROR,se.data.message);break}},this._sendToWorker(ge.INIT,r,n)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var rt=class extends Ne{init(e){return o(this,null,function*(){s.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var y=Object.defineProperty;var E=a=>y(a,"__esModule",{value:!0});var M=(a,p)=>{E(a);for(var e in p)y(a,e,{get:p[e],enumerable:!0})};var D={};M(D,{default:()=>V});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var V=(a,p)=>{let e=null,n=null,g=!0;function b(){return a({locateFile:p}).then(r=>n=r)}function s(r,m,l,R,x){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(x),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let d=e.getImageBuffer();if(!d){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let c=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(d.byteLength);if(i.set(d),R){let o=new ImageData(i,c,f);createImageBitmap(o,0,0,c,f).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:i.buffer,width:c,height:f},[i.buffer])}b().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return D;})();\n',t=>{if(t.error)s.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(ge.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:n,debug:s.enabled()},[t.buffer])}destroy(){this._removeWorker(),s.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var je=class extends Ne{init(e){return o(this,null,function*(){s.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var i=Object.defineProperty;var f=e=>i(e,"__esModule",{value:!0});var E=(e,d)=>{f(e);for(var a in d)i(e,a,{get:d[a],enumerable:!0})};var g={};E(g,{default:()=>V});var s=(a=>(a.VP9="vp09.00.50.08",a.VP8="vp8",a))(s||{}),o=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(o||{});var V=()=>{let e=null,d=!0;function a(){self.postMessage({type:o.READY})}function l(r,p,t,m=!1){(!e||d!==t)&&(d=t,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${t?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${t?"VP9":"VP8"}`}),e=new VideoDecoder({output:c=>{("createImageBitmap"in c?c.createImageBitmap():createImageBitmap(c)).then(n=>{self.postMessage({type:o.FRAME,data:n}),n.close()}).finally(()=>c.close())},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:t?s.VP9:s.VP8}));let u=new EncodedVideoChunk({type:m?"key":"delta",timestamp:r,data:p});e.decode(u)}self.onmessage=r=>{switch(r.data.type){case o.INIT:a();break;case o.FRAME:l(r.data.timestamp,r.data.data,r.data.isVP9,r.data.keyFrame);break}}};return g;})();\n',t=>{t.error?s.warn("WebCodecsDecoder",t.error):e(t.data)})})}decodeFrame(e,t,i,r=!1){this._sendToWorker(ge.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),s.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window&&"ImageBitmap"in window&&"createImageBitmap"in window}};var si="_okcls_",at=(()=>{try{let a=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(a,a),t=e.getItem(a)===a,e.removeItem(a),t?e:null}catch(a){return null}})();function Pa(a){let e=at?at.getItem(si+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function Ma(a,e){try{at&&at.setItem(si+a,JSON.stringify(e))}catch(t){}}function Aa(a){at&&at.removeItem(si+a)}var oi;(i=>{function a(r){return Pa(r)||null}i.get=a;function e(r,n){Ma(r,n)}i.set=e;function t(r){Aa(r)}i.remove=t})(oi||(oi={}));var Ve=oi;var nt=He(require("big-integer"));function Tr(a,e){if(a.isAudioEnabled!==e.isAudioEnabled||a.isVideoEnabled!==e.isVideoEnabled||a.isScreenSharingEnabled!==e.isScreenSharingEnabled||a.videoStreams.length!==e.videoStreams.length)return!1;for(let t of a.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function fe(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}var Cr=a=>a.stop(),Ir=a=>a.getTracks().forEach(Cr),ci=a=>a.getVideoTracks().forEach(Cr),yr=a=>a.getVideoTracks()[0].clone();var O=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(y).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,O)}};var Ee=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(Ee||{}),me=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(me||{}),di=class extends J{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=fe();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return o(this,arguments,function*(e=[pe.AUDIO]){if(this._stream)return;let t=e.includes(pe.VIDEO),i=e.includes(pe.AUDIO);if(!T.isBrowserSupported())throw new O(ie.UNSUPPORTED);try{this._stream=yield T.getUserMedia(t,i),this._mediaSettings.isVideoEnabled=t&&this._stream.getVideoTracks().filter(r=>r.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=i&&this._stream.getAudioTracks().filter(r=>r.enabled).length>0||!1}catch(r){throw new O(r)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t=!1){let i=this.getStream(),r=this._getSendAudioTrack(),n=this.getSendVideoTrack(t);if(!i||!r&&!n)throw new Error("No local stream found");r&&e.addTrack(r,i),n&&e.addTrack(n,i)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return o(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return o(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=S.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);navigator.mediaDevices.addEventListener("devicechange",()=>o(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),c=n&&n.groupId,p=this._stream.getVideoTracks()[0],l=p&&p.enabled&&p.getSettings(),m=l&&l.groupId;if(!c&&!m)return;let R=yield navigator.mediaDevices.enumerateDevices();!e&&c&&(e=!R.find(k=>k.groupId===c)),!t&&m&&(t=!R.find(k=>k.groupId===m)),i()}))}_changeVideoInput(e=null){return o(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield T.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{d.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),n=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),u.log(h.DEVICE_CHANGED,t),s.log("Video stream changed"),yield this._replaceLocalTrack(n),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(h.ERROR,"change_video"),s.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=yr(e)),t=this._trackVideoStreamBackup.clone(),ci(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),ci(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 T.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),u.log(h.DEVICE_CHANGED,"audio"),s.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(h.ERROR,"change_audio"),s.error("Microphone change failed",t),t}})}_changeScreen(e){return o(this,null,function*(){try{if(e=e||(yield T.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=d.consumerScreenTrack?t:yield this._videoEffect(null,t);u.log(h.DEVICE_CHANGED,"screen"),s.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,d.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=d.consumerScreenDataChannel?T.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(h.ERROR,"screen"),s.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(h.DEVICE_CHANGED,`effect_${e}`),d.videoEffects.setEffect(e,t)}catch(i){return s.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){d.videoEffects&&(this._effect=null,d.videoEffects.destroy()),this._stream&&(Ir(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 T.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=T.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return o(this,null,function*(){if(!this._stream)return;let t;e?t=(yield T.getUserAudio()).getAudioTracks()[0]:t=T.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return 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 pi;(Vi=>{function a(v,C,b,I,A=!1){let ye=/[\r\n]+/,Q=`\r
8
+ `;if(!C&&!b&&!I)return A?N(v.split(ye)).join(Q):v;function N($){let Oe=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],he="a=rtcp-fb:111",ne=$.findIndex(Z=>Z.startsWith(he));return~ne&&($[ne]=$[ne]+Q+Oe.join(Q)),$}function X($,Oe,he){let ne=$.split(" "),Z=ne.slice(0,3),ue;for(ue=3;ue<ne.length;ue++)he.includes(ne[ue])&&Z.push(ne[ue]);for(ue=3;ue<ne.length;ue++)!he.includes(ne[ue])&&!Oe.includes(ne[ue])&&Z.push(ne[ue]);return Z.join(" ")}function P($,Oe){let he=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),ne,Z=[];for(ne=0;ne<$.length;++ne){let ue=$[ne].match(he);ue&&ue.length===3&&ue[2]===Oe&&Z.push(ue[1])}return Z}function j($,Oe,he,ne){let Z,ue="m="+Oe;for(Z=0;Z<$.length;++Z)if($[Z].startsWith(ue)){$[Z]=X($[Z],he,ne);break}}let de=[],M=v.split(ye);(b||C)&&(de=P(M,"H264"));let Le=[];if(I&&(Le=P(M,"VP9")),b){let $=de.slice(0),Oe=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),he;for(he=0;he<M.length;++he){let Z=M[he].match(Oe);Z&&Z.length===3&&$.includes(Z[2])&&$.push(Z[1])}let ne=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(he=M.length;he--;){let Z=M[he].match(ne);Z&&Z.length===3&&$.includes(Z[2])&&M.splice(he,1)}j(M,"video",$,[])}else C&&j(M,"video",[],de);return I&&j(M,"video",[],Le),A&&N(M),M.join(Q)}Vi.patchSDP=a;function e(v){return v?`${v.type||"WEB_SOCKET"}_${v.id}`:"_"}Vi.getPeerIdString=e;function t(v,C){return v&&v.id===C.id&&(v.type||"WEB_SOCKET")===(C.type||"WEB_SOCKET")}Vi.comparePeerId=t;function i(v){return o(this,null,function*(){return!v||!v.getStats?Promise.resolve(null):v.getStats(null).then(C=>{let b=null,I=null;if(C.forEach(A=>{A.type==="transport"&&A.selectedCandidatePairId?I=C.get(A.selectedCandidatePairId):A.type==="candidate-pair"&&A.state==="succeeded"&&!I&&(!A.hasOwnProperty("selected")||A.selected)&&(I=A)}),I&&I.localCandidateId){let A=C.get(I.localCandidateId);A&&(b={type:A.candidateType,ip:A.ip||A.ipAddress,port:A.port||A.portNumber})}return b}).catch(()=>null)})}Vi.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function c(v,C){let b=String(v);return n.test(b)?(s.warn(`Already composite id [${v}] type supplied [${C}]`),b):C===Y.GROUP?"g"+b:C===Y.USER?"u"+b:(s.warn(`Unknown type [${C}] for id [${v}]`),b.match(r)?"u"+b:b)}Vi.composeId=c;function p(v){return c(v.id,v.idType||Y.USER)}Vi.composeParticipantId=p;function l(v){return v.participant?p(v.participant):c(v.participantId,v.participantType||Y.USER)}Vi.composeMessageId=l;function m(v){let C=String(v),b=C.match(n);return b?{id:Number(b[2]),type:b[1]==="g"?Y.GROUP:Y.USER}:(s.warn(`Unsupported compositeId [${v}]`),{id:Number(C),type:Y.USER})}Vi.decomposeId=m;function R(){let v="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),C=new Array(36),b=0,I,A;for(A=0;A<36;A++)A===8||A===13||A===18||A===23?C[A]="-":A===14?C[A]="4":(b<=2&&(b=33554432+Math.random()*16777216|0),I=b&15,b=b>>4,C[A]=v[A===19?I&3|8:I]);return C.join("")}Vi.uuid=R;function k(v,C){let b;function I(){let A=this,ye=arguments;b&&window.clearTimeout(b),b=window.setTimeout(()=>{v.apply(A,ye)},C)}return I}Vi.throttle=k;function z(v){let C="",b=v.split(`
9
+ `);for(let Q of b)if(Q.startsWith("a=fingerprint")){let N=Q.split(" ");if(N.length===2){C=N[1];break}}if(!C)return nt.default.minusOne;let I=C.split(":"),A=nt.default.zero;for(let Q=Math.min(7,I.length-1);Q>=0;Q--){let N=(0,nt.default)(I[Q],16);A=A.shiftLeft(8).or(N)}return((Q,N)=>{let X=N.value;if(typeof X=="bigint")return(0,nt.default)(BigInt.asIntN(Q,X));let P=nt.default.one.shiftLeft(Q),j=N.and(P.subtract(1));return j.greaterOrEquals(P.subtract(j))?j.subtract(P):j})(64,A)}Vi.sdpFingerprint=z;function se(v){return o(this,null,function*(){return new Promise(C=>window.setTimeout(C,v))})}Vi.delay=se;function B(v,C,b){let I=[];return v.getSenders().forEach(A=>q(C,A,A.track,b,I)),I}Vi.applySettings=B;function q(v,C,b,I,A){if(v&&b&&b.kind===me.video){let ye=b.getSettings();if(ye){let Q=v.maxBitrateK?v.maxBitrateK*1024:null,N=ye.width,X=ye.height,P=N&&X&&v.maxDimension?Math.max(1,Math.max(N,X)/v.maxDimension):null,j=v.maxFramerate?v.maxFramerate:null,de=v.degradationPreference?v.degradationPreference:"balanced",M=I[b.id];if(M&&M.bitrate===Q&&M.scaleResolutionDownBy===P&&M.maxFramerate===j&&M.degradationPreference===de){A[b.id]=M;return}A[b.id]={bitrate:Q,scaleResolutionDownBy:P,maxFramerate:j,degradationPreference:de};let Le=C.getParameters();Le.encodings||(Le.encodings=[{}]),Le.encodings.forEach($=>{Q?$.maxBitrate=Q:delete $.maxBitrate,P?$.scaleResolutionDownBy=P:delete $.scaleResolutionDownBy,j?$.maxFramerate=j:delete $.maxFramerate}),Le.degradationPreference=de,C.setParameters(Le)}}}Vi.applyVideoTrackSettings=q;function ae(v,C){Array.isArray(C)||(C=[C]);for(let b of C)if(v.includes(b))return!0;return!1}Vi.includesOneOf=ae;function oe(v){var C;return Object.entries(((C=v.participantState)==null?void 0:C.state)||{}).reduce((b,[I,A])=>(v.participantState&&(b[I]={ts:v.participantState.stateUpdateTs[I],state:A}),b),{})}Vi.mapParticipantState=oe;function Ze(v){return Object.entries(v).reduce((C,[b,{state:I}])=>(C[b]=I,C),{})}Vi.mapLegacyParticipantState=Ze;function le(v){return v.map(C=>{let b={uid:C.externalId,mediaSettings:C.mediaSettings,status:C.status,muteStates:C.muteStates,unmuteOptions:C.unmuteOptions};return d.participantStateMapped&&(b.participantState=C.participantState),b})}Vi.mapSharedParticipants=le;function W(v,C){let b=Object.keys(v),I=Object.keys(C);if(b.length!==I.length)return!1;for(let A of b)if(!I.hasOwnProperty(A)||v[A].state!==C[A].state||v[A].ts!==C[A].ts)return!1;return!0}Vi.isEqualParticipantState=W;function Pe(v,C){let b=Object.keys(v),I=Object.keys(C);if(b.length!==I.length)return!1;for(let A of b)if(!C.hasOwnProperty(A)||v[A]!==C[A])return!1;return!0}Vi.isObjectsEquals=Pe;function ut(v,C){if(v.length!==C.length)return!1;for(let b of v)if(C.indexOf(b)<0)return!1;return!0}Vi.isArraysEquals=ut;function Bi(v){return!Object.keys(v).length}Vi.isEmptyObject=Bi})(pi||(pi={}));var S=pi;var Ke=null,li=null,wt=[],Nt=[],ui=[],ft=null,St=null,mi=null,hi=!1,_i=!1,xt,st,Lt,Rr=!1,br=!1,gi=null,fi="",Ut=[],Si=null,Pr=navigator.appVersion,Da=navigator.appName,Te=navigator.userAgent,vi=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(vi||{}),vt=class{constructor(e,t=!1,i=d.videoMaxWidth,r=d.videoMaxHeight){let n=!1;if(e){n={noiseSuppression:d.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let p;St&&(p=St.deviceId),typeof e=="string"&&(p=e),p&&(n.deviceId={exact:p})}let c=!1;if(t){c={width:{min:d.videoMinWidth,max:i,ideal:i},height:{min:d.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:d.videoAspectRatio},frameRate:{ideal:d.videoFrameRate}};let p;ft&&(p=ft.deviceId),typeof t=="string"&&(p=t),p&&(c.deviceId={exact:p}),d.videoFacingMode&&(c.facingMode={exact:d.videoFacingMode})}this.audio=n,this.video=c,this.needVideo=!!c}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},Mr=class extends vt{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=d.screenFrameRate}};function Oa(){return o(this,null,function*(){Ke=null,yield Bt()})}function ka(){Ke=null,Bt().then(()=>f.onDeviceChange())}function Bt(){return o(this,null,function*(){return Ke||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!li&&navigator.mediaDevices.addEventListener&&(li=S.throttle(ka,1e3),navigator.mediaDevices.addEventListener("devicechange",li)),Ke=navigator.mediaDevices.enumerateDevices().then(a=>{wt=a.filter(r=>r.kind==="videoinput"?(r.label&&(hi=!0),!0):!1),Nt=a.filter(r=>r.kind==="audioinput"?(r.label?_i=!0:$e.isMobile()&&$e.browserName()==="Firefox"&&(_i=hi),!0):!1),ui=a.filter(r=>r.kind==="audiooutput");let e=Ve.get("videoinput"),t=Ve.get("audioinput"),i=Ve.get("audiooutput");return ft=wt.find(r=>r.deviceId===e)||null,St=Nt.find(r=>r.deviceId===t)||null,mi=ui.find(r=>r.deviceId===i)||null,Ke=Promise.resolve(a),a}).catch(()=>(Ke=null,[]))))})}function wa(){return o(this,null,function*(){return $e.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(Rr=!0),/^a=mid:0$/m.test(t.sdp)&&(br=!0),a()}).catch(a)}):Promise.resolve()})}function Vt(a,e){return o(this,null,function*(){s.debug("Try to get media",a.getNative());let t=$e.hasPermissions(a.isVideo());!t&&!e&&f.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield Oa()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?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 Vt(a.simplify(),e);let r=e||ie.UNKNOWN;throw f.onPermissionsError(r),r}})}function Na(a){return o(this,null,function*(){s.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&&(s.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 Ei(){return Ut.length||(Ut=(()=>{let a,e=!1,t=0,i=Te.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return a=/\brv[ :]+(\d+)/g.exec(Te),["IE",a&&a[1]||"Unknown",e,t];if(i[1]==="Safari"){if(a=Te.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(a=Te.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,a[1]];if(a=Te.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t];if(a=Te.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t];if(a=Te.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),a=Te.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t];if(a=Te.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t];if(a=Te.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t];if(a=Te.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t]}return a=Te.match(/version\/(\d+)/i),[i[2]?i[1]:Da,a&&a[1]||i[2]||Pr,e,t]})()),Ut}var $e;(Q=>{function a(){return o(this,null,function*(){return yield wa(),Bt()})}Q.init=a;function e(){return wt}Q.getCameras=e;function t(){return Nt}Q.getMicrophones=t;function i(){return ui}Q.getOutput=i;function r(){return wt.length>0}Q.hasCamera=r;function n(){return Nt.length>0}Q.hasMicrophone=n;function c(){return ft}Q.getSavedCamera=c;function p(){return St}Q.getSavedMicrophone=p;function l(){return mi}Q.getSavedOutput=l;function m(){return hi}Q.hasCameraPermission=m;function R(){return _i}Q.hasMicrophonePermission=R;function k(N=!1){return R()?r()&&N?m():!0:!1}Q.hasPermissions=k;function z(N=!1,X=!0){return o(this,null,function*(){let P=n()&&X,j=r()&&N,de;if(!P&&!j)de=new MediaStream;else try{de=yield Vt(new vt(P,j))}catch(M){de=new MediaStream}return de.getVideoTracks().length||de.addTrack(Ze()),de.getAudioTracks().length||de.addTrack(oe()),de})}Q.getUserMedia=z;function se(){return o(this,null,function*(){return Na(new Mr(window.screen.width,window.screen.height))})}Q.getScreenMedia=se;function B(N,X=!1){return o(this,null,function*(){let P=X?d.videoEffectMaxWidth:d.videoMaxWidth,j=X?d.videoEffectMaxHeight:d.videoMaxHeight;return Vt(new vt(!1,N||!0,P,j))})}Q.getUserVideo=B;function q(N){return o(this,null,function*(){return Vt(new vt(N||!0,!1))})}Q.getUserAudio=q;function ae(N,X){return o(this,null,function*(){let j=(yield Bt()).find(de=>de.kind===N&&de.deviceId===X);return j?(N==="videoinput"?ft=j:N==="audioinput"?St=j:N==="audiooutput"&&(mi=j),Ve.set(N,X),j):null})}Q.saveDeviceId=ae;function oe(){if(!Lt||Lt.readyState==="ended"){let N=ye(),X=N.createMediaStreamDestination(),P=N.createGain();P.gain.value=1e-5,P.connect(X),P.connect(N.destination);let j=N.createOscillator();j.type="sine",j.frequency.value=0,j.connect(P),j.start(),Lt=X.stream.getAudioTracks()[0]}return Object.assign(Lt.clone(),{enabled:!1})}Q.getSilentMediaTrack=oe;function Ze(N=d.videoMinWidth,X=d.videoMinHeight){return st||(st=document.createElement("canvas"),st.getContext("2d")),st.width=N,st.height=X,(!xt||xt.readyState==="ended")&&(xt=st.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(xt.clone(),{enabled:!1})}Q.getBlackMediaTrack=Ze;function le(){if(b()==="Edge"&&I()<70)return!1;try{let N=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&N.RTCPeerConnection&&N.RTCIceCandidate&&N.RTCSessionDescription&&N.HTMLCanvasElement&&N.HTMLCanvasElement.prototype.captureStream&&N.RTCRtpSender&&N.RTCRtpSender.prototype.replaceTrack&&N.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(N){return!1}}Q.isBrowserSupported=le;function W(){return!!navigator.mediaDevices.getDisplayMedia}Q.isScreenCapturingSupported=W;function Pe(){return Rr}Q.canVP8=Pe;function ut(){return br}Q.isUnifiedPlan=ut;function Bi(){return Q.browserName()==="Opera"&&Q.os()==="Windows"}Q.isBrokenH264=Bi;function Vi(){return!(Q.baseChromeVersion()&&Q.isMobile())}Q.canPreferH264=Vi;function v(){return fi||(fi=(()=>{let N={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let X in N)if(N.hasOwnProperty(X)&&N[X].test(Te))return X;return"Unknown"})()),fi}Q.os=v;function C(){return gi===null&&(gi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Pr)),gi}Q.isMobile=C;function b(){return Ei()[0]}Q.browserName=b;function I(){return Ei()[1]}Q.browserVersion=I;function A(){return Ei()[3]}Q.baseChromeVersion=A;function ye(){return Si||(Si=new(window.AudioContext||window.webkitAudioContext)),Si}Q.getAudioContext=ye})($e||($e={}));var T=$e;var Ar=He(require("bit-buffer"));var xa=65536,qe=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(s.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%xa!==e.sequence){s.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:n}=qe.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:n})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((n,c)=>n+c.data.byteLength,0),i=new Uint8Array(t),r=0;for(let n of e)i.set(new Uint8Array(n.data),r),r+=n.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new Ar.BitStream(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),c=i.readBits(1)<<1|r;return c===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,c>=2&&i.index++,i.readBits(3)!==7?(i.index++,(c===1||c===3)&&(i.index+=3)):(c===1||c===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Et=class extends qe{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;s.debug(`StreamBuilder started for participant [${e}]`),this._useImageBitmap="ImageBitmap"in window,je.isBrowserSupported()?this._decoder=new je:this._decoder=new rt,this._decoder.init(i=>this._drawImage(i)).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}_drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._removeStream(),s.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(T.browserName()==="Safari"&&T.browserVersion()>=15)}};var Ft=1,La=1,Dr=0,Or=11,kr=1,wr=2,Nr=4,xr=8;function Lr(a,e,t,i,r,n,c){let p=0;e&&(p|=kr),t&&(p|=wr),i&&(p|=Nr),c||(p|=xr);let l=new ArrayBuffer(Or),m=new DataView(l);if(m.setUint8(0,Ft),m.setUint16(1,r),m.setUint32(3,a),m.setUint8(7,n?1:0),m.setUint16(8,Dr),m.setUint8(10,p),!c)return l;let R=new Uint8Array(l.byteLength+c.byteLength);return R.set(new Uint8Array(l),0),R.set(new Uint8Array(c),l.byteLength),R.buffer}function Ur(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,c=e.getUint16(8),p=e.getUint8(10),l=!!(p&kr),m=!!(p&wr),R=!!(p&Nr),k=!!(p&xr);if(t!==Ft)throw new Error(`Unexpected protocol version. Got ${t}, expected ${Ft}`);return{timestamp:r,start:l,end:m,keyframe:R,sequence:i,isVP9:n,ssrc:c,eos:k,data:a.slice(Or)}}function Br(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==Ft||e.getUint8(1)!==La||e.getUint16(2)!==Dr)}var _=He(require("simple-ebml-builder"));var Ua=Gi(2,15)-1,Ti=1,Ba=5,Va=5;var Ht=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),s.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=Ht._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return _.build(e[0])}else return new Uint8Array;let t=e.reduce((n,c)=>n+c.countSize(),0),i=new Uint8Array(t),r=0;for(let n of e){let c=_.build(n);i.set(c,r),r+=c.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var n;let e=(n=this._sourceBuffer)==null?void 0:n.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-Ba);r-i>Va&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},Ae=class extends qe{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;s.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return _.element(_.ID.EBML,[_.element(_.ID.EBMLVersion,_.number(1)),_.element(_.ID.EBMLReadVersion,_.number(1)),_.element(_.ID.EBMLMaxIDLength,_.number(4)),_.element(_.ID.EBMLMaxSizeLength,_.number(8)),_.element(_.ID.DocType,_.string("webm")),_.element(_.ID.DocTypeVersion,_.number(2)),_.element(_.ID.DocTypeReadVersion,_.number(2))])}static _genSegmentHeader(e,t,i){let r=_.element(_.ID.Info,[_.element(_.ID.TimecodeScale,_.number(1e6)),_.element(_.ID.MuxingApp,_.string("vk-webm-builder")),_.element(_.ID.WritingApp,_.string("vk-webm-builder"))]),n=[_.element(_.ID.PixelWidth,_.number(e)),_.element(_.ID.PixelHeight,_.number(t))],c=_.element(_.ID.Tracks,_.element(_.ID.TrackEntry,[_.element(_.ID.TrackNumber,_.number(Ti)),_.element(_.ID.TrackUID,_.number(Ti)),_.element(_.ID.TrackType,_.number(1)),_.element(_.ID.FlagLacing,_.number(0)),_.element(_.ID.DefaultDuration,_.number(1e9)),_.element(_.ID.CodecID,_.string(`V_${i.toUpperCase()}`)),_.element(_.ID.Video,n)]));return _.unknownSizeElement(_.ID.Segment,[r,c])}static _genClusterHeader(e){return _.unknownSizeElement(_.ID.Cluster,[_.element(_.ID.Timecode,_.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new Ht(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){s.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=()=>s.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,s.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,s.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let c=Ae._genWebmHeader();this._mediaBuffer.append(c);let p=Ae._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(p),this._mediaBuffer.cleanup()}let r=Math.round(i-this._clusterStartTime);if(r>Ua&&(this._clusterStartTime=i,r=0),r===0){s.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let c=Ae._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(c)}let n=_.element(_.ID.SimpleBlock,[_.vintEncodedNumber(Ti),_.bytes(Ae._intToU16BE(r)),_.number((e.keyframe?1:0)<<7),_.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),s.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var ot=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};s.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=n=>this._onDataChannelMessage(n.data)}_onDataChannelMessage(e){var n,c;let t=Ur(e),i=(c=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:c.participantId;if(!i){s.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&&Ae.isBrowserSupported()?r=new Ae(i,p):r=new Et(i,p),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,s.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(je.isBrowserSupported()||rt.isBrowserSupported())&&(Et.isBrowserSupported()||Ae.isBrowserSupported())}};var Ci=He(require("@vkontakte/libvpx"));var Fa=1e3,Tt=class extends Ne{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(),c=()=>i(new Error("Autoplay is disabled"));n?n.catch(c):c()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return 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;s.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})},[Ci.default,Ci.default.getUrl],{isVP9:this.isVP9(),debug:s.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(ge.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},Fa),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),s.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var ct=class extends Ne{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;s.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var b=Object.defineProperty;var g=i=>b(i,"__esModule",{value:!0});var F=(i,n)=>{g(i);for(var r in n)b(i,r,{get:n[r],enumerable:!0})};var A={};F(A,{default:()=>h});var l=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(l||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,n,r,c,s,f,t,a=null,p=0,u=!1;function V(e){n=e.readable,r=n.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&E(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),n.cancel();return}a=R,E(R,e)}}))}function E(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
11
+ `,r=>{var n;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(n=r.data)==null?void 0:n.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:d.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(ge.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),s.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var Ha=16*1024,Ga=11,Vr=Ha-Ga,Wa=65536,Ii=0,dt=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;s.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,n)=>{if(!this._destroyed){if(!r){s.warn("requestFrame failed, keyFrame: "+this._needKeyframe,n),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(c=>{s.warn("sendFrame failed",c),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};ct.isBrowserSupported()?this._encoder=new ct(e,i):this._encoder=new Tt(e,i),this._datachannel.onmessage=r=>{Br(r.data)&&(s.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>s.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,n){let c=Lr(e,t,i,r,Ii,this._encoder.isVP9(),n);return Ii=(Ii+1)%Wa,c}_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+Vr),c=e.data.byteLength<=t+n.byteLength,p=this._wrapHeader(e.timestamp,!t,c,e.type==="key",n);this._datachannel.onbufferedamountlow=c?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(p)}catch(l){s.warn("Error send data to DataChannel",l),r();return}c||window.setTimeout(()=>this._sendChunk(e,t+Vr,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),s.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return ct.isBrowserSupported()||Tt.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 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")&&(ee.accessToken=e.apiAuth.accessToken,ee.sessionKey=e.apiAuth.sessionKey,ee.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(g._params,e)}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.5.1"}static get debug(){return!1}static get protocolVersion(){return 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 apiAppId(){return 42}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.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 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 producerNotificationDataChannel(){return g._params.producerNotificationDataChannel&&ot.isBrowserSupported()}static get producerCommandDataChannel(){return g._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return g._params.consumerScreenDataChannel&&dt.isBrowserSupported()}static get producerScreenDataChannel(){return g._params.producerScreenDataChannel&&g.producerNotificationDataChannel}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&&g.producerScreenDataChannel}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 batchParticipantsOnStart(){return g._params.batchParticipantsOnStart}static get participantStateMapped(){return g._params.participantStateMapped}},d=g;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,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!1,producerScreenTrack:!1,videoTracksCount:0,movieShare:!1,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!1};var K=(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))(K||{});function V(a,...e){let t=d.get(a);t&&setTimeout(t,0,...e)}function xe(a){return Object.assign({},a)}function pt(a){return a.slice()}var yi;(ue=>{function a(E,x){V("onLocalStream",E,xe(x))}ue.onLocalStream=a;function e(E,x){V("onScreenStream",E,xe(x))}ue.onScreenStream=e;function t(E,x){V("onLocalStreamUpdate",xe(E),x)}ue.onLocalStreamUpdate=t;function i(E){V("onLocalStatus",E)}ue.onLocalStatus=i;function r(E,x){V("onRemoteStream",E,x)}ue.onRemoteStream=r;function n(E,x,ce){V("onRemoteLive",E,x,ce)}ue.onRemoteLive=n;function c(E,x){V("onRemoteScreenStream",E,x)}ue.onRemoteScreenStream=c;function p(E,x,ce,mt){V("onConversation",E,xe(x),xe(ce),mt)}ue.onConversation=p;function l(E,x){V("onRemoteMediaSettings",E,xe(x))}ue.onRemoteMediaSettings=l;function m(E,x){V("onRemoteParticipantState",E,xe(x))}ue.onRemoteParticipantState=m;function R(E,x,ce=null){V("onRemoteStatus",E,x,ce)}ue.onRemoteStatus=R;function k(E,x,ce=null){V("onParticipantStatus",E,x,ce)}ue.onParticipantStatus=k;function z(){V("onPermissionsRequested")}ue.onPermissionsRequested=z;function se(E){V("onPermissionsError",E)}ue.onPermissionsError=se;function B(E){V("onRemoteRemoved",E)}ue.onRemoteRemoved=B;function q(E,x,ce){V("onCallState",E,x,xe(ce))}ue.onCallState=q;function ae(E,x){V("onDeviceSwitched",E,x)}ue.onDeviceSwitched=ae;function oe(E,x,ce,mt=!1,Qt=!1,Xt=null,ma=null){V("onMuteStates",xe(E),pt(x),pt(ce),mt,Qt,Xt,ma)}ue.onMuteStates=oe;function Ze(E,x){V("onRolesChanged",E,pt(x))}ue.onRolesChanged=Ze;function le(E){V("onLocalRolesChanged",pt(E))}ue.onLocalRolesChanged=le;function W(E,x){V("onPinnedParticipant",E,x)}ue.onPinnedParticipant=W;function Pe(E){V("onLocalPin",E)}ue.onLocalPin=Pe;function ut(E){V("onOptionsChanged",pt(E))}ue.onOptionsChanged=ut;function Bi(){V("onCallAccepted")}ue.onCallAccepted=Bi;function Vi(){V("onRateNeeded")}ue.onRateNeeded=Vi;function v(E){V("onSpeakerChanged",E)}ue.onSpeakerChanged=v;function C(E){V("onVolumesDetected",pt(E))}ue.onVolumesDetected=C;function b(E,x){V("onLocalVolume",E,x)}ue.onLocalVolume=b;function I(E,x){V("onJoinStatus",E,x)}ue.onJoinStatus=I;function A(E,x){V("onHangup",E,x)}ue.onHangup=A;function ye(E){V("onMultipartyChatCreated",xe(E))}ue.onMultipartyChatCreated=ye;function Q(){V("onDeviceChange")}ue.onDeviceChange=Q;function N(E){V("onFingerprintChange",E)}ue.onFingerprintChange=N;function X(){V("onTokenExpired")}ue.onTokenExpired=X;function P(E,x,ce=!1){V("onChatMessage",E,x,ce)}ue.onChatMessage=P;function j(E,x,ce=!1){V("onCustomData",E,x,ce)}ue.onCustomData=j;function de(E,x,ce,mt,Qt,Xt){V("onRecordStarted",E,x,ce,mt,Qt,Xt)}ue.onRecordStarted=de;function M(){V("onRecordStopped")}ue.onRecordStopped=M;function Le(E){V("onLocalNetworkStatusChanged",E)}ue.onLocalNetworkStatusChanged=Le;function $(E){V("onNetworkStatusChanged",E)}ue.onNetworkStatusChanged=$;function Oe(E,...x){V("onDebugMessage",E,...x)}ue.onDebugMessage=Oe;function he(E,x){let ce=Object.assign({},E,{memory:x});V("onStatistics",ce)}ue.onStatistics=he;function ne(){V("onAutoplayError")}ue.onAutoplayError=ne;function Z(E,x,ce){V("onChatRoomUpdated",E,x,ce)}ue.onChatRoomUpdated=Z})(yi||(yi={}));var f=yi;var Ri=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(Ri||{}),bi;(le=>{let a="📞",e=(W,...Pe)=>{f.onDebugMessage(W,...Pe)},t=!1,i=(W,Pe)=>(...ut)=>{W(...ut),Er(Pe,ut)},r=console.debug.bind(console,a),n=console.log.bind(console,a),c=console.warn.bind(console,a),p=console.error.bind(console,a),l=e.bind(null,"DEBUG"),m=e.bind(null,"LOG"),R=e.bind(null,"WARN"),k=e.bind(null,"ERROR");le.debug=l,le.log=m,le.warn=R,le.error=k;function ae(){return t}le.enabled=ae;function oe(W){t=W,d.debugLog&&ri(),W?(le.debug=d.debugLog?i(r,"DEBUG"):r,le.log=d.debugLog?i(n,"LOG"):n,le.warn=d.debugLog?i(c,"WARN"):c,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(R,"WARN"):R,le.error=d.debugLog?i(k,"ERROR"):k)}le.toggle=oe;function Ze(W,...Pe){switch(W){case"DEBUG":le.debug(...Pe);break;case"LOG":le.log(...Pe);break;case"WARN":le.warn(...Pe);break;case"ERROR":le.error(...Pe);break}}le.send=Ze})(bi||(bi={}));var s=bi;var Je=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(Je||{}),te;(p=>{function a(l){return l.length?typeof l[0]=="object"?l:l.map(m=>e(m)):[]}p.fromIds=a;function e(l,m="USER"){return{id:l,type:m}}p.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}p.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}p.toString=i;function r(l,m="USER"){return i(e(l,m))}p.fromIdToString=r;function n(l){try{return JSON.parse(l)}catch(m){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}p.fromString=n;function c(l,m){return l.id===m.id&&l.type===m.type}p.compare=c})(te||(te={}));var ve=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(ve||{}),Pi=":",Fr="s",Hr="m";function Ye(a){return a.participantId+(a.mediaType?Pi+Fr+a.mediaType:"")+(a.streamName?Pi+Hr+a.streamName:"")}function Ct(a){let e=a.split(Pi),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i={participantId:t,mediaType:null};for(let r of e)switch(r.charAt(0)){case Fr:i.mediaType=ja(r.slice(1));break;case Hr:i.streamName=r.slice(1);break;default:throw new Error("Unexpected parameter type "+r.charAt(0)+" in stream description "+a)}return i}function ja(a){for(let e of Object.keys(ve))if(e===a)return ve[e];return null}function Mi(a,e){return a===null||e===null?a===null&&e===null:!(a.maxDimension!==e.maxDimension||a.maxBitrateK!==e.maxBitrateK||a.maxFramerate!==e.maxFramerate||a.degradationPreference!==e.degradationPreference)}function Gt(a,e){return!(!Mi(a.camera,e.camera)||!Mi(a.screenSharing,e.screenSharing))}function Ai(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function Gr(a){try{return btoa(JSON.stringify(a))}catch(e){s.warn("WaitingParticipant: failed convert to string",a,e)}return null}function Wr(a){try{return JSON.parse(atob(a))}catch(e){s.warn("WaitingParticipant: failed convert from string",a,e)}return null}var It=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,u.log(h.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,u.log(h.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(s.log("Failed to fix RV"),u.log(h.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(s.log("Fixed RV"),u.log(h.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,s.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===me.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Wt=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var c;if(!((c=this._output)==null?void 0:c.audioTrack))return;let e=T.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{s.warn("Error on play audio"),f.onAutoplayError()},r=p=>{t.srcObject=new MediaStream([p]),t.load();let l=t.play();l?l.catch(i):i()},n=()=>{var l;s.debug("Recover audio playback");let p=(l=this._output)==null?void 0:l.audioTrack;p?r(p):s.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=T.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw u.log(h.ERROR,"change_output"),s.error("Output change failed",r),r}})}};var Ka=90,$a=3,jt=class extends J{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),f.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>Ka?s.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=$a)&&(s.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var qa=44100,yt=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=T.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=qa/this._fftBins.length,t=Math.ceil(d.voiceParams.minFreq/e),i=Math.floor(d.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((n,c)=>n+c,0)/e.length/255,r=this._lastSmoothedLevel*d.voiceParams.smoothing+i*(1-d.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var Kt=class extends J{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&f.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,Ee.SOURCE_CHANGED,r=>{r.kind===me.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new yt("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var Ja=1e3;function Ce(a,e,t=0){return e in a&&a[e]?a[e]:t}function jr(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function Fe(a,e){return t=>t[a]===e}function Ya(a){return(e,t)=>e[a]-t[a]}function $t(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function za(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Qa(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Di(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=Qa(t[1])?Di(t[1]):t[1],e),{})}function Xa(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function Za(a){return 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(Xa).then(za)})}function en(a){let e=a.filter(Fe("type","candidate-pair")).sort(Ya("priority")).find(jr(Fe("nominated",!0),Fe("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=a.find(Fe("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=a.find(Fe("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),Di(t)}function tn(a,e){let t=$t("id",a),i=a.filter(jr(Fe("type","inbound-rtp"),Fe("type","outbound-rtp")));T.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,c)=>{if(!n[c.ssrc])n[c.ssrc]=c;else{let p=Object.assign({},n[c.ssrc],c),l=n[c.ssrc].isRemote?c:n[c.ssrc];p.id=l.id,p.type=l.type,delete p.isRemote,delete p.remoteId,n[p.ssrc]=p}return n},{})));let r={};if(T.browserName()==="Safari"){let n=a.filter(Fe("type","track"));r=$t("trackIdentifier",n)}return i.map(n=>{let c=Number(n.ssrc),p=n.mediaType||n.kind,l=n.trackId,m=n.type,R=n.codecId;if(T.browserName()==="Safari"){let ae=/^.+_([\d]+)$/.exec(n.id);if(ae&&(c=parseInt(ae[1],10)),p=n.id.indexOf("Audio")>0?"audio":"video",e[c]){let oe=p+"-"+e[c];r[oe]&&(l=r[oe].id)}}if(!m||!c||!p)return null;let k=Ce(n,"framesDecoded"),z=Ce(n,"totalInterFrameDelay"),B=(Ce(n,"totalSquaredInterFrameDelay")-z*z/k)/k,q={ssrc:c,type:m,kind:p,bytesReceived:Ce(n,"bytesReceived"),bytesSent:Ce(n,"bytesSent"),jitter:Ce(n,"jitter"),packetsLost:Ce(n,"packetsLost"),packetsReceived:Ce(n,"packetsReceived"),packetsSent:Ce(n,"packetsSent"),fractionLost:Ce(n,"fractionLost"),pliCount:Ce(n,"pliCount"),firCount:Ce(n,"firCount"),nackCount:Ce(n,"nackCount"),userId:e[c],interframeDelayVariance:B};if(R&&t[R]){let ae=t[R];q.clockRate=ae.clockRate,q.mimeType=ae.mimeType}if(l&&t[l]){let ae=t[l];q.frameHeight=ae.frameHeight,q.frameWidth=ae.frameWidth,q.framesDecoded=ae.framesDecoded,q.framesReceived=ae.framesReceived,q.framesDropped=ae.framesDropped}return Di(q)}).filter(n=>!!n)}function rn(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=$t("ssrc",a.rtps),i=$t("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let c=t[n],p=i[n];if(!(!c||!p)){if(c.bytesReceived&&c.bytesReceived>p.bytesReceived&&(c.bandwidth=Math.round((c.bytesReceived-p.bytesReceived)/r)),c.bytesSent&&c.bytesSent>p.bytesSent&&(c.bandwidth=Math.round((c.bytesSent-p.bytesSent)/r)),c.packetsReceived)if(c.packetsReceived>p.packetsReceived||c.packetsLost>p.packetsLost){let l=c.packetsLost-p.packetsLost,m=c.packetsReceived-p.packetsReceived;c.packetLoss=parseFloat((100*l/(l+m)).toFixed(2))}else c.packetLoss=0;c.framesDropped&&p.framesDropped&&c.framesDropped>p.framesDropped&&(c.framesDroppedDelta=parseFloat(((c.framesDropped-p.framesDropped)/r).toFixed(0)))}}),a}function Rt(i,r){return o(this,arguments,function*(a,e,t={}){let n=yield Za(a),c={timestamp:Date.now(),transport:en(n),rtps:tn(n,t)};return e?rn(c,e):(yield S.delay(Ja),Rt(a,c,t))})}var qt=.8,ze=class extends J{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=U.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=n,this.subscribe(this._signaling,_e.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Ee.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Ee.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:d.iceServers,iceTransportPolicy:d.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(c){u.log(h.ERROR,"addTrack-direct"),s.error("Unable to add media source tracks",c,{participantId:this._participantId}),this._failedOnCreate=c;return}this._createOffer(!1).catch(c=>{this._state===U.IDLE?this._failedOnCreate=c:this.close(c)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==U.IDLE&&e!==U.CLOSED&&e!==U.FAILED&&this._startStatInterval()}open(e=null){return o(this,null,function*(){if(this._isOpen){s.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(s.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(i){u.log(h.ERROR,"addTrack-direct"),s.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(U.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(L.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Gt(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(L.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(s.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(U.FAILED)):(s.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(U.CLOSED)),this._triggerEvent(L.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(s.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(L.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case D.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case D.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 D.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){s.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw u.log(h.ERROR,"addIceCandidate-direct"),s.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else s.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]){s.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){s.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw u.log(h.ERROR,"setRemoteDescription-direct"),s.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){s.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(L.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(L.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return o(this,null,function*(){e.candidate&&this._signaling.ready&&(s.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(s.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(s.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===U.IDLE||e===U.OPENED?this._setState(U.CONNECTING):this._setState(U.RECONNECTING);break}}_onConnectionStateChange(){switch(s.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),u.log(h.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(U.CONNECTED),this._stopReconnection(),S.getPeerConnectionHostInfo(this._pc).then(e=>{e&&u.log(h.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(U.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(s.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&&(s.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(Ie.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(u.log(h.ICE_RESTART),s.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):s.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,s.error("Ice restart failed",{participantId:this._participantId}),u.log(h.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return o(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return s.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw s.error("Unable to create offer",i,{participantId:this._participantId}),u.log(h.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return s.debug("Created offer",{participantId:this._participantId,offer:i}),i=ze._patchDescription(i),s.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw s.error("Unable to set local description",i,{participantId:this._participantId}),u.log(h.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return o(this,null,function*(){return s.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw s.error("Unable to create answer",e,{participantId:this._participantId}),u.log(h.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return s.debug("Created answer",{participantId:this._participantId,answer:e}),e=ze._patchDescription(e),s.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw s.error("Unable to set local description",e,{participantId:this._participantId}),u.log(h.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!T.baseChromeVersion();return e.sdp=S.patchSDP(e.sdp,d.preferH264&&T.canPreferH264(),T.isBrokenH264(),d.preferVP9,t&&d.audioNack),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{s.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),u.log(h.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Rt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:Ie.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:Ie.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(L.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,d.statisticsInterval)})};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=oe=>oe.rtt<=this._networkLimits.goodNet.rtt&&oe.loss<=this._networkLimits.goodNet.loss,i=oe=>oe.rtt>=this._networkLimits.badNet.rtt||oe.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((oe,Ze)=>Math.max(oe,Ze.packetLoss||0),0),c={rtt:this._lastNetworkStat.rtt*(1-qt)+r*qt,loss:this._lastNetworkStat.loss*(1-qt)+n*qt},p=i(c),l=t(c),m=i(this._remoteNetworkStat),R=t(this._remoteNetworkStat),k=i(this._lastNetworkStat),z=t(this._lastNetworkStat),q=p||m?.2:l&&R?1:0,ae=Date.now();if((k!==p||z!==l||ae-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},c)},null).catch(oe=>{s.warn("Unable to send [bad-net]",oe)})),q){let oe={};oe[this._participantId]=oe[""]=q,this._triggerEvent(L.NETWORK_STATUS,oe)}this._lastNetworkStat.rtt=c.rtt,this._lastNetworkStat.loss=c.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=S.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(f.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=S.applySettings(this._pc,e,this._prevConsumerSettings))}};var Kr=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Kr||{}),bt=Kr;var Qe=He(require("messagepack"));var Oi=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var n,c;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let p=(0,Qe.decode)(r);return Object.entries(p).forEach(([B,q])=>{let ae=Ct(B);this.streamDescriptionByCompactId.set(q,ae)}),null;case 2:case 4:let l=(0,Qe.decode)(r),m=[];for(let B of l){let q=this.getStreamDescription(B);q&&m.push(q.participantId)}return i===2?{type:"notification",notification:D.AUDIO_ACTIVITY,activeParticipants:m}:{type:"notification",notification:D.STALLED_ACTIVITY,stalledParticipants:m};case 3:let R=(0,Qe.decode)(r);return{type:"notification",notification:D.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(R))==null?void 0:n.participantId};case 5:let k=(0,Qe.decode)(r);return{type:"notification",notification:D.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:k[0],maxDimension:k[1]}};case 6:let z=(0,Qe.decode)(r),se={};for(let[B,q]of Object.entries(z)){let ae=(c=this.getStreamDescription(Number(B)))==null?void 0:c.participantId;ae&&(se[ae]=q/100)}return{type:"notification",notification:D.NETWORK_STATUS,statuses:se};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return s.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,Qe.decode)(e),i=[];for(let[r,n]of Object.entries(t)){let c=n[0],p=n[1],l=n[2],m;if(c!==null){if(m=this.getStreamDescription(c),!m){s.error(`could not uncompress participant ID ${c}`);continue}}else m=null;if(l===null){s.error("unexpected null sequenceNumber",r,n);continue}let R=Me.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,k=p?p>>>0:null;i.push({participantStreamDescription:m,streamId:R,rtpTimestamp:k,sequenceNumber:l})}return{type:"notification",notification:D.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var $r="videochat-epi",Pt=class extends J{constructor(e,t){super();this._previousTimestamp=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};this._signaling=t,this.subscribe(e,L.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem($r)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return o(this,null,function*(){if(!d.perfStatReportEnabled||!e.inbound||!e.inbound.rtps)return;let t=e.inbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.framesDecoded+=n.framesDecoded||0,r.framesReceived+=n.framesReceived||0),r),{framesDecoded:0,framesReceived:0}),i=Date.now();if(!(this._previousTimestamp+5e3>i)){if(t.framesDecoded)try{let r=yield this._signaling.reportPerfStat(t);localStorage.setItem($r,r.estimatedPerformanceIndex)}catch(r){}this._reportCallStats(e),this._previousTimestamp=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,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,n)=>(n.kind==="video"?(n.jitter&&(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_received+=n.nackCount||0,r.pli_received+=n.pliCount||0,r.fir_received+=n.firCount||0):n.jitter&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+n.jitter*1e3/(r.inbound_audio_count+1),r.inbound_audio_count++),r),t),e.outbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.nack_sent+=n.nackCount||0,r.pli_sent+=n.pliCount||0,r.fir_sent+=n.firCount||0),r),t);let i={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};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),u.logCustom("callStat",i),this._previousCallStatReport=t}};var an=90,nn=4294967295,Re=class extends J{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._reconnectionPrevented=!1;this._state=U.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,_e.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Ee.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Ee.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,Ee.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Pt(this,e),this._serverSettings=i,s.debug("ServerTransport: Created")}getState(){return this._state||U.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==U.IDLE&&e!==U.CLOSED&&e!==U.FAILED&&this._startStatInterval()}open(){if(this._isOpen){s.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(s.error("ServerTransport: Closed",e),this._setState(U.FAILED)):(s.debug("ServerTransport: Closed"),this._setState(U.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Gt(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,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(L.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){s.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{s.debug(`[${t}] data channel opened`),r.onerror=n=>{s.error(`[${t}] data channel error`,n)},i(r)}}_openConnection(e=!1){s.debug("ServerTransport: Open single connection");let t={};T.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=S.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Re._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,bt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Oi,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,bt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,bt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){s.error("ServerTransport: Unable to add media source tracks",i),u.log(h.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,bt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(U.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==U.OPENED&&(this._setState(U.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(L.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(L.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(L.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(L.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
+ `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Me.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!d.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new dt(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!d.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new ot(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(L.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(L.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!d.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==me.video)return;let r=!this._disabledSenders.has(i),n=e.maxDimension!==0;if(r&&!n){s.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(T.getBlackMediaTrack()).catch(p=>{s.error("Could not disable video upload",p)});return}let c=this._mediaSource.getSendVideoTrack();if(!r&&n&&c){s.log("Enabling video upload"),this._disabledSenders.delete(i);let p=i.track;p.enabled=c.enabled,i.replaceTrack(c).then(()=>p.stop()).catch(l=>{s.error("Could not enable video upload",l)})}S.applyVideoTrackSettings(e,i,c!=null?c:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(L.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,d.statisticsInterval)};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return o(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Rt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(L.REMOTE_DATA_STATS,{inbound:{topology:Ie.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:Ie.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(c=>c.type==="inbound-rtp"&&c.kind==="audio"&&this._ssrcMap[c.ssrc]==="mix");if(!t)return;let i=Me.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let c=t.bytesReceived-r.bytesReceived;c>=0&&c<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(L.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Pt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:d.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:d.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:d.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:d.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:Re._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return o(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,s.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(s.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw s.error("[single] unable to set remote offer",i),u.log(h.ERROR,"setRemoteDescription-single"),i}).then(()=>o(this,null,function*(){if(s.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw s.error("[single] unable to create answer",i),u.log(h.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=S.patchSDP(i.sdp,!1,T.isBrokenH264(),!1),i)).then(i=>o(this,null,function*(){if(s.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw s.error("[single] unable to set local answer",i),u.log(h.ERROR,"setLocalDescription-single"),i}).then(i=>o(this,null,function*(){s.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),s.debug("[single] remote offer has been processed")})).catch(i=>{s.warn("[single] unable to send local answer",i),u.log(h.ERROR,"acceptProducer")}).then(()=>o(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){s.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 D.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case D.REALLOC_CON:this._reconnect();break;case D.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case D.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case D.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case D.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return o(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),d.breakVideoPayloadTypes&&(s.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){s.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent(L.REMOTE_TRACK_REMOVED,i.id,i,n.track)}),i.getTracks().find(n=>n.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(L.REMOTE_TRACK_ADDED,i.id,i,t.track)):s.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){s.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(s.debug("[single] connection state changed",{state:e.connectionState},t),u.log(h.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===U.IDLE||i===U.OPENED?this._setState(U.CONNECTING):e.iceConnectionState==="checking"&&this._setState(U.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(U.RECONNECTING);break;case"connected":this._setState(U.CONNECTED),S.getPeerConnectionHostInfo(e).then(r=>{r&&u.log(h.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(d.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{s.error("ServerTransport: Unable to replace track",r),u.log(h.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=T.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(T.browserName(),T.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return u.log(h.PAT_WAITING_TIME_ERROR,"noConnection"),s.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return u.log(h.PAT_WAITING_TIME_ERROR,"noReceiver"),s.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return s.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let c=r[0].rtpTimestamp;if(!Number.isInteger(c))return u.log(h.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),s.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${c}`),0;let p=t-c&nn,l=Math.ceil(p/an);return Math.min(100,Math.max(0,l))}};var L=(B=>(B.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",B.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",B.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",B.REMOTE_ALL_STALL="REMOTE_ALL_STALL",B.REMOTE_DATA_STATS="REMOTE_DATA_STATS",B.STATE_CHANGED="STATE_CHANGED",B.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",B.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",B.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",B.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",B.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",B.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",B.NETWORK_STATUS="NETWORK_STATUS",B.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",B))(L||{}),U=(p=>(p.IDLE="IDLE",p.OPENED="OPENED",p.CONNECTING="CONNECTING",p.RECONNECTING="RECONNECTING",p.CONNECTED="CONNECTED",p.CLOSED="CLOSED",p.FAILED="FAILED",p))(U||{}),Ie=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(Ie||{}),ki=class extends J{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,_e.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){s.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){s.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){s.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),s.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&s.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===D.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===D.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(s.log(`Topology changed ${this._topology} -> ${e.topology}`),u.log(h.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],n=i.length&&r.length?S.composeId(i[0],r[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){s.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&s.warn("Topology changed to DIRECT, but the allocated participants count more then one");let c=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let p=n===c;this._directTransport=this._createDirectTransport(c,p)}this._opened.indexOf(c)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new ze(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),this._dtListeners&&this._dtListeners.length>0&&s.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._setLocalNoiseSuppression(!1),this._stListeners&&this._stListeners.length>0&&s.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("ACTIVE_PARTICIPANTS_NO_SIGNAL",this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;d.noiseSuppression!==e&&(d.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent("ACTIVE_PARTICIPANTS_NO_SIGNAL")}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(u.log(h.PAT_WAITING_TIME_ERROR,"wrongTopology"),s.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(u.log(h.PAT_WAITING_TIME_ERROR,"noTransport"),s.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Xe=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(Xe||{}),wi=class extends J{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,L.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,L.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,L.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,L.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===me.audio&&((r=this._detector)==null||r.destroy(),this._detector=new yt(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,d.voiceParams.interval)};this._interval=window.setTimeout(n,d.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===me.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===Me.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var Ni=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(Ni||{}),xi=class extends J{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,Xe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,L.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,L.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,L.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>d.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*d.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent("SPEAKER_CHANGED",e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var Jt=class extends J{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,L.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,Xe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===U.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),d.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),d.specListenerParams.volumeTimeout))),t===U.FAILED&&this._connectionTimeout&&(s.warn("Transport failed, send callSpecError"),u.log(h.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==U.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(s.warn("There is not connected transport, send callSpecError"),u.log(h.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),u.log(h.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&s.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var sn=1e3,on=1e4;var F=class extends J{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=G.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 Wt,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),sn))}static current(){return F._current}static hangupAfterInit(){F._activationMutex&&!F._current&&(F._delayedHangup=!0)}static id(){var e,t;return((t=(e=F._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,c=!1){return o(this,null,function*(){if(F._activationMutex)throw u.log(h.ERROR,"startCall"),s.warn("Conversation: there is already running activation"),new O(y.FAILED);F._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let p=this._mediaSource.getMediaSettings();t===ke.CHAT||e.length>1?this._logWithMediaSettings(h.OUTGOING_MULTIPARTY_CALL,p):this._logWithMediaSettings(h.OUTGOING_CALL,p);let l=yield this._startConversation(e,t,Ue.OUTGOING,i,r,n,c);if(!this._conversation)throw new O(y.UNKNOWN_ERROR);if(this._participantState=G.ACCEPTED,this._signaling.changeMediaSettings(p),yield this._registerParticipants(l.conversation.participants),this._processConnectionData(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),F._delayedHangup)throw new O(y.CANCELED);s.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let m=Object.values(this._participants),R;return d.batchParticipantsOnStart&&(R=S.mapSharedParticipants(m)),f.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),f.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,R),f.onLocalStatus(K.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),F._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(m,K.WAITING),this._conversation}catch(p){throw this._close(p,"Unable to start conversation"),p}finally{F._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){if(F._activationMutex)throw u.log(h.ERROR,"joinCall"),s.warn("Conversation: there is already running activation"),new O(y.FAILED);F._activationMutex=!0,this._state="PROCESSING";try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(h.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new O(y.UNKNOWN_ERROR);return f.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(s.log("In waiting hall"),F._current=this,F._activationMutex=!1,this._signaling.readyToSend(),f.onLocalStatus(K.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw F._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return o(this,null,function*(){s.debug("Join conversation part 2"),F._activationMutex=!0;try{if(this._participantState=G.ACCEPTED,!this._conversation||!this._mediaSource)throw new O(y.UNKNOWN_ERROR);if(this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),F._delayedHangup)throw new O(y.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=S.mapSharedParticipants(t)),f.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),f.onLocalStatus(K.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),F._current=this,d.batchParticipantsOnStart||this._setParticipantsStatus(t,K.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{F._activationMutex=!1}})}onPush(r){return o(this,arguments,function*(e,t=Y.USER,i){if(F._activationMutex)throw s.warn("Conversation: there is already running activation"),new O(y.REJECTED);F._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new O(y.UNKNOWN_ERROR);if(!n.conversation.participants.find(p=>{var l;return p.state===G.CALLED&&p.id===((l=this._conversation)==null?void 0:l.userId)}))throw s.log("Push rejected (there is an active call)"),u.log(h.PUSH,"rejected"),new O(y.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),u.log(h.PUSH,"accepted"),F._current=this,F._delayedHangup)throw new O(y.CANCELED);F._activationMutex=!1}catch(n){throw F._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Ot.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>S.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return o(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new O(y.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(h.ACCEPT_CONCURRENT,e),s.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),f.onCallAccepted(),this._state="ACTIVE",this._participantState=G.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(h.ERROR,"acceptIncoming"),s.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new O(y.UNKNOWN_ERROR);this._state="PROCESSING",s.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(h.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=G.ACCEPTED;let i=Object.values(this._participants),r;d.batchParticipantsOnStart&&(r=S.mapSharedParticipants(i)),f.onCallAccepted(),f.onLocalStream(this._mediaSource.getStream(),t),f.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),f.onLocalStatus(K.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(Be.MUTE)||n.includes(Be.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),d.batchParticipantsOnStart||this._setParticipantsStatus(i,K.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(h.ERROR,"declineIncoming"),s.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",s.debug("Decline incoming call"),this._logWithMediaSettings(h.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=G.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(y.REJECTED)),this._close(new O(y.REJECTED))})}hangup(){return o(this,null,function*(){s.debug("Hangup");let e=this._state==="ACTIVE"?y.HUNGUP:y.CANCELED;u.log(h.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new O(e))):f.onHangup(new O(y.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new O(y.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=y.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(e,n,r)})}removeParticipant(e,t=!1){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){if(!this._transport)return;let i=[];for(let r of e)(r.state===G.CALLED||r.state===G.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===G.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&s.error(t,e),s.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(y.FAILED):u.log(h.ERROR,e.hangup),F._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([y.CANCELED,y.NOT_FRIENDS,y.CALLEE_IS_OFFLINE,y.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===y.REJECTED&&!e.remote){f.onHangup(e,i),this.destroy();return}if(e.hangup===y.HUNGUP&&(!e.remote||this._participantState===G.CALLED)){f.onHangup(e,i),this.destroy();return}if(e.hangup===y.MISSED&&!e.remote){f.onHangup(e,i),this.destroy();return}if(e.hangup===y.SOCKET_CLOSED&&F._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===y.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=G.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,F._current=null,F._delayedHangup=!1,f.onHangup(e||new O(y.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;s.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,F._current=null,F._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);s.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let c=r.urls.filter((p,l,m)=>m.indexOf(p)===l);c.forEach(p=>c.push(`${p}?transport=tcp`)),i.push({urls:c,username:r.username,credential:r.credential})}d.iceServers=i,d.wssBase=t.endpoint,d.wssToken=t.token,t.client_type&&(d.clientType=t.client_type)})}_startConversation(e,t,i,r,n="",c=!1,p=!1){return o(this,null,function*(){let l=S.uuid();s.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let m=r.includes(pe.VIDEO),R=yield this._api.startConversation(l,e,t,m,n,c,p);s.debug("Api.startConversation",R),yield this._getConversationParams(R.id);let k=yield this._connectSignaling(we.START,R);return yield this._setConversation(R,k,i),k})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n}=e;s.debug("Conversation: join",{conversationId:t,joinLink:n});let c=i.includes(pe.VIDEO),p;if(t)p=yield this._api.joinConversation(t,c,r);else if(n)p=yield this._api.joinConversationByLink(n,c);else throw new O(y.UNKNOWN_ERROR);s.debug("Api.joinConversation",p),yield this._getConversationParams(p.id);let l=yield this._connectSignaling(we.JOIN,p);return yield this._setConversation(p,l,Ue.JOINING),l})}_prepareConversation(r){return o(this,arguments,function*(e,t=Y.USER,i){s.debug("Conversation: push",{conversationId:e,type:t,peerId:i}),yield this._getConversationParams(e);let n=this._api.getUserId();if(!n)throw new O(y.UNKNOWN_ERROR);let c={id:e,peerId:i,endpoint:`${d.wssBase}?userId=${n}&entityType=${t}&conversationId=${e}&token=${d.wssToken}`,is_concurrent:!1,p2p_forbidden:!1},p=yield this._connectSignaling(we.ACCEPT,c);return F._current&&(F._current._participantState===G.ACCEPTED||F._current._participantState===G.CALLED)?(s.log("Push rejected (busy)"),u.log(h.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(y.BUSY),Promise.reject({hangup:y.BUSY})):(F._current&&(F._current.destroy(),F._current=null),yield this._setConversation(c,p,Ue.INCOMING,t),p)})}_createParticipant(e){return o(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:fe(),participantState:{},state:G.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);return e.externalId?this._api.cacheExternalId(t.id,e.externalId):t.externalId=yield this._getUserId(t.id),t})}_getUserId(e){return o(this,null,function*(){try{return yield this._api.userId(e)}catch(t){throw this._close(new O(y.NETWORK_ERROR),t),t}})}_setConversation(n,c,p){return o(this,arguments,function*(e,t,i,r=Y.USER){let l=t.conversation.participants.map(z=>z.id);yield this._api.prepareUserIds(l);let m=this._api.getUserId();if(!m){let z=(t.conversation.participants||[]).find(se=>S.comparePeerId(se.peerId,t.peerId));if(!z)throw new O(y.UNKNOWN_ERROR);m=Number(z.id),z.idType&&(r=z.idType),this._api.setUserId(m)}let R=S.composeId(m,r),k=yield this._getUserId(R);this._conversation={userId:m,compositeUserId:R,externalId:k,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||Ie.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),u.log(h.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new O(y.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||Ie.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 di;return this.subscribe(e,Ee.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Ee.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new It(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,_e.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,_e.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,_e.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return o(this,null,function*(){if(!!this._conversation)for(let t of e){let i=S.composeParticipantId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(s.debug(`Local roles changed: ${t.roles}`),f.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===G.HUNGUP||t.state===G.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],y.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&te.fromSignaling(t.externalId),mediaSettings:fe(t.mediaSettings),participantState:S.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?K.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(s.debug(`Roles for participant [${i}] changed: ${t.roles}`),f.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){S.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Dt.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new ki(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new jt,this.subscribe(this._transport,L.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,L.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,L.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,L.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,L.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,L.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,L.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,L.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,L.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,L.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,L.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,L.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Ue.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===G.ACCEPTED||t.state===G.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new wi(this._transport),this.subscribe(this._volumesDetector,Xe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new xi(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,Ni.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Kt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Jt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=T.getCameras().length,t=T.getMicrophones().length;s.debug("Cameras: "+e+(T.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(T.hasMicrophonePermission()?"✔":"✖")),u.log(h.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){u.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===G.CALLED||e.state===G.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===y.HUNGUP?this._setParticipantsStatus([e],K.HANGUP):this._setParticipantsStatus([e],K.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],f.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){s.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*(){s.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===G.ACCEPTED||r.state===G.CALLED)){s.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&te.fromSignaling(t.externalId),mediaSettings:fe(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],K.WAITING),i?(r.state=G.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=G.CALLED,this._transport.allocate(r.id,!0),u.log(h.ADD_PARTICIPANT))})}_onRemoveParticipant(e){s.debug(`Remove participant [${e}]`);let t=this._participants[e];if(!t){s.warn(`Participant [${e}] isn't in conversation`);return}this._transport&&this._transport.close(t.id),u.log(h.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new It(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(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(h.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return u.log(h.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:te.fromId(r.uid),c=te.toString(n);i[c]=r.priority}for(let r of Object.values(this._participants)){let n=te.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return o(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}updateDisplayLayout(e){return o(this,null,function*(){if(e.length<1||!this._signaling.ready)return;s.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:te.fromId(r.uid),c=te.toString(n),p=this._api.getCachedOkIdByExternalId(n);if(!p){s.log(`Unknown participant external ID ${c}`);continue}let l=Ye({participantId:p,mediaType:r.mediaType,streamName:r.streamName}),m=this._participants[p];m&&(m.lastRequestedLayouts[l]=r),F._isStopStreaming(r)?this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now()):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&d.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=F._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>d.videoTracksCount;){let r=i.next();if(r.done){s.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]=F._layoutToString({stopStream:!0})}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(s.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Ct(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===ve.STREAM||i.mediaType===ve.SCREEN)?f.onRemoteLive(r.externalId,i.streamName,null):f.onRemoteStream(r.externalId,null),u.log(h.PAT_DEALLOCATED)):s.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 c=Ct(r),p=this._participants[c.participantId];if(p){let l;typeof n!="number"?(s.warn(`Unexpected error code ${n} received for participant ${c.participantId}`),l=lr.UNKNOWN_ERROR):l=ur(n),i.push({externalId:p.externalId,errorReason:l})}}if(i&&i.length)throw new Yt("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+on>Date.now())break;let c=r[0];this._stopStreaming(c),e[c]=F._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(F._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),e.keyFrame&&(t!==""&&(t+=":"),t+="kf"),t}_onParticipantSourcesUpdate(e){if(this._conversation){s.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){s.log("Promoted in waiting hall",!e.demote),e.demote?(s.log("Kicked from waiting hall"),this._close(new O(y.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return o(this,arguments,function*(e,t=0,i=[]){s.log(`Chat room updated: ${e}`);let n=[],c=[];i.length&&(i.forEach(p=>{if(p.externalId){let l=te.fromSignaling(p.externalId);n.push(l),this._api.cacheExternalId(p.id.id,l)}else c.push(S.decomposeId(p.id.id).id)}),c.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(c))),f.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var p,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===ve.SCREEN)return;let i=Ye(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){s.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),u.log(h.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,c=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(c<=0){this._streamWaitTimerByStreamDescription.delete(i);let m=t.participantId,R=this._participants[m];if(!R){u.log(h.PAT_ERROR,"participantMissing"),s.error(`Could not find participant by ID: ${m}`);return}let k=this._streamByStreamId.get(n);if(!k){u.log(h.PAT_ERROR,"streamNotFound"),s.error(`Could not find stream by ID: ${n}`);return}u.log(h.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let z=(p=e.participantStreamDescription)==null?void 0:p.mediaType;if(z===ve.STREAM||z===ve.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&f.onRemoteLive(R.externalId,e.participantStreamDescription.streamName,k);else{let se=(d.producerScreenTrack?null:R.secondStream)||k;f.onRemoteStream(R.externalId,se)}}else{s.debug(`Waiting for ${c} until stream ${n} for ${i} is switched`);let m=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),c);this._streamWaitTimerByStreamDescription.set(i,m)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Ye(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Ye(i)))return i}else{let i={participantId:t,mediaType:ve.CAMERA};if(this._streamIdByStreamDescription.has(Ye(i)))return i;let r={participantId:t,mediaType:ve.SCREEN};if(this._streamIdByStreamDescription.has(Ye(r)))return r}return s.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?S.includesOneOf(this._conversation.roles,[Ge.ADMIN,Ge.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!S.includesOneOf(this._conversation.roles,[Ge.ADMIN,Ge.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return 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=Zi(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=Wr(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let c=n.participants||[],p=[],l=[],m=null;return c.length&&(c.forEach(R=>{if(R.externalId){let k=te.fromSignaling(R.externalId);p.push(k),this._api.cacheExternalId(R.id.id,k)}else l.push(S.decomposeId(R.id.id).id)}),l.length&&!p.length&&(p=yield this._api.getExternalIdsByOkIds(l)),n.hasMore&&(m=Gr(c[c.length-1].id))),{participants:p,pageMarker:m,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return 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 c=yield this._signaling.updateMovie(n);if(c.error)throw new Error(c.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 c={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},p=yield this._signaling.startStream(c);return p.error?Promise.reject(p.message):p})}stopStream(){return 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)})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t;!this._conversation||(s.debug("Local media stream changed",e.mediaSettings),f.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return o(this,null,function*(){var t;if(s.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;f.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){s.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&f.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){s.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&(d.participantStateMapped?f.onRemoteParticipantState(i.externalId,i.participantState):f.onRemoteParticipantState(i.externalId,S.mapLegacyParticipantState(i.participantState))))}_onSignalingNotification(e){switch(e.notification){case D.ACCEPTED_CALL:return this._onAcceptedCall(e);case D.HUNGUP:return this._onHungup(e);case D.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case D.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case D.CLOSED_CONVERSATION:return this._onClosedConversation(e);case D.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case D.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case D.RATE_CALL_DATA:return this._onNeedRate();case D.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case D.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case D.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case D.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case D.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case D.REGISTERED_PEER:return this._onPeerRegistered(e);case D.SWITCH_MICRO:return this._onMicSwitched(e);case D.CHAT_MESSAGE:return this._onChatMessage(e);case D.CUSTOM_DATA:return this._onCustomData(e);case D.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case D.RECORD_STOPPED:return this._onRecordInfo(null);case D.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case D.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case D.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case D.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case D.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case D.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case D.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return o(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let c=S.composeParticipantId(n),p=n.roles||[];if(c===this._conversation.compositeUserId){t=fe(n.mediaSettings),_t(this._conversation.roles,p)||this._onRolesChanged(c,p);continue}r.push(c);let l=this._participants[c];if(!l)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let m=fe(n.mediaSettings);Tr(m,l.mediaSettings)||this._changeRemoteMediaSettings(c,m);let R=S.mapParticipantState(n),k=l.participantState;S.isEqualParticipantState(R,k)||this._changeRemoteParticipantState(c,R),_t(p,l.roles)||this._onRolesChanged(l.id,p)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],y.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){s.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(s.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new O(y.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:fe(e.mediaSettings)}),r=this._participants[t]),r.state=G.ACCEPTED,r.mediaSettings=fe(e.mediaSettings),this._logWithMediaSettings(h.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Ue.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){s.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=S.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new O(e.reason));return}let i=this._participants[t];if(!i){s.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===y.REJECTED?G.REJECTED:G.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,y.HUNGUP)}_onAddedParticipant(e){return o(this,null,function*(){var r,n;s.debug(`Participant added [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state!==G.HUNGUP&&i.state!==G.REJECTED){s.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&te.fromSignaling(e.participant.externalId),mediaSettings:fe(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=G.CALLED,i.mediaSettings=fe((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],K.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onJoinedParticipant(e){return o(this,null,function*(){var r;s.debug(`Participant joined [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state===G.ACCEPTED){s.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&te.fromSignaling(e.participant.externalId),mediaSettings:fe(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Ue.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=G.ACCEPTED,i.mediaSettings=fe(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],K.CONNECTED):this._setParticipantsStatus([i],K.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id])),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new O(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=S.composeMessageId(e);this._changeRemoteMediaSettings(t,fe(e.mediaSettings))}_onParticipantStateChanged(e){let t=S.composeMessageId(e);this._changeRemoteParticipantState(t,S.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),f.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=fe(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),d.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Ai(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(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=Ai(this._serverSettings,r),s.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=S.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return o(this,null,function*(){f.onDeviceSwitched(pe.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._getUserId(t),f.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._getUserId(t),f.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return o(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getUserId(e.initiator);f.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else f.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!_t(this._conversation.roles,t)){s.debug(`Local roles changed: ${t}`),this._conversation.roles=t,f.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!_t(i.roles,t)&&(s.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,f.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||[],c=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){s.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let p=this._participants[e.participantId];p&&(s.debug(`Mute states for participant [${e.participantId}] changed`,i),f.onMuteStates(i,r,n,e.muteAll,e.unmute,p.externalId,c==null?void 0:c.externalId));return}S.isObjectsEquals(this._conversation.muteStates,i)&&S.isArraysEquals(this._conversation.unmuteOptions,r)&&!n.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(n,e.muteAll,e.unmute,t,c)))})}_processMuteState(){return o(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==G.ACCEPTED)return;let c=Object.assign({},this._conversation.muteStates),p=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),m=Object.entries(c);for(let[R,k]of m)if(!(k!==Be.MUTE&&k!==Be.MUTE_PERMANENT)&&(this._isCallAdmin()&&k===Be.MUTE_PERMANENT&&(c[R]=Be.MUTE),!(!e.includes(R)||i)))switch(R){case pe.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(f.onDeviceSwitched(pe.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case pe.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(f.onDeviceSwitched(pe.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case pe.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(f.onDeviceSwitched(pe.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}f.onMuteStates(c,p,e,t,i,null,n==null?void 0:n.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?f.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&f.onLocalPin(!0)),this._participants[e]?f.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&f.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!Xi(this._conversation.options,e)&&(this._conversation.options=e,f.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,f.onLocalNetworkStatusChanged(r);else{let c=this._participants[i];c.networkRating=r,t.push({uid:c.externalId,rating:r})}}if(t.length===0)return;s.log("Received network status update: ",e),f.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){f.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,d.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){s.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)){s.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let c=this._streamByStreamId.get(n);if(!c){u.log(h.PAT_ERROR,"streamNotFound"),s.error(`Could not find stream by ID: ${n}`);return}f.onRemoteStream(i.externalId,i.secondStream||c)}else{let r=t||i.remoteStream;r&&f.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===Ie.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(zi.ADD_PARTICIPANT);f.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&f.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})}f.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(f.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){s.debug(`Transport state has changed: ${t}`,e);let i;if(t===U.CONNECTED?i=K.CONNECTED:t===U.CONNECTING||t===U.OPENED?i=K.CONNECTING:t===U.RECONNECTING&&(i=K.RECONNECT),!i)return;let r=e.reduce((n,c)=>{if(c in this._participants){let p=this._participants[c];n.push(p),t===U.CONNECTED&&(p.remoteStream||(p.mediaSettings&&this._changeRemoteMediaSettings(c,p.mediaSettings),this._changeRemoteParticipantState(c,p.participantState)),this._updateDisplayLayoutFromCache(c))}else s.warn(`Participant [${c}] isn't in conversation`);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){s.debug(`Local transport state has changed: ${e}`),e===U.CONNECTED&&f.onLocalStatus(K.CONNECTED),e===U.CONNECTING&&f.onLocalStatus(K.CONNECTING),e===U.RECONNECTING&&f.onLocalStatus(K.RECONNECT),e===U.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(y.FAILED)),this._close(new O(y.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(Me.AUDIO_MIX))s.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(Me.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))s.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{s.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(s.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],K.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(f.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===me.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;f.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),d.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(s.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case me.audio:this._removeAudioTrack(e,t,i);break;case me.video:case me.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Me.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onRemoteActivityNoSignal(){this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)}_onTopologyChanged(e){this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let n=this._participants[r];e||this._lastStalled[r]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,K.RECONNECT),i.length&&this._setParticipantsStatus(i,K.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let c=this._participants[n];c&&!this._remoteAllStalled&&i.push(c)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let c=this._participants[n];c&&!this._remoteAllStalled&&r.push(c)}),i.length&&this._setParticipantsStatus(i,K.RECONNECT),r.length&&this._setParticipantsStatus(r,K.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!T.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(s.debug("Toggle join availability",{available:t,chatId:e}),f.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==Ie.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,c)=>(c.status!==t&&(c.status=t,d.batchParticipantsOnStart?n.push(c.externalId):f.onParticipantStatus(c.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&f.onRemoteStatus(r,t,i)}},w=F;w._delayedHangup=!1;var Yt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Yt.prototype),this.participantErrors=t}};var zt;function cn(){return o(this,null,function*(){var a;if(d.apiEnv!=="AUTO")return d.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT1hcGkuX2VuZHBvaW50Lm9rLnJ1JnR5cGU9VFhU"),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 s.debug("Resolved API endpoint",r),r}catch(e){return s.warn("Failed to resolve API endpoint using DNS, default is used",e),d.apiEndpoint}})}function qr(){if(!d.apiAppId||!d.apiKey)throw new O(ie.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function Li(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Yr(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${zt}/fb.do`,r)}function Jr(i){return o(this,arguments,function*(a,e={},t=!1){zt||(zt=yield cn());let r=Yr(a,e,t);return dn(r)})}function dn(a){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${zt}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(n){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(a)})})}function Yr(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=d.apiKey),t||(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 ln=10,un=700,mn=3e3,Mt=class extends et{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return o(this,arguments,function*(e,t={},i=!1){let n=c=>o(this,null,function*(){try{return yield Jr(e,t,i)}catch(p){if(!p.hasOwnProperty("error_msg")&&(c++,s.debug(`${e} network error, attempt ${c}...`),c<ln))return yield S.delay(Math.min(c*un,mn)),n(c);throw s.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){s.warn("Api call error",n);let c=ie.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:c=y.SERVICE_DISABLED;break;case 1102:c=y.CALLEE_IS_OFFLINE;break;case 1103:c=y.NOT_FRIENDS;break;case 1104:case 1106:c=y.EXTERNAL_API_ERROR;break}throw new O(c,{message:n.error_msg,code:n.error_code})}})}userId(e){return o(this,null,function*(){let t=S.decomposeId(e).id;return ee.isEmpty()?te.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),te.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=Ve.get("uuid");t||(t=S.uuid(),Ve.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:d.appVersion,client_type:"SDK_JS"}};return d.authToken&&(e.session_data.auth_token=d.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),ee.sessionKey=t.session_key,ee.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&f.onTokenExpired(),new O(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})};Li("log.externalLog",t)}init(){qr()}joinConversation(e,t=!1,i){return o(this,null,function*(){let r={conversationId:e,isVideo:t};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return o(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1};return t&&(r.payload=t),d.domain&&(r.domainId=d.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,n="",c=!1,p=!1){return o(this,null,function*(){let l={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case ke.USER:l.uids=t.join(",");break;case ke.GROUP:l.gid=t[0];break;case ke.CHAT:l.chatId=t[0];break}return c&&(l.createJoinLink=!0),n&&(l.payload=n),d.domain&&(l.domainId=d.domain),p&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return o(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return o(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return o(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return o(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1){return o(this,null,function*(){let i={joinLink:e,isVideo:t};return d.anonymToken&&(i.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=te.fromIds(e),i=[],r={methods:[]},n=[],c=Object.keys(this._externalUidsCache),p=Object.values(this._externalUidsCache);for(let m of t){let R=te.toString(m),k=p.indexOf(R);k>-1?i.push(Number(c[k])):(n.push(R),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:m.id,anonym:m.type===Je.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((m,R)=>{if(m.ok){let k=Number(m.ok.ok_id);this._externalUidsCache[k]=n[R],i.push(k)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(te.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(te.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=te.toString(e),n=i.indexOf(r);return n>-1?S.composeId(t[n],Y.USER):null}cacheExternalId(e,t){let i=S.decomposeId(e).id;this._externalUidsCache[i]=te.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:y.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),Li("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]=te.fromIdToString(n,Je.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=te.fromIdToString(n,Je.ANONYM);return t}catch(i){return t}})}getTokenForAnonym(e,t){return o(this,null,function*(){let i={id:e};return t&&(i.application_key=t),(yield this._callUnsafe("auth.getTokenForAnonym",i,!0)).token})}call(i){return o(this,arguments,function*(e,t={}){return this._call(e,t)})}};var zr=(P=>(P.RECOVER="recover",P.ACCEPT_CALL="accept-call",P.ADD_PARTICIPANT="add-participant",P.REMOVE_PARTICIPANT="remove-participant",P.HANGUP="hangup",P.TRANSMIT_DATA="transmit-data",P.ACCEPT_PRODUCER="accept-producer",P.ALLOCATE_CONSUMER="allocate-consumer",P.CHANGE_MEDIA_SETTINGS="change-media-settings",P.CHANGE_PARTICIPANT_STATE="change-participant-state",P.CHANGE_STREAM_PRIORITIES="change-streams-priorities",P.UPDATE_DISPLAY_LAYOUT="update-display-layout",P.REPORT_PERF_STAT="report-perf-stat",P.RECORD_START="record-start",P.RECORD_STOP="record-stop",P.RECORD_SET_ROLE="record-set-role",P.RECORD_GET_STATUS="record-get-status",P.SWITCH_MICRO="switch-micro",P.SWITCH_TOPOLOGY="switch-topology",P.REQUEST_REALLOC="request-realloc",P.CHAT_MESSAGE="chat-message",P.CHAT_HISTORY="chat-history",P.CUSTOM_DATA="custom-data",P.GRANT_ROLES="grant-roles",P.MUTE_PARTICIPANT="mute-participant",P.PIN_PARTICIPANT="pin-participant",P.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",P.CHANGE_OPTIONS="change-options",P.GET_WAITING_HALL="get-waiting-hall",P.PROMOTE_PARTICIPANT="promote-participant",P.REQUEST_TEST_MODE="request-test-mode",P.ADD_MOVIE="add-movie",P.UPDATE_MOVIE="update-movie",P.REMOVE_MOVIE="remove-movie",P))(zr||{}),H=zr;var Qr="open",Xr=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0,()=>d.movieShare],hn=10,be=class extends it{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+d.platform+"&appVersion="+d.appVersion+"&version="+d.protocolVersion+"&device="+d.device+"&capabilities="+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}static _getCapabilityFlags(){let e=0;for(let t=0;t<Xr.length;t++)Xr[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return o(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){u.log(h.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return o(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=S.decomposeId(t.participantId);t=Object.assign({},t,{participantId:n.id,participantType:n.type})}return this._sendRaw(e,t,i)})}_sendRaw(r){return o(this,arguments,function*(e,t={},i=0){let n=c=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(c),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===Qr&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){u.log(h.SOCKET_ACTION,"not_opened"),s.warn("Socket not opened"),c.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(u.log(h.SOCKET_ACTION,"invalid_state"),s.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(c),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((c,p)=>{let l=(R,k=!1)=>{!i||k?p(R):(s.debug("Resending a signaling message",e,m.sequence),i--,n(m))},m={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:c,reject:l};n(m)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(H.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return o(this,null,function*(){return this._send(H.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return o(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(H.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(H.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},hn)})}changeParticipantState(e){return o(this,null,function*(){return this._send(H.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(H.ADD_PARTICIPANT,ji({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(H.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(H.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(H.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(H.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(H.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return o(this,null,function*(){return this._send(H.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(H.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(H.REMOVE_MOVIE,e)})}startStream(e){return o(this,null,function*(){return this._send(H.RECORD_START,e)})}stopStream(){return o(this,null,function*(){return this._send(H.RECORD_STOP)})}recordSetRole(e,t){return o(this,null,function*(){return this._send(H.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return o(this,null,function*(){return this._send(H.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(H.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(H.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(H.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(H.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(H.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(H.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(H.GRANT_ROLES,r)})}muteParticipant(e,t,i){return o(this,null,function*(){return this._sendRaw(H.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(H.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(H.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(H.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(H.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(H.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===we.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),s.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){s.debug("Socket opened"),u.log(h.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){u.log(h.SOCKET_ACTION,"parse_error"),s.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(s.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(_e.RECONNECT,e),e.conversation.topology&&this._triggerEvent(_e.NOTIFICATION,{type:"notification",notification:D.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(_e.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(u.log(h.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(u.log(h.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new O(y.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(_e.NOTIFICATION,{notification:D.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 O(ie.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(u.log(h.SOCKET_ACTION,"unknown_message"),s.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(_e.FAILED,e)}_onError(e){u.log(h.SOCKET_ACTION,"error"),s.error("Signaling error",e)}_onClose(e){u.log(h.SOCKET_ACTION,"closed"),s.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));s.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),u.log(h.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,we.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],u.log(h.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),be.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),n=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==Qr){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}be._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),be.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(n))}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),be.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(n))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new O(ie.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(()=>{s.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(we.RETRY)},be.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},De=be;De.RECONNECT_DELAY=d.signalingReconnectDelay,De.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,De.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,De.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,De.WAIT_RESPONSE_DELAY=d.waitResponseDelay,De.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var Zr=(t=>(t.KING="KING",t.PAWN="PAWN",t))(Zr||{}),ea=Zr;var lt,re,At=null,_n={getCameras:T.getCameras,getMicrophones:T.getMicrophones,getOutput:T.getOutput,hasCamera:T.hasCamera,hasMicrophone:T.hasMicrophone,getSavedCamera:T.getSavedCamera,getSavedMicrophone:T.getSavedMicrophone,getSavedOutput:T.getSavedOutput,hasCameraPermission:T.hasCameraPermission,hasMicrophonePermission:T.hasMicrophonePermission,hasPermissions:T.hasPermissions,getUserMedia:T.getUserMedia,getUserVideo:T.getUserVideo,getUserAudio:T.getUserAudio,saveDeviceId:T.saveDeviceId,isBrowserSupported:T.isBrowserSupported,isScreenCapturingSupported:T.isScreenCapturingSupported,os:T.os,isMobile:T.isMobile,browserName:T.browserName,browserVersion:T.browserVersion,baseChromeVersion:T.baseChromeVersion,getAudioContext:T.getAudioContext};function ta(a){re=a}function ia(a){lt=a}function gn(a){At=a}function fn(a){d.videoEffects=a}function Sn(a){return o(this,null,function*(){if(d.set(a),T.browserName()==="Sferum"&&(d.platform=`SFERUM:${T.browserVersion()}`),re||ta(new Mt),lt||ia(()=>new De),d.debug&&(Ui.default.disableLog(!1),s.toggle(!0)),s.log(`Calls SDK ${d.sdkVersion}`,a),yield T.init(),!T.isBrowserSupported())throw new O(ie.UNSUPPORTED);re.init()})}function vn(n){return o(this,arguments,function*(a,e=[pe.AUDIO],t="",i=!1,r=!1){let c=[],p=[];if(Array.isArray(a)?c=a.length?a:[]:a&&(c=[a]),c.length&&(p=yield re.getOkIdsByExternalIds(c),!p.length))throw new O(y.CALLEE_IS_OFFLINE);return ra(p,ke.USER,e,t,i,r)})}function ra(c){return o(this,arguments,function*(a,e=ke.USER,t,i="",r=!1,n=!1){if(w.current())throw s.error("There is already active call"),new O(y.FAILED);return new w(re,lt(),At).onStart(a,e,t,i,r,n)})}function En(a){return o(this,null,function*(){return aa(a)})}function aa(i){return o(this,arguments,function*(a,e=Y.USER,t){if(a===w.id())throw new Error("Push has already been processed");return new w(re,lt(),At).onPush(a,e,t)})}function Tn(a,e){return o(this,null,function*(){return re.getTokenForAnonym(a,e)})}function Cn(t){return o(this,arguments,function*(a,e={}){return re.call(a,e)})}function In(a){return o(this,null,function*(){return a&&(d.authToken=a),re.authorize()})}function yn(){return o(this,arguments,function*(a=[pe.AUDIO]){let e=w.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function Rn(){return o(this,null,function*(){let a=w.current();if(a)return a.decline()})}function bn(t){return o(this,arguments,function*(a,e=[pe.AUDIO]){return na(a,e)})}function na(a,e,t){return o(this,null,function*(){if(w.current())throw s.error("There is already active call"),new O(y.FAILED);return new w(re,lt(),At).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function Pn(i){return o(this,arguments,function*(a,e=[pe.AUDIO],t){if(w.current())throw s.error("There is already active call"),new O(y.FAILED);return t&&(d.anonymToken=t),new w(re,lt(),At).onJoin({joinLink:a,mediaOptions:e})})}function Mn(){return o(this,null,function*(){let a=w.current();if(a)return a.hangup();w.hangupAfterInit()})}function An(a,e){return o(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return sa(t[0],e)})}function sa(a,e){return o(this,null,function*(){let t=w.current();t&&(yield t.addParticipant(S.composeId(a,Y.USER),e))})}function Dn(a,e=!1){return o(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);return oa(t[0],e)})}function oa(a,e=!1){return o(this,null,function*(){let t=w.current();t&&(yield t.removeParticipant(S.composeId(a,Y.USER),e))})}function On(a,e){return o(this,null,function*(){let t=yield T.saveDeviceId(a,e),i=w.current();return t&&i?i.changeDevice(a):Promise.reject()})}function kn(a){return o(this,null,function*(){let e=w.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function wn(a,e=!1){return o(this,null,function*(){let t=w.current();t&&(yield t.setVideoStream(a,e))})}function Nn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalVideo(a))})}function xn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalAudio(a))})}function Ln(a,e,t){return o(this,null,function*(){let i=w.current();if(i)return i.setLocalResolution(a,e,t)})}function Un(a){return o(this,null,function*(){let e=w.current();e&&(yield e.changePriorities(a))})}function Bn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.changeParticipantState(a))})}function Vn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.updateDisplayLayout(a))})}function Fn(a,e,t=!1){return o(this,null,function*(){let i=yield re.getOkIdsByExternalIds([a]);return ca(i[0],e,t)})}function ca(a,e,t=!1){return o(this,null,function*(){let i=w.current();i&&(yield i.grantRoles(S.composeId(a,Y.USER),e,t))})}function Hn(){return o(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield re.getOkIdsByExternalIds([a]))[0]),da(i,e,t)})}function da(){return o(this,arguments,function*(a=null,e,t=[]){let i=w.current();if(i){let r=a?S.composeId(a,Y.USER):null;yield i.muteParticipant(r,e,t)}})}function Gn(a,e=!1){return o(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);return pa(t[0],e)})}function pa(a,e=!1){return o(this,null,function*(){let t=w.current();t&&(yield t.pinParticipant(S.composeId(a,Y.USER),e))})}function Wn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.updateMediaModifiers(a))})}function jn(a){return o(this,null,function*(){let e=w.current();e&&(yield e.changeOptions(a))})}function Kn(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=w.current();if(t){let i=e?S.composeId(e,Y.USER):null;yield t.chatMessage(a,i)}})}function $n(a=10){return o(this,null,function*(){let e=w.current();if(e)return e.chatHistory(a)})}function qn(a,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield re.getOkIdsByExternalIds([e]))[0]),ua(a,t)})}function ua(a,e=null){return o(this,null,function*(){let t=w.current();if(t){let i=e?S.composeId(e,Y.USER):null;yield t.customData(a,i)}})}function Jn(a="",e=!1){return o(this,null,function*(){return(yield re.createConversation(S.uuid(),a,e)).join_link})}function Yn(){return o(this,null,function*(){let a=w.current();return a?a.createJoinLink():Promise.reject()})}function zn(){return o(this,null,function*(){let a=w.current();return a?a.removeJoinLink():Promise.reject()})}function Qn(a,e){return o(this,null,function*(){return re.getAnonymTokenByLink(a,e)})}function Xn(a){let e=w.current();e&&e.setVolume(a)}function Zn(a){d.forceRelayPolicy=a}function es(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return o(this,null,function*(){let n=w.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function ts(){return o(this,null,function*(){let a=w.current();return a?a.stopStream():Promise.reject()})}function is(a,e){return o(this,null,function*(){let t=w.current();if(t){let i=yield re.getOkIdsByExternalIds([a]);return t.recordSetRole(S.composeId(i[0],Y.USER),e)}return Promise.reject()})}function rs(){return o(this,null,function*(){let a=w.current();return a?a.getStreamInfo():Promise.reject()})}function as(a){return o(this,null,function*(){let e=w.current();return e?e.addMovie(a):Promise.reject()})}function ns(a,e,t,i){return o(this,null,function*(){let r=w.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function ss(a){return o(this,null,function*(){let e=w.current();return e?e.removeMovie(a):Promise.reject()})}function os(a){d.statisticsInterval=a;let e=w.current();if(e)return e.updateStatisticsInterval()}function cs(a){Ui.default.disableLog(!a),s.toggle(a)}function ds(a,...e){!d.debugLog||s.send(a,"[external]",...e)}function ps(a){return o(this,null,function*(){let e=w.current();if(e)return e.videoEffect(a)})}function ls(a){return o(this,null,function*(){let e=w.current();e&&(yield e.setAudioStream(a))})}function us(a=null,e,t=!1){return o(this,null,function*(){let i=w.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(a,e,t)})}function ms(a,e=!1){return o(this,null,function*(){let t=w.current();if(!t)throw new Error("Conversation not found");let i=yield re.getOkIdsByExternalIds([a]);return t.promoteParticipant(S.composeId(i[0],Y.USER),e)})}function hs(a){return o(this,null,function*(){yield re.removeHistoryRecords(a)})}