@vkontakte/calls-sdk 2.5.3-beta.9 → 2.5.3-dev.18fb1f2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/calls-sdk.esm.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
- * @vkontakte/calls-sdk v2.5.3-beta.9
3
- * Thu, 23 Jun 2022 14:06:12 GMT
2
+ * @vkontakte/calls-sdk v2.5.3-dev.18fb1f2.0
3
+ * Thu, 21 Jul 2022 14:44:28 GMT
4
4
  * https://st.mycdn.me/static/callssdk/2-5-3/doc/
5
5
  */
6
6
 
7
- var ta=Object.defineProperty;var Bi=Object.getOwnPropertySymbols;var ia=Object.prototype.hasOwnProperty,ra=Object.prototype.propertyIsEnumerable;var Vi=Math.pow,Fi=(a,e,t)=>e in a?ta(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,Hi=(a,e)=>{for(var t in e||(e={}))ia.call(e,t)&&Fi(a,t,e[t]);if(Bi)for(var t of Bi(e))ra.call(e,t)&&Fi(a,t,e[t]);return a};var c=(a,e,t)=>new Promise((i,r)=>{var n=l=>{try{p(t.next(l))}catch(m){r(m)}},o=l=>{try{p(t.throw(l))}catch(m){r(m)}},p=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,o);p((t=t.apply(a,e)).next())});import Zr from"webrtc-adapter";var ut=class{createJoinLink(e){return c(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return c(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return c(this,null,function*(){return""})}log(e){}prepareUserIds(e){return c(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return c(this,null,function*(){})}cleanup(){}};var mt=class{log(e,t,i=!1){}destroy(){}};var Y=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 ht=class extends Y{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var Gi=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(Gi||{}),Be=Gi;var Wi=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(Wi||{}),Ne=Wi;var ji=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(ji||{}),ei=ji;var Ki=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(Ki||{}),$i=Ki;var qi=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(qi||{}),ti=qi;function Ji(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function Yi(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 zi=(K=>(K.CAMERA_PERMISSION="camera",K.MIC_PERMISSION="mic",K.CAMERA_ACCESS="cameralock",K.MIC_ACCESS="miclock",K.MIC_NOT_FOUND="nomic",K.SCREEN_PERMISSION="screenpermission",K.SCREEN_ACCESS="screenlock",K.CONNECTION="connection",K.NETWORK="network",K.UNKNOWN="unknown",K.UNSUPPORTED="unsupported",K.SIGNALING_FAILED="signalingfailed",K.API="api",K.AUTH="auth",K))(zi||{}),ee=zi;var Qi=(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.HAS_ACTIVE_CALL="HAS_ACTIVE_CALL",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))(Qi||{}),D=Qi;var Xi=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(Xi||{}),de=Xi;var Zi=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(Zi||{}),Ve=Zi;var er=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(er||{}),G=er;var tr=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(tr||{}),Le=tr;var ir=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(ir||{}),_e=ir;var rr=(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))(rr||{}),O=rr;var ar=(h=>(h.ERROR="callError",h.DEVICES="callDevices",h.CALL_SPEC_ERROR="callSpecError",h.ICE_CONNECTION_STATE="callIceConnectionState",h.ICE_CONNECTION_TYPE="callIceConnectionType",h.ICE_RESTART="callIceRestart",h.PUSH="callPush",h.OUTGOING_CALL="callStart",h.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",h.JOIN_CONVERSATION="callJoinConversation",h.ACCEPTED_OUTGOING="callAcceptedOutgoing",h.ACCEPT_INCOMING="callAcceptIncoming",h.DECLINE_INCOMING="callDeclineIncoming",h.ACCEPT_CONCURRENT="callAcceptConcurrent",h.HANGUP="callHangup",h.MEDIA_STATUS="callMediaStatus",h.DEVICE_CHANGED="callDeviceChanged",h.SOCKET_ACTION="callSocketAction",h.ADD_PARTICIPANT="callAddParticipant",h.REMOVE_PARTICIPANT="callRemoveParticipant",h.POOR_CONNECTION="callPoorConnection",h.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",h.RELAY_POLICY="callForceRelay",h.PAT_ALLOCATED="patAllocate",h.PAT_DEALLOCATED="patDeallocate",h.PAT_ERROR="patError",h.PAT_WAITING_TIME_ERROR="patWaitingTimeError",h.PAT_OUTDATED_RESPONSE="patOutdatedResponse",h))(ar||{}),_=ar;var nr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(nr||{}),Pe=nr;var sr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(sr||{}),or=sr;function cr(a){switch(a){case 1:return"no-available-tracks";default:return"unknown-error"}}var dr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(dr||{}),Qe=dr;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 pr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(pr||{}),Q=pr;var ii=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 lr=2*1024*1024,aa=512*1024,gt=100*1024,na=5,ri="_okcls_logs_session_",sa=3e4,ur=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=lr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(ri)!==0)continue;let i=e.getItem(t);if(!i){_r(t);continue}let r=hr(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(ri,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(_r(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>lr||this.length>na-1||this.size+e>this.available);)this.deleteOldestItem()}};function mr(){return`${ri}${Date.now()}`}function hr(a){return new Blob([a]).size}function _r(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function ai(){let a=je.toString();if(!ve.available||!a)return;let e=hr(a);ve.cleanup(e);try{window.localStorage.setItem(At,a)}catch(t){if(console.warn("Failed to write log to storage",t),ve.storageSize=ve.size+e,ve.cleanup(gt+e),ve.available>=gt+e){ai();return}if(e>gt){je.bisect(),ai();return}ve.storageSize=0;return}e>aa&&(ve.add(At,e),At=mr(),je.clear(),ve.cleanup(gt))}function ni(){!ve.available||!je.length||ai()}function oa(a=!1){let e=[];try{let r=window.localStorage;for(let o of ve.items){let p=r.getItem(o.key);e.push(p)}let n=je.toString();n&&e.push(n)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(a)return t;let i=`logs_${Date.now()}.json`;return ca(t,i),i}function ca(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 gr(a,e){!ve.available||(je.push({t:Date.now(),l:a,d:e}),oi||(oi=window.setTimeout(()=>{oi=null,ni()},sa)))}function si(){ve||(ve=new ur,je=new ii,At=mr(),window.addEventListener("beforeunload",ni))}var ve,je,At,oi=null;window.__VKCallsSDKLogs__=(a=!1)=>(ve||si(),ni(),oa(a));import fr from"@vkontakte/libvpx";var ge=(o=>(o.INIT="init",o.READY="ready",o.FRAME="frame",o.ERROR="error",o.DEBUG="debug",o.LOG_ERROR="log_error",o))(ge||{});var u=class extends mt{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 ke=class{constructor(){this._worker=null}_createWorker(o,p){return c(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((l,m)=>{let b=i.join(","),R=new Blob([e,`exports.default(${b});`],{type:"application/javascript; charset=utf-8"}),V=window.URL.createObjectURL(R);this._worker=new Worker(V),this._worker.onmessage=A=>{switch(A.data.type){case ge.READY:l();break;case ge.ERROR:m(A.data.error);break;case ge.FRAME:t(A.data);break;case ge.DEBUG:s.debug(A.data.message);break;case ge.LOG_ERROR:u.log(_.ERROR,A.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 Xe=class extends ke{init(e){return c(this,null,function*(){s.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var b=Object.defineProperty;var E=a=>b(a,"__esModule",{value:!0});var M=(a,p)=>{E(a);for(var e in p)b(a,e,{get:p[e],enumerable:!0})};var V={};M(V,{default:()=>D});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var D=(a,p)=>{let e=null,n=null,g=!0;function y(){return a({locateFile:p}).then(r=>n=r)}function s(r,m,l,R,x){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(x),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let d=e.getImageBuffer();if(!d){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let c=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(d.byteLength);if(i.set(d),R){let o=new ImageData(i,c,f);createImageBitmap(o,0,0,c,f).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:i.buffer,width:c,height:f},[i.buffer])}y().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return V;})();\n',t=>{if(t.error)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)},[fr,fr.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 Ue=class extends ke{init(e){return c(this,null,function*(){s.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var l=Object.defineProperty;var u=e=>l(e,"__esModule",{value:!0});var m=(e,a)=>{u(e);for(var d in a)l(e,d,{get:a[d],enumerable:!0})};var g={};m(g,{default:()=>E});var s=(d=>(d.VP9="vp09.00.50.08",d.VP8="vp8",d))(s||{}),t=(o=>(o.INIT="init",o.READY="ready",o.FRAME="frame",o.ERROR="error",o.DEBUG="debug",o.LOG_ERROR="log_error",o))(t||{});var E=()=>{let e=null,a=!0;function d(){self.postMessage({type:t.READY})}function i(r,p,o,n=!1){if(!e||a!==o){if(!n){self.postMessage({type:t.DEBUG,message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}a=o,e?self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec changed to ${o?"VP9":"VP8"}`}):(self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec ${o?"VP9":"VP8"}`}),e=new VideoDecoder({output:c=>{self.postMessage({type:t.FRAME,data:c},[c]),c.close()},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:t.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:o?s.VP9:s.VP8})}let f=new EncodedVideoChunk({type:n?"key":"delta",timestamp:r,data:p});e.decode(f)}self.onmessage=r=>{switch(r.data.type){case t.INIT:d();break;case t.FRAME:i(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}};import{BitStream as pa}from"bit-buffer";var la=65536,Ke=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)%la!==e.sequence){s.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:n}=Ke.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,o)=>n+o.data.byteLength,0),i=new Uint8Array(t),r=0;for(let n of e)i.set(new Uint8Array(n.data),r),r+=n.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new pa(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),o=i.readBits(1)<<1|r;return o===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,o>=2&&i.index++,i.readBits(3)!==7?(i.index++,(o===1||o===3)&&(i.index+=3)):(o===1||o===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 ci="_okcls_",Ze=(()=>{try{let a=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(a,a),t=e.getItem(a)===a,e.removeItem(a),t?e:null}catch(a){return null}})();function ua(a){let e=Ze?Ze.getItem(ci+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function ma(a,e){try{Ze&&Ze.setItem(ci+a,JSON.stringify(e))}catch(t){}}function ha(a){Ze&&Ze.removeItem(ci+a)}var di;(i=>{function a(r){return ua(r)||null}i.get=a;function e(r,n){ma(r,n)}i.set=e;function t(r){ha(r)}i.remove=t})(di||(di={}));var Fe=di;function Sr(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 vr=a=>a.stop(),Er=a=>a.getTracks().forEach(vr),pi=a=>a.getVideoTracks().forEach(vr),Tr=a=>a.getVideoTracks()[0].clone();var k=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(D).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,k)}};var Ee=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(Ee||{}),ne=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(ne||{}),li=class extends Y{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 c(this,arguments,function*(e=[de.AUDIO],t=!0){if(this._stream)return;let i=e.includes(de.VIDEO),r=e.includes(de.AUDIO);if(!C.isBrowserSupported())throw new k(ee.UNSUPPORTED);try{this._stream=yield C.getUserMedia(i,r,t),this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(n=>n.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=r&&this._stream.getAudioTracks().filter(n=>n.enabled).length>0||!1}catch(n){throw new k(n)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t,i,r){let n=this.getStream(),o=this._getSendAudioTrack(),p=this.getSendVideoTrack(i);if(!n||!o&&!p&&!t)throw new Error("No local stream found");if(o&&!t){if(r){let{codecs:l}=RTCRtpSender.getCapabilities("audio"),m="audio/red",b=48e3,R=l.findIndex(V=>V.mimeType===m&&V.clockRate===b);if(R>=0){let V=[];V.push(l[R]);for(let A=0;A<l.length;A++)A!==R&&V.push(l[A]);e.getTransceivers().forEach(A=>A.setCodecPreferences(V))}}e.addTrack(o,n)}p&&!t&&e.addTrack(p,n)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return c(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return c(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=T.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);this._onDeviceChange=()=>c(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),o=n&&n.deviceId,p=this._stream.getVideoTracks()[0],l=p&&p.enabled&&p.getSettings(),m=l&&l.deviceId;if(!o&&!m)return;let b=yield navigator.mediaDevices.enumerateDevices();!e&&o&&(e=!b.find(R=>R.deviceId===o)),!t&&m&&(t=!b.find(R=>R.deviceId===m)),i()}),navigator.mediaDevices.addEventListener("devicechange",this._onDeviceChange)}_destroyDeviceChangeListener(){this._onDeviceChange&&navigator.mediaDevices.removeEventListener("devicechange",this._onDeviceChange)}_changeVideoInput(e=null){return c(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield C.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{d.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),n=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),u.log(_.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(_.ERROR,"change_video"),s.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=Tr(e)),t=this._trackVideoStreamBackup.clone(),pi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),pi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return c(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return c(this,null,function*(){try{if(e=e||(yield C.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),u.log(_.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(_.ERROR,"change_audio"),s.error("Microphone change failed",t),t}})}_changeScreen(e){return c(this,null,function*(){try{if(e=e||(yield C.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=d.consumerScreenTrack?t:yield this._videoEffect(null,t);u.log(_.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?C.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(_.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 c(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 c(this,null,function*(){if(!d.videoEffects)return t;try{return u.log(_.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(){this._destroyDeviceChangeListener(),d.videoEffects&&(this._effect=null,d.videoEffects.destroy()),this._stream&&(Er(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return c(this,null,function*(){return e?this._changeScreen():d.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return c(this,null,function*(){if(!this._stream)return;d.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield C.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=C.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return c(this,null,function*(){if(!this._stream)return;let t;e?t=(yield C.getUserAudio()).getAudioTracks()[0]:t=C.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return c(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 c(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 c(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 et=":",Ot="d",ui;(Ui=>{function a(E,h,P,F,x=!1,$=!1){let J=/[\r\n]+/,v=`\r
8
- `;if(!h&&!P&&!F&&!$)return x?z(E.split(J)).join(v):E;function z(ae){let Oe=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],g="a=rtcp-fb:111",y=ae.findIndex(L=>L.startsWith(g));return~y&&(ae[y]=ae[y]+v+Oe.join(v)),ae}function ce(ae,Oe,g){let y=ae.split(" "),L=y.slice(0,3),Z;for(Z=3;Z<y.length;Z++)g.includes(y[Z])&&L.push(y[Z]);for(Z=3;Z<y.length;Z++)!g.includes(y[Z])&&!Oe.includes(y[Z])&&L.push(y[Z]);return L.join(" ")}function M(ae,Oe){let g=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),y,L=[];for(y=0;y<ae.length;++y){let Z=ae[y].match(g);Z&&Z.length===3&&Z[2]===Oe&&L.push(Z[1])}return L}function Se(ae,Oe,g,y){let L,Z="m="+Oe;for(L=0;L<ae.length;++L)if(ae[L].startsWith(Z)){ae[L]=ce(ae[L],g,y);break}}let re=[],te=E.split(J);(P||h)&&(re=M(te,"H264"));let Ae=[];F&&(Ae=M(te,"VP9"));let Dt=[];if($&&(Dt=M(te,"red")),P){let ae=re.slice(0),Oe=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),g;for(g=0;g<te.length;++g){let L=te[g].match(Oe);L&&L.length===3&&ae.includes(L[2])&&ae.push(L[1])}let y=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(g=te.length;g--;){let L=te[g].match(y);L&&L.length===3&&ae.includes(L[2])&&te.splice(g,1)}Se(te,"video",ae,[])}else h&&Se(te,"video",[],re);return F&&Se(te,"video",[],Ae),$&&Dt.length>0&&Se(te,"audio",[],Dt),x&&z(te),te.join(v)}Ui.patchSDP=a;function e(E){return E?`${E.type||"WEB_SOCKET"}_${E.id}`:"_"}Ui.getPeerIdString=e;function t(E,h){return E&&E.id===h.id&&(E.type||"WEB_SOCKET")===(h.type||"WEB_SOCKET")}Ui.comparePeerId=t;function i(E){return c(this,null,function*(){return!E||!E.getStats?Promise.resolve(null):E.getStats(null).then(h=>{let P=null,F=null;if(h.forEach(x=>{x.type==="transport"&&x.selectedCandidatePairId?F=h.get(x.selectedCandidatePairId):x.type==="candidate-pair"&&x.state==="succeeded"&&!F&&(!x.hasOwnProperty("selected")||x.selected)&&(F=x)}),F&&F.localCandidateId){let x=h.get(F.localCandidateId);x&&(P={type:x.candidateType,ip:x.ip||x.ipAddress,port:x.port||x.portNumber})}return P}).catch(()=>null)})}Ui.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function o(E,h){let P=String(E);return n.test(P)?(s.warn(`Already composite id [${E}] type supplied [${h}]`),P):h===Q.GROUP?"g"+P:h===Q.USER?"u"+P:(s.warn(`Unknown type [${h}] for id [${E}]`),P.match(r)?"u"+P:P)}Ui.composeUserId=o;function p(E,h,P){let F=o(E,h);return l(F,P)}Ui.composeParticipantId=p;function l(E,h){return h?E+et+Ot+h:E}Ui.compose=l;function m(E){return p(E.id,E.idType||Q.USER,E.deviceIdx||0)}Ui.composeId=m;function b(E){return E.participant?m(E.participant):p(E.participantId,E.participantType||Q.USER,E.deviceIdx||0)}Ui.composeMessageId=b;function R(E){let h=String(E),P=h.match(n);return P?{id:Number(P[2]),type:P[1]==="g"?Q.GROUP:Q.USER}:(s.warn(`Unsupported compositeId [${E}]`),{id:Number(h),type:Q.USER})}Ui.decomposeId=R;function V(E){let h=E.split(et+Ot);return{compositeUserId:h[0],deviceIdx:h.length>1?parseInt(h[1],10):0}}Ui.decomposeParticipantId=V;function A(){var J,v;let E=(v=(J=window.crypto)==null?void 0:J.randomUUID)==null?void 0:v.call(J);if(E)return E;let h="0123456789abcdefghijklmnopqrstuvwxyz".split(""),P=new Array(36),F=0,x,$;for($=0;$<36;$++)$===8||$===13||$===18||$===23?P[$]="-":$===14?P[$]="4":(F<=2&&(F=33554432+Math.random()*16777216|0),x=F&15,F=F>>4,P[$]=h[$===19?x&3|8:x]);return P.join("")}Ui.uuid=A;function K(E,h){let P;function F(){let x=this,$=arguments;P&&window.clearTimeout(P),P=window.setTimeout(()=>{E.apply(x,$)},h)}return F}Ui.throttle=K;function he(E){if(!window.BigInt)return null;let h="",P=E.split(`
9
- `);for(let $ of P)if($.startsWith("a=fingerprint")){let J=$.split(" ");if(J.length===2){h=J[1];break}}if(!h)return BigInt(-1);let F=h.split(":"),x=BigInt(0);for(let $=Math.min(7,F.length-1);$>=0;$--){let J=BigInt(parseInt(F[$],16));x<<=BigInt(8),x|=J}return BigInt.asIntN(64,x)}Ui.sdpFingerprint=he;function De(E){return c(this,null,function*(){return new Promise(h=>window.setTimeout(h,E))})}Ui.delay=De;function le(E,h,P){let F=[];return E.getSenders().forEach(x=>We(h,x,x.track,P,F)),F}Ui.applySettings=le;function We(E,h,P,F,x){if(E&&P&&P.kind===ne.video){let $=P.getSettings();if($){let J=E.maxBitrateK?E.maxBitrateK*1024:null,v=$.width,z=$.height,ce=v&&z&&E.maxDimension?Math.max(1,Math.max(v,z)/E.maxDimension):null,M=E.maxFramerate?E.maxFramerate:null,Se=E.degradationPreference?E.degradationPreference:"balanced",re=F[P.id];if(re&&re.bitrate===J&&re.scaleResolutionDownBy===ce&&re.maxFramerate===M&&re.degradationPreference===Se){x[P.id]=re;return}x[P.id]={bitrate:J,scaleResolutionDownBy:ce,maxFramerate:M,degradationPreference:Se};let te=h.getParameters();te.encodings||(te.encodings=[{}]),te.encodings.forEach(Ae=>{J?Ae.maxBitrate=J:delete Ae.maxBitrate,ce?Ae.scaleResolutionDownBy=ce:delete Ae.scaleResolutionDownBy,M?Ae.maxFramerate=M:delete Ae.maxFramerate}),te.degradationPreference=Se,h.setParameters(te)}}}Ui.applyVideoTrackSettings=We;function oe(E,h){Array.isArray(h)||(h=[h]);for(let P of h)if(E.includes(P))return!0;return!1}Ui.includesOneOf=oe;function be(E){var h;return Object.entries(((h=E.participantState)==null?void 0:h.state)||{}).reduce((P,[F,x])=>(E.participantState&&(P[F]={ts:E.participantState.stateUpdateTs[F],state:x}),P),{})}Ui.mapParticipantState=be;function W(E){let h=E.map(P=>({uid:P.externalId,mediaSettings:P.mediaSettings,status:P.status,muteStates:P.muteStates,unmuteOptions:P.unmuteOptions,participantState:P.participantState}));return d.filterObservers?h.filter(P=>!P.uid.observer):h}Ui.mapSharedParticipants=W;function lt(E,h){let P=Object.keys(E),F=Object.keys(h);if(P.length!==F.length)return!1;for(let x of P)if(!F.hasOwnProperty(x)||E[x].state!==h[x].state||E[x].ts!==h[x].ts)return!1;return!0}Ui.isEqualParticipantState=lt;function xi(E,h){let P=Object.keys(E),F=Object.keys(h);if(P.length!==F.length)return!1;for(let x of P)if(!h.hasOwnProperty(x)||E[x]!==h[x])return!1;return!0}Ui.isObjectsEquals=xi;function Ni(E,h){if(E.length!==h.length)return!1;for(let P of E)if(h.indexOf(P)<0)return!1;return!0}Ui.isArraysEquals=Ni;function Li(E){return!Object.keys(E).length}Ui.isEmptyObject=Li})(ui||(ui={}));var T=ui;var $e=null,mi=null,kt=[],wt=[],hi=[],ft=null,St=null,_i=null,gi=!1,fi=!1,xt,tt,Nt,Ir=!1,Cr=!1,Si=null,vi="",Lt=[],Ei=null,yr=navigator.appVersion,_a=navigator.appName,Te=navigator.userAgent,Rr=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(Rr||{}),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={ideal:p})}let o=!1;if(t){o={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&&(o.deviceId={ideal:p}),d.videoFacingMode&&(o.facingMode={ideal:d.videoFacingMode})}this.audio=n,this.video=o,this.needVideo=!!o}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}},br=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 ga(){return c(this,null,function*(){$e=null,yield Ut()})}function fa(){$e=null,Ut().then(()=>I.onDeviceChange())}function Ut(){return c(this,null,function*(){return $e||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!mi&&navigator.mediaDevices.addEventListener&&(mi=T.throttle(fa,1e3),navigator.mediaDevices.addEventListener("devicechange",mi)),$e=navigator.mediaDevices.enumerateDevices().then(a=>{kt=a.filter(r=>r.kind==="videoinput"?(r.label&&(gi=!0),!0):!1),wt=a.filter(r=>r.kind==="audioinput"?(r.label?fi=!0:qe.isMobile()&&qe.browserName()==="Firefox"&&(fi=gi),!0):!1),hi=a.filter(r=>r.kind==="audiooutput");let e=Fe.get("videoinput"),t=Fe.get("audioinput"),i=Fe.get("audiooutput");return ft=kt.find(r=>r.deviceId===e)||null,St=wt.find(r=>r.deviceId===t)||null,_i=hi.find(r=>r.deviceId===i)||null,$e=Promise.resolve(a),a}).catch(()=>($e=null,[]))))})}function Sa(){return c(this,null,function*(){return qe.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(Ir=!0),/^a=mid:0$/m.test(t.sdp)&&(Cr=!0),a()}).catch(a)}):Promise.resolve()})}function Bt(a,e){return c(this,null,function*(){s.debug("Try to get media",a.getNative());let t=qe.hasPermissions(a.isVideo());!t&&!e&&I.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield ga()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?ee.CAMERA_PERMISSION:ee.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?ee.CAMERA_ACCESS:ee.MIC_ACCESS;break}if(a.canSimplify())return Bt(a.simplify(),e);let r=e||ee.UNKNOWN;throw I.onPermissionsError(r),r}})}function va(a){return c(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 ee.SCREEN_PERMISSION;default:throw ee.SCREEN_ACCESS}}})}function Vt(){return Lt.length||(Lt=(()=>{let a,e=!1,t=0,i="0",r=Te.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return a=/\brv[ :]+(\d+)/g.exec(Te),["IE",a&&a[1]||"Unknown",e,t,i];if(r[1]==="Safari"){if(a=Te.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(a=Te.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,Number(a[1]),i];if(a=Te.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t,i];if(a=Te.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t,i];if(a=Te.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t,i]}if(r[1]==="Chrome"){if(e=!0,t=Number(r[2]),a=Te.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t,i];if(a=Te.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t,i];if(a=Te.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t,i];if(a=Te.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t,i]}return a=Te.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),a&&a[2]!==void 0&&(i=a[2]),[r[2]?r[1]:_a,a&&a[1]||r[2]||yr,e,t,i]})()),Lt}var qe;(J=>{function a(){return c(this,null,function*(){return yield Sa(),Ut()})}J.init=a;function e(){return kt}J.getCameras=e;function t(){return wt}J.getMicrophones=t;function i(){return hi}J.getOutput=i;function r(){return kt.length>0}J.hasCamera=r;function n(){return wt.length>0}J.hasMicrophone=n;function o(){return ft}J.getSavedCamera=o;function p(){return St}J.getSavedMicrophone=p;function l(){return _i}J.getSavedOutput=l;function m(){return gi}J.hasCameraPermission=m;function b(){return fi}J.hasMicrophonePermission=b;function R(v=!1){return b()?r()&&v?m():!0:!1}J.hasPermissions=R;function V(v=!1,z=!0,ce=!0){return c(this,null,function*(){let M=n()&&z,Se=r()&&v,re;if(!M&&!Se)re=new MediaStream;else try{re=yield Bt(new vt(M,Se))}catch(te){re=new MediaStream}return!re.getVideoTracks().length&&ce&&re.addTrack(We()),!re.getAudioTracks().length&&ce&&re.addTrack(le()),re})}J.getUserMedia=V;function A(){return c(this,null,function*(){return va(new br(window.screen.width,window.screen.height))})}J.getScreenMedia=A;function K(v,z=!1){return c(this,null,function*(){let ce=z?d.videoEffectMaxWidth:d.videoMaxWidth,M=z?d.videoEffectMaxHeight:d.videoMaxHeight;return Bt(new vt(!1,v||!0,ce,M))})}J.getUserVideo=K;function he(v){return c(this,null,function*(){return Bt(new vt(v||!0,!1))})}J.getUserAudio=he;function De(v,z){return c(this,null,function*(){let M=(yield Ut()).find(Se=>Se.kind===v&&Se.deviceId===z);return M?(v==="videoinput"?ft=M:v==="audioinput"?St=M:v==="audiooutput"&&(_i=M),Fe.set(v,z),M):null})}J.saveDeviceId=De;function le(){if(!Nt||Nt.readyState==="ended"){let v=x(),z=v.createMediaStreamDestination(),ce=v.createGain();ce.gain.value=1e-5,ce.connect(z),ce.connect(v.destination);let M=v.createOscillator();M.type="sine",M.frequency.value=0,M.connect(ce),M.start(),Nt=z.stream.getAudioTracks()[0]}return Object.assign(Nt.clone(),{enabled:!1})}J.getSilentMediaTrack=le;function We(v=d.videoMinWidth,z=d.videoMinHeight){return tt||(tt=document.createElement("canvas"),tt.getContext("2d")),tt.width=v,tt.height=z,(!xt||xt.readyState==="ended")&&(xt=tt.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(xt.clone(),{enabled:!1})}J.getBlackMediaTrack=We;function oe(){if(h()==="Edge"&&Number(P())<70)return!1;try{let v=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&v.RTCPeerConnection&&v.RTCIceCandidate&&v.RTCSessionDescription&&v.HTMLCanvasElement&&v.HTMLCanvasElement.prototype.captureStream&&v.RTCRtpSender&&v.RTCRtpSender.prototype.replaceTrack&&v.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(v){return!1}}J.isBrowserSupported=oe;function be(){return!!navigator.mediaDevices.getDisplayMedia}J.isScreenCapturingSupported=be;function W(){return Ir}J.canVP8=W;function lt(){return Cr}J.isUnifiedPlan=lt;function xi(){let v=J.browserName()==="Safari"&&J.browserVersion()==="15"&&J.browserSubVersion()==="1",z=J.browserName()==="Opera"&&J.os()==="Windows";return v||z}J.isBrokenH264=xi;function Ni(){return!(J.baseChromeVersion()&&J.isMobile())}J.canPreferH264=Ni;function Li(){var v;return((v=window.RTCRtpTransceiver)==null?void 0:v.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}J.canPreferRed=Li;function Ui(){return vi||(vi=(()=>{let v={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let z in v)if(v.hasOwnProperty(z)&&v[z].test(Te))return z;return"Unknown"})()),vi}J.os=Ui;function E(){return Si===null&&(Si=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(yr)),Si}J.isMobile=E;function h(){return Vt()[0]}J.browserName=h;function P(){return Vt()[1]}J.browserVersion=P;function F(){return Vt()[3]}J.baseChromeVersion=F;function x(){return Ei||(Ei=new(window.AudioContext||window.webkitAudioContext)),Ei}J.getAudioContext=x;function $(){return Vt()[4]}J.browserSubVersion=$})(qe||(qe={}));var C=qe;var it=class{constructor(e){this._onStream=e}drawFrame(e){return c(this,null,function*(){throw new Error("Method `drawFrame` is not supported by this implementation")})}drawImage(e){throw new Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Et=class extends it{constructor(e){super(e);this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;s.debug("CanvasRenderer started"),this._useImageBitmap="ImageBitmap"in window}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}drawFrame(e){return c(this,null,function*(){let t="createImageBitmap"in e?yield e.createImageBitmap():yield createImageBitmap(e);this.drawImage(t),t.close()})}drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}destroy(){this._removeStream(),s.debug("CanvasRenderer destroyed")}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(C.browserName()==="Safari"&&Number(C.browserVersion())===15)}};var rt=class extends it{constructor(e){super(e);s.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:ne.video}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}drawFrame(e){return c(this,null,function*(){yield this._writer.write(e)})}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),s.debug("TrackGeneratorRenderer destroyed")}static isBrowserSupported(){return"VideoFrame"in window&&"MediaStreamTrackGenerator"in window&&Ue.isBrowserSupported()}};var Tt=class extends Ke{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];s.debug(`StreamBuilder started for participant [${e}]`),rt.isBrowserSupported()?this._renderer=new rt(t):this._renderer=new Et(t),Ue.isBrowserSupported()?this._decoder=new Ue:this._decoder=new Xe;let i=r=>c(this,null,function*(){"VideoFrame"in window&&r instanceof VideoFrame?yield this._renderer.drawFrame(r):this._renderer.drawImage(r)});this._decoder.init(i).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._renderer.destroy(),s.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return Et.isBrowserSupported()||rt.isBrowserSupported()}};var Ft=1,Ea=1,Pr=0,Mr=11,Dr=1,Ar=2,Or=4,kr=8;function wr(a,e,t,i,r,n,o){let p=0;e&&(p|=Dr),t&&(p|=Ar),i&&(p|=Or),o||(p|=kr);let l=new ArrayBuffer(Mr),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,Pr),m.setUint8(10,p),!o)return l;let b=new Uint8Array(l.byteLength+o.byteLength);return b.set(new Uint8Array(l),0),b.set(new Uint8Array(o),l.byteLength),b.buffer}function xr(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,o=e.getUint16(8),p=e.getUint8(10),l=!!(p&Dr),m=!!(p&Ar),b=!!(p&Or),R=!!(p&kr);if(t!==Ft)throw new Error(`Unexpected protocol version. Got ${t}, expected ${Ft}`);return{timestamp:r,start:l,end:m,keyframe:b,sequence:i,isVP9:n,ssrc:o,eos:R,data:a.slice(Mr)}}function Nr(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==Ft||e.getUint8(1)!==Ea||e.getUint16(2)!==Pr)}import*as S from"simple-ebml-builder";var Ta=Vi(2,15)-1,Ti=1,Ia=5,Ca=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 S.build(e[0])}else return new Uint8Array;let t=e.reduce((n,o)=>n+o.countSize(),0),i=new Uint8Array(t),r=0;for(let n of e){let o=S.build(n);i.set(o,r),r+=o.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,o,p;((n=this._mediaSource)==null?void 0:n.readyState)==="open"&&((o=this._sourceBuffer)==null||o.abort());let e=(p=this._sourceBuffer)==null?void 0:p.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-Ia);r-i>Ca&&(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}},Me=class extends Ke{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 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))],o=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,o])}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){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,this._mediaBuffer.cleanup(),s.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let o=Me._genWebmHeader();this._mediaBuffer.append(o);let p=Me._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(p)}let r=Math.round(i-this._clusterStartTime);if(r>Ta&&(this._clusterStartTime=i,r=0),r===0){s.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let o=Me._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(o)}let n=S.element(S.ID.SimpleBlock,[S.vintEncodedNumber(Ti),S.bytes(Me._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),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 at=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,o;let t=xr(e),i=(o=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:o.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&&Me.isBrowserSupported()?r=new Me(i,p):r=new Tt(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(Ue.isBrowserSupported()||Xe.isBrowserSupported())&&(Tt.isBrowserSupported()||Me.isBrowserSupported())}};import Lr from"@vkontakte/libvpx";var ya=1e3,It=class extends ke{constructor(e,t){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return c(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=p=>t(),r.onerror=()=>i(new Error("Video element error"));let n=r.play(),o=()=>i(new Error("Autoplay is disabled"));n?n.catch(o):o()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return c(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var 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 c(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})},[Lr,Lr.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)},ya),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 nt=class extends ke{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return c(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;s.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var E=Object.defineProperty;var g=i=>E(i,"__esModule",{value:!0});var F=(i,l)=>{g(i);for(var r in l)E(i,r,{get:l[r],enumerable:!0})};var A={};F(A,{default:()=>h});var n=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(n||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,l,r,c,s,f,t,a=null,p=0,u=!1;function V(e){l=e.readable,r=l.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&b(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),l.cancel();return}a=R,b(R,e)}}))}function b(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
11
- `,r=>{var n;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(n=r.data)==null?void 0:n.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:d.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(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 Ra=16*1024,ba=11,Ur=Ra-ba,Pa=65536,Ii=0,st=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(o=>{s.warn("sendFrame failed",o),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};nt.isBrowserSupported()?this._encoder=new nt(e,i):this._encoder=new It(e,i),this._datachannel.onmessage=r=>{Nr(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 o=wr(e,t,i,r,Ii,this._encoder.isVP9(),n);return Ii=(Ii+1)%Pa,o}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return c(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+Ur),o=e.data.byteLength<=t+n.byteLength,p=this._wrapHeader(e.timestamp,!t,o,e.type==="key",n);this._datachannel.onbufferedamountlow=o?()=>{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}o||window.setTimeout(()=>this._sendChunk(e,t+Ur,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 nt.isBrowserSupported()||It.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 f=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(f._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(f._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(f._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(f._params,e)}static get(e){return f._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.5.3-beta.9"}static get debug(){return undefined}static get protocolVersion(){return f._params.joinFromMultipleDevices?6:5}static get platform(){return f._params.platform}static set platform(e){f._params.platform=e}static get clientType(){return f._params.clientType}static set clientType(e){f._params.clientType=e}static get device(){return f._params.device}static get apiKey(){return f._params.apiKey}static get apiEnv(){return f._params.apiEnv}static get apiEndpoint(){switch(f.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return f._params.apiEnv}}static get authToken(){return f._params.authToken}static set authToken(e){f._params.authToken=e}static get anonymToken(){return f._params.anonymToken}static set anonymToken(e){f._params.anonymToken=e}static get domain(){return f._params.domain}static get iceServers(){return f._params.iceServers}static set iceServers(e){f._params.iceServers=e}static get wssBase(){return f._params.wssBase}static set wssBase(e){f._params.wssBase=e}static get wssToken(){return f._params.wssToken}static set wssToken(e){f._params.wssToken=e}static get signalingReconnectDelay(){return f._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return f._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return f._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return f._params.waitConnectionDelay}static get waitResponseDelay(){return f._params.waitResponseDelay}static get waitMessageDelay(){return f._params.waitMessageDelay}static get waitAnotherTabDelay(){return f._params.waitAnotherTabDelay}static get debugLog(){return f._params.debugLog}static get forceRelayPolicy(){return f._params.forceRelayPolicy}static set forceRelayPolicy(e){f._params.forceRelayPolicy=e}static get videoMinWidth(){return f._params.videoMinWidth}static get videoMaxWidth(){return f._params.videoMaxWidth}static set videoMaxWidth(e){f._params.videoMaxWidth=e}static get videoMinHeight(){return f._params.videoMinHeight}static get videoMaxHeight(){return f._params.videoMaxHeight}static set videoMaxHeight(e){f._params.videoMaxHeight=e}static get videoAspectRatio(){return f._params.videoAspectRatio}static get videoFrameRate(){return f._params.videoFrameRate}static get videoFacingMode(){return f._params.videoFacingMode}static get screenFrameRate(){return f._params.screenFrameRate}static get videoEffects(){return f._params.videoEffects}static set videoEffects(e){f._params.videoEffects=e}static get videoEffectMaxWidth(){return f._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){f._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return f._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){f._params.videoEffectMaxHeight=e}static get voiceParams(){return f._params.voiceParams}static get specListenerParams(){return f._params.specListenerParams}static get iceRestartWaitTime(){return f._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return f._params.transportConnectionWaitTime}static get statisticsInterval(){return f._params.statisticsInterval}static set statisticsInterval(e){f._params.statisticsInterval=e}static get networkStatisticsInterval(){return f._params.networkStatisticsInterval}static get perfStatReportEnabled(){return f._params.perfStatReportEnabled}static get callStatReportEnabled(){return f._params.callStatReportEnabled}static get producerNotificationDataChannel(){return f._params.producerNotificationDataChannel&&at.isBrowserSupported()}static get producerCommandDataChannel(){return f._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return f._params.consumerScreenDataChannel&&st.isBrowserSupported()}static get producerScreenDataChannel(){return f._params.producerScreenDataChannel&&f.producerNotificationDataChannel}static get screenShareWebmBuilder(){return f._params.screenShareWebmBuilder}static get noiseSuppression(){return f._params.noiseSuppression}static set noiseSuppression(e){f._params.noiseSuppression=e}static get preferH264(){return f._params.preferH264}static get preferVP9(){return f._params.preferVP9}static get audioNack(){return f._params.audioNack}static get consumerScreenTrack(){return f._params.consumerScreenTrack&&f.consumerScreenDataChannel}static get producerScreenTrack(){return f._params.producerScreenTrack&&f.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=f._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return f._params.movieShare&&f.videoTracksCount>0}static get videoTracksCount(){return f.producerNotificationDataChannel?f._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return f._params.breakVideoPayloadTypes}static get filteredMessages(){return f._params.filteredMessages}static get serverAudioRed(){return f._params.serverAudioRed&&C.canPreferRed()}static get p2pAudioRed(){return f._params.p2pAudioRed&&C.canPreferRed()}static get batchParticipantsOnStart(){return f._params.batchParticipantsOnStart}static get filterObservers(){return f._params.filterObservers}static get muteMode(){return f._params.muteMode}},d=f;d._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,serverAudioRed:!1,p2pAudioRed:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1};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 j(a,...e){let t=d.get(a);t&&setTimeout(t,0,...e)}function Ce(a,e,...t){if(d.filterObservers){if(Array.isArray(e)){if(e=e.filter(i=>!i.observer),!e.length)return}else if(e.observer)return}j(a,e,...t)}function we(a){return Object.assign({},a)}function ot(a){return a.slice()}var Ci;(Oe=>{function a(g,y){j("onLocalStream",g,we(y))}Oe.onLocalStream=a;function e(g,y){j("onScreenStream",g,we(y))}Oe.onScreenStream=e;function t(g,y){j("onLocalStreamUpdate",we(g),y)}Oe.onLocalStreamUpdate=t;function i(g){j("onLocalStatus",g)}Oe.onLocalStatus=i;function r(g,y){Ce("onRemoteStream",g,y)}Oe.onRemoteStream=r;function n(g,y,L){Ce("onRemoteLive",g,y,L)}Oe.onRemoteLive=n;function o(g,y){Ce("onRemoteScreenStream",g,y)}Oe.onRemoteScreenStream=o;function p(g,y,L,Z){Ce("onConversation",g,we(y),we(L),Z)}Oe.onConversation=p;function l(g,y){Ce("onRemoteMediaSettings",g,we(y))}Oe.onRemoteMediaSettings=l;function m(g,y){Ce("onRemoteParticipantState",g,we(y))}Oe.onRemoteParticipantState=m;function b(g,y,L=null){Ce("onRemoteStatus",g,y,L)}Oe.onRemoteStatus=b;function R(g,y,L=null){Ce("onParticipantStatus",g,y,L)}Oe.onParticipantStatus=R;function V(){j("onPermissionsRequested")}Oe.onPermissionsRequested=V;function A(g){j("onPermissionsError",g)}Oe.onPermissionsError=A;function K(g){Ce("onRemoteRemoved",g)}Oe.onRemoteRemoved=K;function he(g,y,L){j("onCallState",g,y,we(L))}Oe.onCallState=he;function De(g,y){j("onDeviceSwitched",g,y)}Oe.onDeviceSwitched=De;function le(g,y,L,Z=!1,Xt=!1,Zt=null,ea=null){j("onMuteStates",we(g),ot(y),ot(L),Z,Xt,Zt,ea)}Oe.onMuteStates=le;function We(g,y){Ce("onRolesChanged",g,ot(y))}Oe.onRolesChanged=We;function oe(g){j("onLocalRolesChanged",ot(g))}Oe.onLocalRolesChanged=oe;function be(g,y){Ce("onPinnedParticipant",g,y)}Oe.onPinnedParticipant=be;function W(g){j("onLocalPin",g)}Oe.onLocalPin=W;function lt(g){j("onOptionsChanged",ot(g))}Oe.onOptionsChanged=lt;function xi(){j("onCallAccepted")}Oe.onCallAccepted=xi;function Ni(){j("onRateNeeded")}Oe.onRateNeeded=Ni;function Li(g){Ce("onSpeakerChanged",g)}Oe.onSpeakerChanged=Li;function Ui(g){j("onVolumesDetected",ot(g))}Oe.onVolumesDetected=Ui;function E(g,y){j("onLocalVolume",g,y)}Oe.onLocalVolume=E;function h(g,y){j("onJoinStatus",g,y)}Oe.onJoinStatus=h;function P(g,y){j("onHangup",g,y)}Oe.onHangup=P;function F(g){j("onMultipartyChatCreated",we(g))}Oe.onMultipartyChatCreated=F;function x(){j("onDeviceChange")}Oe.onDeviceChange=x;function $(g){j("onFingerprintChange",g)}Oe.onFingerprintChange=$;function J(){j("onTokenExpired")}Oe.onTokenExpired=J;function v(g,y,L=!1){j("onChatMessage",g,y,L)}Oe.onChatMessage=v;function z(g,y,L=!1){j("onCustomData",g,y,L)}Oe.onCustomData=z;function ce(g,y,L,Z,Xt,Zt){j("onRecordStarted",g,y,L,Z,Xt,Zt)}Oe.onRecordStarted=ce;function M(){j("onRecordStopped")}Oe.onRecordStopped=M;function Se(g){j("onLocalNetworkStatusChanged",g)}Oe.onLocalNetworkStatusChanged=Se;function re(g){j("onNetworkStatusChanged",g)}Oe.onNetworkStatusChanged=re;function te(g,...y){j("onDebugMessage",g,...y)}Oe.onDebugMessage=te;function Ae(g,y){let L=Object.assign({},g,{memory:y});j("onStatistics",L)}Oe.onStatistics=Ae;function Dt(){j("onAutoplayError")}Oe.onAutoplayError=Dt;function ae(g,y,L){j("onChatRoomUpdated",g,y,L)}Oe.onChatRoomUpdated=ae})(Ci||(Ci={}));var I=Ci;var Br=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(Br||{}),yi;(oe=>{let a="📞",e=(be,...W)=>{I.onDebugMessage(be,...W)},t=!1,i=(be,W)=>(...lt)=>{be(...lt),gr(W,lt)},r=console.debug.bind(console,a),n=console.log.bind(console,a),o=console.warn.bind(console,a),p=console.error.bind(console,a),l=e.bind(null,"DEBUG"),m=e.bind(null,"LOG"),b=e.bind(null,"WARN"),R=e.bind(null,"ERROR");oe.debug=l,oe.log=m,oe.warn=b,oe.error=R;function De(){return t}oe.enabled=De;function le(be){t=be,d.debugLog&&si(),be?(oe.debug=d.debugLog?i(r,"DEBUG"):r,oe.log=d.debugLog?i(n,"LOG"):n,oe.warn=d.debugLog?i(o,"WARN"):o,oe.error=d.debugLog?i(p,"ERROR"):p):(oe.debug=d.debugLog?i(l,"DEBUG"):l,oe.log=d.debugLog?i(m,"LOG"):m,oe.warn=d.debugLog?i(b,"WARN"):b,oe.error=d.debugLog?i(R,"ERROR"):R)}oe.toggle=le;function We(be,...W){switch(be){case"DEBUG":oe.debug(...W);break;case"LOG":oe.log(...W);break;case"WARN":oe.warn(...W);break;case"ERROR":oe.error(...W);break}}oe.send=We})(yi||(yi={}));var s=yi;var ct=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(ct||{}),ue;(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 o(l,m){return l.id===m.id&&l.type===m.type}p.compare=o})(ue||(ue={}));var me;(r=>{function a(n,o="USER",p=0){return{id:n,type:o,deviceIdx:p}}r.fromId=a;function e(n){return`{"id":"${n.id}","type":"${n.type}","deviceIdx":"${n.deviceIdx}"}`}r.toString=e;function t(n,o){return Object.assign({deviceIdx:o},ue.fromSignaling(n))}r.fromSignaling=t;function i(n){return n&&typeof n=="object"?n.deviceIdx:0}r.getDeviceIdx=i})(me||(me={}));var Ie=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(Ie||{}),Vr="s",Fr="m";function He(a){return a.participantId+(a.mediaType?et+Vr+a.mediaType:"")+(a.streamName?et+Fr+a.streamName:"")}function Ct(a){let e=a.split(et),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 Vr:i=Ma(p.slice(1));break;case Fr:r=p.slice(1);break;case Ot:n=Number.parseInt(p.slice(1),10);break;default:throw new Error("Unexpected parameter type "+p.charAt(0)+" in stream description "+a)}return{participantId:T.compose(t,n),mediaType:i,streamName:r}}function Ma(a){for(let e of Object.keys(Ie))if(e===a)return Ie[e];return null}function Ri(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!(!Ri(a.camera,e.camera)||!Ri(a.screenSharing,e.screenSharing))}function bi(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function Hr(a){try{return btoa(JSON.stringify(a))}catch(e){s.warn("WaitingParticipant: failed convert to string",a,e)}return null}function Gr(a){try{return JSON.parse(atob(a))}catch(e){s.warn("WaitingParticipant: failed convert from string",a,e)}return null}var yt=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(_.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,u.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?(s.log("Failed to fix RV"),u.log(_.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(s.log("Fixed RV"),u.log(_.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===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 o;if(d.muteMode||!((o=this._output)==null?void 0:o.audioTrack))return;let e=C.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"),I.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 c(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=C.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw u.log(_.ERROR,"change_output"),s.error("Output change failed",r),r}})}};var Da=90,Aa=3,jt=class extends Y{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}),I.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>Da?s.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Aa)&&(s.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var Oa=44100,Rt=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=C.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=Oa/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,o)=>n+o,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 Y{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&I.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===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 Rt("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 Wr="videochat-epi",ka=5e3,wa=3e4,Je=class extends Y{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,U.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Wr)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return c(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&d.perfStatReportEnabled&&this._previousTimestamp+ka<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),d.callStatReportEnabled&&this._previousCallStatReportTimestamp+wa<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return c(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(Wr,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,n)=>(n.kind==="video"?(n.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+n.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+n.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=n.framesDropped,r.nack_sent+=n.nackCount,r.pli_sent+=n.pliCount,r.fir_sent+=n.firCount):(n.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+n.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+n.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=n.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=n.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=n.removedSamplesForAcceleration,r.concealed_audio_samples+=n.concealedSamples,r.silent_concealed_audio_samples+=n.silentConcealedSamples,r.audio_concealment_events+=n.concealmentEvents),r),t),e.outbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.nack_received+=n.nackCount,r.pli_received+=n.pliCount,r.fir_received+=n.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,n=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,o=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,p=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,l=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,m=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=n/r*1e3,i.removed_audio_samples_for_acceleration=o/r*1e3,i.concealed_audio_samples=p/r*1e3,i.concealed_silent_audio_samples=l/r*1e3,i.concealment_audio_avg_size=p/m,i.total_audio_energy=t.total_audio_energy}u.logCustom("callStat",i),s.log("Sent call stats",i),this._previousCallStatReport=t}};var xa=1e3;function se(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 Ge(a,e){return t=>t[a]===e}function Na(a){return(e,t)=>e[a]-t[a]}function $t(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function La(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Ua(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Pi(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=Ua(t[1])?Pi(t[1]):t[1],e),{})}function Ba(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function Va(a){return c(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(Ba).then(La)})}function Fa(a){let e=a.filter(Ge("type","candidate-pair")).sort(Na("priority")).find(jr(Ge("nominated",!0),Ge("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(Ge("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(Ge("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}})),Pi(t)}function Ha(a,e){let t=$t("id",a),i=a.filter(jr(Ge("type","inbound-rtp"),Ge("type","outbound-rtp")));C.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,o)=>{if(!n[o.ssrc])n[o.ssrc]=o;else{let p=Object.assign({},n[o.ssrc],o),l=n[o.ssrc].isRemote?o:n[o.ssrc];p.id=l.id,p.type=l.type,delete p.isRemote,delete p.remoteId,n[p.ssrc]=p}return n},{})));let r={};if(C.browserName()==="Safari"){let n=a.filter(Ge("type","track"));r=$t("trackIdentifier",n)}return i.map(n=>{let o=Number(n.ssrc),p=n.mediaType||n.kind,l=n.trackId,m=n.type,b=n.codecId;if(C.browserName()==="Safari"){let V=/^.+_([\d]+)$/.exec(n.id);if(V&&(o=parseInt(V[1],10)),p=n.id.indexOf("Audio")>0?"audio":"video",e[o]){let A=p+"-"+e[o];r[A]&&(l=r[A].id)}}if(!m||!o||!p)return null;let R={ssrc:o,type:m,kind:p,bytesReceived:se(n,"bytesReceived"),bytesSent:se(n,"bytesSent"),jitter:se(n,"jitter"),packetsLost:se(n,"packetsLost"),packetsReceived:se(n,"packetsReceived"),packetsSent:se(n,"packetsSent"),fractionLost:se(n,"fractionLost"),pliCount:se(n,"pliCount"),firCount:se(n,"firCount"),nackCount:se(n,"nackCount"),userId:e[o]};if(p==="video"){let V=se(n,"framesDecoded"),A=se(n,"totalInterFrameDelay"),K=se(n,"totalSquaredInterFrameDelay");R.interframeDelayVariance=(K-A*A/V)/V}if(p==="audio"&&(R.totalSamplesReceived=se(n,"totalSamplesReceived"),R.concealedSamples=se(n,"concealedSamples"),R.insertedSamplesForDeceleration=se(n,"insertedSamplesForDeceleration"),R.removedSamplesForAcceleration=se(n,"removedSamplesForAcceleration"),R.silentConcealedSamples=se(n,"silentConcealedSamples"),R.concealmentEvents=se(n,"concealmentEvents"),R.totalAudioEnergy=se(n,"totalAudioEnergy")),b&&t[b]){let V=t[b];R.clockRate=V.clockRate,R.mimeType=V.mimeType}if(l&&t[l]){let V=t[l];R.frameHeight=V.frameHeight,R.frameWidth=V.frameWidth,R.framesDecoded=V.framesDecoded,R.framesReceived=V.framesReceived,R.framesDropped=V.framesDropped}return Pi(R)}).filter(n=>!!n)}function Ga(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 o=t[n],p=i[n];if(!(!o||!p)){if(o.bytesReceived&&o.bytesReceived>p.bytesReceived&&(o.bandwidth=Math.round((o.bytesReceived-p.bytesReceived)/r)),o.bytesSent&&o.bytesSent>p.bytesSent&&(o.bandwidth=Math.round((o.bytesSent-p.bytesSent)/r)),o.packetsReceived)if(o.packetsReceived>p.packetsReceived||o.packetsLost>p.packetsLost){let l=o.packetsLost-p.packetsLost,m=o.packetsReceived-p.packetsReceived;o.packetLoss=parseFloat((100*l/(l+m)).toFixed(2))}else o.packetLoss=0;o.framesDropped&&p.framesDropped&&o.framesDropped>p.framesDropped&&(o.framesDroppedDelta=parseFloat(((o.framesDropped-p.framesDropped)/r).toFixed(0)))}}),a}function bt(i,r){return c(this,arguments,function*(a,e,t={}){let n=yield Va(a),o={timestamp:Date.now(),transport:Fa(n),rtps:Ha(n,t)};return e?Ga(o,e):(yield T.delay(xa),bt(a,o,t))})}var qt=.8,Ye=class extends Y{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._perfStatReporter=new Je(this,i,!0),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,!1,!0,d.p2pAudioRed),this._applySettings()}catch(o){u.log(_.ERROR,"addTrack-direct"),s.error("Unable to add media source tracks",o,{participantId:this._participantId}),this._failedOnCreate=o;return}this._createOffer(!1).catch(o=>{this._state===N.IDLE?this._failedOnCreate=o:this.close(o)})}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 c(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,!1,!0,d.p2pAudioRed),this._applySettings()}catch(i){u.log(_.ERROR,"addTrack-direct"),s.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={}})}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(U.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(N.FAILED)):(s.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(N.CLOSED)),this._triggerEvent(U.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(s.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(U.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case O.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case O.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 O.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=T.getPeerIdString(e.peerId);T.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){s.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw u.log(_.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 c(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 c(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(_.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(U.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(U.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return c(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=>c(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===N.IDLE||e===N.OPENED?this._setState(N.CONNECTING):this._setState(N.RECONNECTING);break}}_onConnectionStateChange(){switch(s.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),u.log(_.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(N.CONNECTED),this._stopReconnection(),T.getPeerConnectionHostInfo(this._pc).then(e=>{e&&u.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||(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(pe.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(u.log(_.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(_.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return c(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(_.ERROR,"createOffer-direct"),i}).then(i=>c(this,null,function*(){return s.debug("Created offer",{participantId:this._participantId,offer:i}),i=Ye._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(_.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return c(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(_.ERROR,"createAnswer-direct"),e}).then(e=>c(this,null,function*(){return s.debug("Created answer",{participantId:this._participantId,answer:e}),e=Ye._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(_.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!C.baseChromeVersion();return e.sdp=T.patchSDP(e.sdp,d.preferH264&&C.canPreferH264(),C.isBrokenH264(),d.preferVP9,t&&d.audioNack,d.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{s.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),u.log(_.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}bt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:pe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:pe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(U.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=le=>le.rtt<=this._networkLimits.goodNet.rtt&&le.loss<=this._networkLimits.goodNet.loss,i=le=>le.rtt>=this._networkLimits.badNet.rtt||le.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((le,We)=>Math.max(le,We.packetLoss||0),0),o={rtt:this._lastNetworkStat.rtt*(1-qt)+r*qt,loss:this._lastNetworkStat.loss*(1-qt)+n*qt},p=i(o),l=t(o),m=i(this._remoteNetworkStat),b=t(this._remoteNetworkStat),R=i(this._lastNetworkStat),V=t(this._lastNetworkStat),he=p||m?.2:l&&b?1:0,De=Date.now();if((R!==p||V!==l||De-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},o)},null).catch(le=>{s.warn("Unable to send [bad-net]",le)})),he){let le={};le[this._participantId]=le[""]=he,this._triggerEvent(U.NETWORK_STATUS,le)}this._lastNetworkStat.rtt=o.rtt,this._lastNetworkStat.loss=o.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=T.sdpFingerprint(e);if(t===null){s.warn("Fingerprint calculation is unsupported");return}this._fingerprint===null?this._fingerprint=t:(I.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=T.applySettings(this._pc,e,this._prevConsumerSettings))}};var Kr=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Kr||{}),Pt=Kr;import{decode as dt}from"messagepack";var Mi=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var n,o;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let p=dt(r);return Object.entries(p).forEach(([K,he])=>{let De=Ct(K);this.streamDescriptionByCompactId.set(he,De)}),null;case 2:case 4:let l=dt(r),m=[];for(let K of l){let he=this.getStreamDescription(K);he&&m.push(he.participantId)}return i===2?{type:"notification",notification:O.AUDIO_ACTIVITY,activeParticipants:m}:{type:"notification",notification:O.STALLED_ACTIVITY,stalledParticipants:m};case 3:let b=dt(r);return{type:"notification",notification:O.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(b))==null?void 0:n.participantId};case 5:let R=dt(r);return{type:"notification",notification:O.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:R[0],maxDimension:R[1]}};case 6:let V=dt(r),A={};for(let[K,he]of Object.entries(V)){let De=(o=this.getStreamDescription(Number(K)))==null?void 0:o.participantId;De&&(A[De]=he/100)}return{type:"notification",notification:O.NETWORK_STATUS,statuses:A};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return s.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=dt(e),i=[];for(let[r,n]of Object.entries(t)){let o=n[0],p=n[1],l=n[2],m;if(o!==null){if(m=this.getStreamDescription(o),!m){s.error(`could not uncompress participant ID ${o}`);continue}}else m=null;if(l===null){s.error("unexpected null sequenceNumber",r,n);continue}let b=Pe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,R=p?p>>>0:null;i.push({participantStreamDescription:m,streamId:b,rtpTimestamp:R,sequenceNumber:l})}return{type:"notification",notification:O.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Wa=90,ja=4294967295,ye=class extends Y{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=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,_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 Je(this,e),this._serverSettings=i,s.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(e=!1){if(this._isOpen){s.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(s.error("ServerTransport: Closed",e),this._setState(N.FAILED)):(s.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,ye._closeDataChannel(this._producerNotification),ye._closeDataChannel(this._producerCommand),ye._closeDataChannel(this._producerScreen),ye._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(U.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=()=>{let n=r.readyState;n==="open"?(s.debug(`[${t}] data channel opened`),r.onerror=o=>{s.error(`[${t}] data channel error`,o)},i(r)):s.error(`[${t}] data channel open failed, state [${n}]`)}}_openConnection(e=!1){s.debug("ServerTransport: Open single connection");let t={};C.baseChromeVersion()&&(t.sdpSemantics=ye._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=T.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=ye._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,Pt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Mi,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,Pt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,Pt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,d.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){s.error("ServerTransport: Unable to add media source tracks",i),u.log(_.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,Pt.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(U.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(U.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(U.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(U.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
- `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Pe.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 st(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 at(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(U.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(U.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){s.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(C.getBlackMediaTrack()).catch(p=>{s.error("Could not disable video upload",p)});return}let o=this._mediaSource.getSendVideoTrack();if(!r&&n&&o){s.log("Enabling video upload"),this._disabledSenders.delete(i);let p=i.track;p.enabled=o.enabled,i.replaceTrack(o).then(()=>p.stop()).catch(l=>{s.error("Could not enable video upload",l)})}T.applyVideoTrackSettings(e,i,o!=null?o: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(U.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 c(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield bt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(U.REMOTE_DATA_STATS,{inbound:{topology:pe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:pe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(o=>o.type==="inbound-rtp"&&o.kind==="audio"&&this._ssrcMap[o.ssrc]==="mix");if(!t)return;let i=Pe.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let o=t.bytesReceived-r.bytesReceived;o>=0&&o<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(U.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Je.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:ye._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount,red:d.serverAudioRed};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return c(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(_.ERROR,"setRemoteDescription-single"),i}).then(()=>c(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(_.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=T.patchSDP(i.sdp,!1,C.isBrokenH264(),!1),i)).then(i=>c(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(_.ERROR,"setLocalDescription-single"),i}).then(i=>c(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(_.ERROR,"acceptProducer")}).then(()=>c(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 c(this,null,function*(){if(!!this._isOpen)switch(e.notification){case O.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case O.REALLOC_CON:this._reconnect();break;case O.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case O.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case O.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case O.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return c(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(U.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(U.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(_.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),T.getPeerConnectionHostInfo(e).then(r=>{r&&u.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=>{s.error("ServerTransport: Unable to replace track",r),u.log(_.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=C.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(C.browserName(),Number(C.browserVersion()))}getStreamWaitingTimeMs(e,t){if(!this._pc)return u.log(_.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(_.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 o=r[0].rtpTimestamp;if(!Number.isInteger(o))return u.log(_.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),s.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${o}`),0;let p=t-o&ja,l=Math.ceil(p/Wa);return Math.min(100,Math.max(0,l))}};var U=(A=>(A.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",A.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",A.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",A.REMOTE_ALL_STALL="REMOTE_ALL_STALL",A.REMOTE_DATA_STATS="REMOTE_DATA_STATS",A.STATE_CHANGED="STATE_CHANGED",A.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",A.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",A.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",A.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",A.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",A.NETWORK_STATUS="NETWORK_STATUS",A.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",A))(U||{}),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||{}),pe=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(pe||{}),Di=class extends Y{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,i=!1){let r=!1;for(let n of e){if(this._opened.indexOf(n)!==-1){s.warn(`The participant [${n}] has already had opened transport`);continue}if(this._allocated.indexOf(n)===-1){s.warn(`The participant [${n}] has no allocated transport`);continue}this._opened.push(n),r=!0}!r||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),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===O.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===O.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(_.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||[],o=i.length&&r.length?T.composeParticipantId(i[0],r[0],n[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 p=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=o===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._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 ye(this._signaling,this._mediaSource,this._serverSettings);return 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("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;d.noiseSuppression!==e&&(d.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(u.log(_.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(_.PAT_WAITING_TIME_ERROR,"noTransport"),s.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var ze=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(ze||{}),Ai=class extends Y{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,U.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,U.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,U.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,U.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===ne.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Rt(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===Pe.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e===pe.DIRECT&&(this._activeParticipants=null)}};var Oi=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(Oi||{}),ki=class extends Y{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i===pe.SERVER,this.subscribe(e,ze.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,U.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,U.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>d.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*d.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent("SPEAKER_CHANGED",e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e===pe.SERVER}};var Jt=class extends Y{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,U.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,ze.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&&(s.warn("Transport failed, send callSpecError"),u.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)()&&(s.warn("There is not connected transport, send callSpecError"),u.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),u.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&s.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Ka=1e3,$a=1e4;var qa=15,B=class extends Y{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),Ka))}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,o=!1){return c(this,null,function*(){if(B._activationMutex)throw u.log(_.ERROR,"startCall"),s.warn("Conversation: there is already running activation"),new k(D.FAILED);B._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let p=this._mediaSource.getMediaSettings();t===Ne.CHAT||e.length>1?this._logWithMediaSettings(_.OUTGOING_MULTIPARTY_CALL,p):this._logWithMediaSettings(_.OUTGOING_CALL,p);let l=yield this._startConversation(e,t,Be.OUTGOING,i,r,n,o);if(!this._conversation)throw new k(D.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 k(D.CANCELED);s.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let m=Object.values(this._participants),b;return d.batchParticipantsOnStart&&(b=T.mapSharedParticipants(m)),I.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),I.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,b),I.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),B._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(m,q.WAITING),this._conversation}catch(p){throw this._close(p,"Unable to start conversation"),p}finally{B._activationMutex=!1}})}onJoin(e){return c(this,null,function*(){var t;if(B._activationMutex)throw u.log(_.ERROR,"joinCall"),s.warn("Conversation: there is already running activation"),new k(D.FAILED);B._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.JOIN_CONVERSATION,r);let n=yield this._joinConversation(e);if(!this._conversation)throw new k(D.UNKNOWN_ERROR);return this._conversation.observer=i,I.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(s.log("In waiting hall"),B._current=this,B._activationMutex=!1,this._signaling.readyToSend(),I.onLocalStatus(q.WAITING_HALL),this._conversation):this._onJoinPart2(n)}catch(i){throw B._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return c(this,null,function*(){s.debug("Join conversation part 2"),B._activationMutex=!0;try{if(this._participantState=G.ACCEPTED,!this._conversation||!this._mediaSource)throw new k(D.UNKNOWN_ERROR);if(this._conversation.observer||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 k(D.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=T.mapSharedParticipants(t)),I.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),I.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 c(this,arguments,function*(e,t=Q.USER,i){if(B._activationMutex)throw s.warn("Conversation: there is already running activation"),new k(D.REJECTED);B._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new k(D.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(_.PUSH,"rejected"),new k(D.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),u.log(_.PUSH,"accepted"),B._current=this,B._delayedHangup)throw new k(D.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(ti.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>T.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return c(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new k(D.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_CONCURRENT,e),s.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),I.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 c(this,null,function*(){if(this._state!=="IDLE")throw u.log(_.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 k(D.UNKNOWN_ERROR);this._state="PROCESSING",s.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=T.mapSharedParticipants(i)),I.onCallAccepted(),I.onLocalStream(this._mediaSource.getStream(),t),I.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),I.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(Ve.MUTE)||n.includes(Ve.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 c(this,null,function*(){var e;if(this._state!=="IDLE")throw u.log(_.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(_.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=G.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(D.REJECTED)),this._close(new k(D.REJECTED))})}hangup(){return c(this,null,function*(){s.debug("Hangup");let e=this._state==="ACTIVE"?D.HUNGUP:D.CANCELED;u.log(_.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new k(e))):I.onHangup(new k(D.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return c(this,null,function*(){if(!this._signaling.ready){this._close(new k(D.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=D.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(T.composeId(n),n,r)})}removeParticipant(e,t=!1){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let n of e)(n.state===G.CALLED||n.state===G.ACCEPTED)&&(this._transport.isAllocated(n.id)||this._transport.allocate(n.id,t)),n.state===G.ACCEPTED&&i.push(n.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&s.error(t,e),s.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(D.FAILED):u.log(_.ERROR,e.hangup),B._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([D.CANCELED,D.NOT_FRIENDS,D.CALLEE_IS_OFFLINE,D.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===D.REJECTED&&!e.remote){I.onHangup(e,i),this.destroy();return}if(e.hangup===D.HUNGUP&&(!e.remote||this._participantState===G.CALLED)){I.onHangup(e,i),this.destroy();return}if(e.hangup===D.MISSED&&!e.remote){I.onHangup(e,i),this.destroy();return}if(e.hangup===D.SOCKET_CLOSED&&B._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===D.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,B._current=null,B._delayedHangup=!1,I.onHangup(e||new k(D.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,B._current=null,B._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return c(this,null,function*(){let t=yield this._api.getConversationParams(e);s.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let o=r.urls.filter((p,l,m)=>m.indexOf(p)===l);o.push(`${o[o.length-1]}?transport=tcp`),i.push({urls:o,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="",o=!1,p=!1){return c(this,null,function*(){let l=T.uuid();s.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let m=r.includes(de.VIDEO),b=yield this._api.startConversation(l,e,t,m,n,o,p);s.debug("Api.startConversation",b),yield this._getConversationParams(b.id);let R=yield this._connectSignaling(Le.START,b);return yield this._setConversation(b,R,i),R})}_joinConversation(e){return c(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n,observedIds:o}=e;s.debug("Conversation: join",{conversationId:t,joinLink:n,observedIds:o});let p=i.includes(de.VIDEO),l;if(t)l=yield this._api.joinConversation(t,p,r);else if(n)l=yield this._api.joinConversationByLink(n,p,o);else throw new k(D.UNKNOWN_ERROR);s.debug("Api.joinConversation",l),yield this._getConversationParams(l.id);let m=yield this._connectSignaling(Le.JOIN,l);return yield this._setConversation(l,m,Be.JOINING),m})}_prepareConversation(r){return c(this,arguments,function*(e,t=Q.USER,i){s.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let n=this._api.getUserId();if(!n)throw new k(D.UNKNOWN_ERROR);let p=(yield this._getConversationParams(e)).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},m=yield this._connectSignaling(Le.ACCEPT,l);return B._current&&(B._current._participantState===G.ACCEPTED||B._current._participantState===G.CALLED)?(s.log("Push rejected (busy)"),u.log(_.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(D.BUSY),Promise.reject({hangup:D.BUSY})):(B._current&&(B._current.destroy(),B._current=null),yield this._setConversation(l,m,Be.INCOMING,t),m)})}_createParticipant(e){return c(this,null,function*(){var i;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:[],observedIds:[]},e);if(e.externalId){let r=T.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(r,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return((i=t.observedIds)==null?void 0:i.length)&&(t.externalId.observer=!0),t})}_getParticipantId(e){return c(this,null,function*(){try{let t=T.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new k(D.NETWORK_ERROR),t),t}})}_setConversation(n,o,p){return c(this,arguments,function*(e,t,i,r=Q.USER){let l=t.conversation.participants.map(A=>A.id);yield this._api.prepareUserIds(l);let m=this._api.getUserId(),b=e.device_idx||0;if(!m){let A=(t.conversation.participants||[]).find(K=>T.comparePeerId(K.peerId,t.peerId));if(!A)throw new k(D.UNKNOWN_ERROR);m=Number(A.id),A.idType&&(r=A.idType),A.deviceIdx&&(b=A.deviceIdx),this._api.setUserId(m)}let R=T.composeParticipantId(m,r,b),V=yield this._getParticipantId(R);this._conversation={userId:m,compositeUserId:R,externalId:V,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||pe.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),u.log(_.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new k(D.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||pe.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new li;return this.subscribe(e,Ee.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Ee.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new yt(e),e}_connectSignaling(e,t){return c(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 c(this,null,function*(){if(!!this._conversation)for(let t of e){let i=T.composeId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(s.debug(`Local roles changed: ${t.roles}`),I.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],D.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&me.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:fe(t.mediaSettings),participantState:T.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?q.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}),t.roles&&t.roles.length&&(s.debug(`Roles for participant [${i}] changed: ${t.roles}`),I.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){T.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(ei.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Di(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new jt,this.subscribe(this._transport,U.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,U.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,U.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,U.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,U.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,U.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,U.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,U.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,U.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,U.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,U.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Be.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===G.ACCEPTED||t.state===G.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new Ai(this._transport),this.subscribe(this._volumesDetector,ze.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new ki(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,Oi.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=C.getCameras().length,t=C.getMicrophones().length;s.debug("Cameras: "+e+(C.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(C.hasMicrophonePermission()?"✔":"✖")),u.log(_.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"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),!!this._participants[e.id]&&(t===D.HUNGUP?this._setParticipantsStatus([e],q.HANGUP):this._setParticipantsStatus([e],q.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Ie.CAMERA,stopStream:!0}]),delete this._participants[e.id],I.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 c(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&&me.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:fe(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}),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),u.log(_.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){s.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=qa;i++){let r=T.compose(e,i),n=this._participants[r];n&&t.push(n)}if(!t.length){s.warn(`Participant [${e}] isn't in conversation`);return}if(this._transport)for(let i of t)this._transport.close(i.id);u.log(_.REMOVE_PARTICIPANT)}changeDevice(e){return c(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new yt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ee.UNKNOWN)})}toggleScreenCapturing(e){return c(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ee.UNKNOWN)})}setVideoStream(e,t=!1){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return c(this,null,function*(){if(this._mediaSource)return u.log(_.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return c(this,null,function*(){if(this._mediaSource)return u.log(_.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return c(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let n=typeof r.uid=="object"?r.uid:me.fromId(r.uid),o=me.toString(n);i[o]=r.priority}for(let r of Object.values(this._participants)){let n=me.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return c(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return c(this,null,function*(){let t={};return t[He(e)]="kf",this._signaling.updateDisplayLayout(t)})}updateDisplayLayout(e){return c(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:me.fromId(r.uid),o=this._api.getCachedOkIdByExternalId(n);if(!o){let b=me.toString(n);s.log(`Unknown participant external ID ${b}`);continue}let p=T.compose(o,n.deviceIdx),l=He({participantId:p,mediaType:r.mediaType,streamName:r.streamName}),m=this._participants[p];m&&(m.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){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]=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)&&(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===Ie.STREAM||i.mediaType===Ie.SCREEN)?I.onRemoteLive(r.externalId,i.streamName,null):I.onRemoteStream(r.externalId,null),u.log(_.PAT_DEALLOCATED)):s.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return c(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,n]of Object.entries(t.errorCodeByParticipantId||{})){let o=Ct(r),p=this._participants[o.participantId];if(p){let l;typeof n!="number"?(s.warn(`Unexpected error code ${n} received for participant ${o.participantId}`),l=or.UNKNOWN_ERROR):l=cr(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]+$a>Date.now())break;let o=r[0];this._stopStreaming(o),e[o]=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),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 c(this,null,function*(){s.log("Promoted in waiting hall",!e.demote),e.demote?(s.log("Kicked from waiting hall"),this._close(new k(D.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return c(this,arguments,function*(e,t=0,i=[]){s.log(`Chat room updated: ${e}`);let n=[],o=[];i.length&&(i.forEach(p=>{if(p.externalId){let l=ue.fromSignaling(p.externalId);n.push(l),this._api.cacheExternalId(p.id.id,l)}else o.push(T.decomposeId(p.id.id).id)}),o.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(o))),I.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var p,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===Ie.SCREEN)return;let i=He(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(_.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,o=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(o<=0){this._streamWaitTimerByStreamDescription.delete(i);let m=t.participantId,b=this._participants[m];if(!b){u.log(_.PAT_ERROR,"participantMissing"),s.error(`Could not find participant by ID: ${m}`);return}let R=this._streamByStreamId.get(n);if(!R){u.log(_.PAT_ERROR,"streamNotFound"),s.error(`Could not find stream by ID: ${n}`);return}u.log(_.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let V=(p=e.participantStreamDescription)==null?void 0:p.mediaType;if(V===Ie.STREAM||V===Ie.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&I.onRemoteLive(b.externalId,e.participantStreamDescription.streamName,R);else{let A=(d.producerScreenTrack?null:b.secondStream)||R;I.onRemoteStream(b.externalId,A)}}else{s.debug(`Waiting for ${o} until stream ${n} for ${i} is switched`);let m=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),o);this._streamWaitTimerByStreamDescription.set(i,m)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(He(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(He(i)))return i}else{let i={participantId:t,mediaType:Ie.CAMERA};if(this._streamIdByStreamDescription.has(He(i)))return i;let r={participantId:t,mediaType:Ie.SCREEN};if(this._streamIdByStreamDescription.has(He(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?T.includesOneOf(this._conversation.roles,[Qe.ADMIN,Qe.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!T.includesOneOf(this._conversation.roles,[Qe.ADMIN,Qe.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return c(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return c(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return c(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Yi(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return c(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Gr(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let o=n.participants||[],p=[],l=[],m=null;return o.length&&(o.forEach(b=>{if(b.externalId){let R=ue.fromSignaling(b.externalId);p.push(R),this._api.cacheExternalId(b.id.id,R)}else l.push(T.decomposeId(b.id.id).id)}),l.length&&!p.length&&(p=yield this._api.getExternalIdsByOkIds(l)),n.hasMore&&(m=Hr(o[o.length-1].id))),{participants:p,pageMarker:m,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return c(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return c(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return c(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return c(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return c(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 c(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 o=yield this._signaling.updateMovie(n);if(o.error)throw new Error(o.error)})}removeMovie(e){return c(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 c(this,null,function*(){let o={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},p=yield this._signaling.startStream(o);return p.error?Promise.reject(p.message):p})}stopStream(){return c(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return c(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return c(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return c(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 c(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return c(this,null,function*(){var t,i;!this._conversation||(s.debug("Local media stream changed",e.mediaSettings),I.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return c(this,null,function*(){var t,i;if(s.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;I.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){s.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&I.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"&&I.onRemoteParticipantState(i.externalId,i.participantState))}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(s.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),I.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case O.ACCEPTED_CALL:return this._onAcceptedCall(e);case O.HUNGUP:return this._onHungup(e);case O.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case O.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case O.CLOSED_CONVERSATION:return this._onClosedConversation(e);case O.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case O.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case O.RATE_CALL_DATA:return this._onNeedRate();case O.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case O.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case O.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case O.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case O.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case O.REGISTERED_PEER:return this._onPeerRegistered(e);case O.SWITCH_MICRO:return this._onMicSwitched(e);case O.CHAT_MESSAGE:return this._onChatMessage(e);case O.CUSTOM_DATA:return this._onCustomData(e);case O.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case O.RECORD_STOPPED:return this._onRecordInfo(null);case O.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case O.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case O.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case O.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case O.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case O.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case O.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return c(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._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 o=T.composeId(n),p=n.roles||[];if(o===this._conversation.compositeUserId){t=fe(n.mediaSettings),_t(this._conversation.roles,p)||this._onRolesChanged(o,p);continue}r.push(o);let l=this._participants[o];if(!l)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let m=fe(n.mediaSettings);Sr(m,l.mediaSettings)||this._changeRemoteMediaSettings(o,m);let b=T.mapParticipantState(n),R=l.participantState;T.isEqualParticipantState(b,R)||this._changeRemoteParticipantState(o,b),_t(p,l.roles)||this._onRolesChanged(l.id,p)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],D.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 c(this,null,function*(){let t=T.composeMessageId(e),i=T.getPeerIdString(e.peerId);if(s.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new k(D.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(_.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Be.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=T.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new k(e.reason,{remote:!0}));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===D.REJECTED?G.REJECTED:G.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,D.HUNGUP)}_onAddedParticipant(e){return c(this,null,function*(){var r,n;s.debug(`Participant added [${e.participantId}]`);let t=T.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&&me.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:fe(e.participant.mediaSettings),state:e.participant.state,participantState:T.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}),i=this._participants[t]),i.state=G.CALLED,i.mediaSettings=fe((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=T.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),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return c(this,null,function*(){var r,n;s.debug(`Participant joined [${e.participantId}]`);let t=T.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&&me.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:fe(e.participant.mediaSettings),state:e.participant.state,participantState:T.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Be.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=G.ACCEPTED,i.mediaSettings=fe(e.mediaSettings),i.participantState=T.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],null,!!((n=this._conversation)==null?void 0:n.observer))),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new k(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=T.composeMessageId(e);this._changeRemoteMediaSettings(t,fe(e.mediaSettings))}_onParticipantStateChanged(e){let t=T.composeMessageId(e);this._changeRemoteParticipantState(t,T.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),I.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return c(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=bi(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=bi(this._serverSettings,r),s.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=T.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return c(this,null,function*(){I.onDeviceSwitched(de.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return c(this,null,function*(){let t=T.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),I.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return c(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=T.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),I.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return c(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);I.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else I.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,I.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,I.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return c(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],o=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),I.onMuteStates(i,r,n,e.muteAll,e.unmute,p.externalId,o==null?void 0:o.externalId));return}T.isObjectsEquals(this._conversation.muteStates,i)&&T.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,o)))})}_processMuteState(){return c(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==G.ACCEPTED)return;let o=Object.assign({},this._conversation.muteStates),p=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),m=Object.entries(o);for(let[b,R]of m)if(!(R!==Ve.MUTE&&R!==Ve.MUTE_PERMANENT)&&(this._isCallAdmin()&&R===Ve.MUTE_PERMANENT&&(o[b]=Ve.MUTE),!(!e.includes(b)||i)))switch(b){case de.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(I.onDeviceSwitched(de.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case de.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(I.onDeviceSwitched(de.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case de.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(I.onDeviceSwitched(de.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}I.onMuteStates(o,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]?I.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&I.onLocalPin(!0)),this._participants[e]?I.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&I.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!Ji(this._conversation.options,e)&&(this._conversation.options=e,I.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,I.onLocalNetworkStatusChanged(r);else{let o=this._participants[i];o.networkRating=r,t.push({uid:o.externalId,rating:r})}}if(t.length===0)return;s.log("Received network status update: ",e),I.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){I.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 o=this._streamByStreamId.get(n);if(!o){u.log(_.PAT_ERROR,"streamNotFound"),s.error(`Could not find stream by ID: ${n}`);return}I.onRemoteStream(i.externalId,i.secondStream||o)}else{let r=t||i.remoteStream;r&&I.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===pe.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes($i.ADD_PARTICIPANT);I.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&I.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})}I.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(I.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return c(this,null,function*(){s.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,o)=>{if(o in this._participants){let p=this._participants[o];n.push(p),t===N.CONNECTED&&(p.remoteStream||(p.mediaSettings&&this._changeRemoteMediaSettings(o,p.mediaSettings),this._changeRemoteParticipantState(o,p.participantState)),this._updateDisplayLayoutFromCache(o))}else s.warn(`Participant [${o}] isn't in conversation`);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return c(this,null,function*(){s.debug(`Local transport state has changed: ${e}`),e===N.CONNECTED&&I.onLocalStatus(q.CONNECTED),e===N.CONNECTING&&I.onLocalStatus(q.CONNECTING),e===N.RECONNECTING&&I.onLocalStatus(q.RECONNECT),e===N.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(D.FAILED)),this._close(new k(D.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return c(this,null,function*(){if(e.endsWith(Pe.AUDIO_MIX))s.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(Pe.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],q.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(I.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),t.removeTrack(i)),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;I.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 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!==Pe.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e===pe.DIRECT&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let n=this._participants[r];e||this._lastStalled[r]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,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 o=this._participants[n];o&&!this._remoteAllStalled&&i.push(o)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let o=this._participants[n];o&&!this._remoteAllStalled&&r.push(o)}),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;!C.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(s.debug("Toggle join availability",{available:t,chatId:e}),I.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return c(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==pe.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,o)=>(o.status!==t&&(o.status=t,d.batchParticipantsOnStart?n.push(o.externalId):I.onParticipantStatus(o.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&I.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}};var zt;function Ja(){return c(this,null,function*(){var a;if(d.apiEnv!=="AUTO")return d.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(a=i==null?void 0:i.Answer[0])==null?void 0:a.data;if(!r)throw new Error("Wrong DNS response");return 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 $r(){if(!d.apiKey)throw new k(ee.API,{message:"Required argument apiAppKey not passed"})}function wi(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Jr(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${zt}/fb.do`,r)}function qr(i){return c(this,arguments,function*(a,e={},t=!1){zt||(zt=yield Ja());let r=Jr(a,e,t);return Ya(r)})}function Ya(a){return c(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 Jr(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 Qa=10,Xa=700,Za=3e3,Qt=class extends ut{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return c(this,arguments,function*(e,t={},i=!1){let n=o=>c(this,null,function*(){try{return yield qr(e,t,i)}catch(p){if(!p.hasOwnProperty("error_msg")&&(o++,s.debug(`${e} network error, attempt ${o}...`),o<Qa))return yield T.delay(Math.min(o*Xa,Za)),n(o);throw s.warn(e,"error",p),p}});return n(0)})}_call(r){return c(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){s.warn("Api call error",n);let o=ee.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:o=D.SERVICE_DISABLED;break;case 1102:o=D.CALLEE_IS_OFFLINE;break;case 1103:o=D.NOT_FRIENDS;break;case 1104:case 1106:o=D.EXTERNAL_API_ERROR;break}throw new k(o,{message:n.error_msg,code:n.error_code})}})}userId(e){return c(this,null,function*(){let t=T.decomposeId(e).id;return X.isEmpty()?ue.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),ue.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return c(this,null,function*(){X.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return c(this,null,function*(){if(!this._uuid){let t=Fe.get("uuid");t||(t=T.uuid(),Fe.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&&I.onTokenExpired(),new k(ee.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})};wi("log.externalLog",t)}init(){$r()}joinConversation(e,t=!1,i){return c(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 c(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="",o=!1,p=!1){return c(this,null,function*(){let l={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case Ne.USER:l.uids=t.join(",");break;case Ne.GROUP:l.gid=t[0];break;case Ne.CHAT:l.chatId=t[0];break}return o&&(l.createJoinLink=!0),n&&(l.payload=n),d.domain&&(l.domainId=d.domain),p&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return c(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return c(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return c(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return c(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i){return c(this,null,function*(){let r={joinLink:e,isVideo:t,protocolVersion:d.protocolVersion};return(i==null?void 0:i.length)&&(r.observedIds=i.join(",")),d.anonymToken&&(r.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",r)})}getOkIdsByExternalIds(e){return c(this,null,function*(){let t=ue.fromIds(e),i=[],r={methods:[]},n=[],o=Object.keys(this._externalUidsCache),p=Object.values(this._externalUidsCache);for(let m of t){let b=ue.toString(m),R=p.indexOf(b);R>-1?i.push(Number(o[R])):(n.push(b),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:m.id,anonym:m.type===ct.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((m,b)=>{if(m.ok){let R=Number(m.ok.ok_id);this._externalUidsCache[R]=n[b],i.push(R)}}),i})}getExternalIdsByOkIds(e){return c(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(ue.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(ue.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=ue.toString(e),n=i.indexOf(r);return n>-1?T.composeUserId(t[n],Q.USER):null}cacheExternalId(e,t){let i=T.decomposeId(e).id;this._externalUidsCache[i]=ue.toString(t)}getConversationParams(e){return c(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:D.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),wi("vchat.hangupConversation",t)}removeHistoryRecords(e){return c(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return c(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,n]of Object.entries(i.external_ids))t[r]=ue.fromIdToString(n,ct.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=ue.fromIdToString(n,ct.ANONYM);return t}catch(i){return t}})}};var Yr=(v=>(v.RECOVER="recover",v.ACCEPT_CALL="accept-call",v.ADD_PARTICIPANT="add-participant",v.REMOVE_PARTICIPANT="remove-participant",v.HANGUP="hangup",v.TRANSMIT_DATA="transmit-data",v.ACCEPT_PRODUCER="accept-producer",v.ALLOCATE_CONSUMER="allocate-consumer",v.CHANGE_MEDIA_SETTINGS="change-media-settings",v.CHANGE_PARTICIPANT_STATE="change-participant-state",v.CHANGE_STREAM_PRIORITIES="change-streams-priorities",v.UPDATE_DISPLAY_LAYOUT="update-display-layout",v.REPORT_PERF_STAT="report-perf-stat",v.RECORD_START="record-start",v.RECORD_STOP="record-stop",v.RECORD_SET_ROLE="record-set-role",v.RECORD_GET_STATUS="record-get-status",v.SWITCH_MICRO="switch-micro",v.SWITCH_TOPOLOGY="switch-topology",v.REQUEST_REALLOC="request-realloc",v.CHAT_MESSAGE="chat-message",v.CHAT_HISTORY="chat-history",v.CUSTOM_DATA="custom-data",v.GRANT_ROLES="grant-roles",v.MUTE_PARTICIPANT="mute-participant",v.PIN_PARTICIPANT="pin-participant",v.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",v.CHANGE_OPTIONS="change-options",v.GET_WAITING_HALL="get-waiting-hall",v.PROMOTE_PARTICIPANT="promote-participant",v.REQUEST_TEST_MODE="request-test-mode",v.ADD_MOVIE="add-movie",v.UPDATE_MOVIE="update-movie",v.REMOVE_MOVIE="remove-movie",v))(Yr||{}),H=Yr;var zr="open",Qr=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0,()=>d.movieShare],en=10,Re=class extends ht{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="+Re._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<Qr.length;t++)Qr[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 c(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){u.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 c(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=T.decomposeParticipantId(t.participantId),o=T.decomposeId(n.compositeUserId);t=Object.assign({},t,{participantId:o.id,participantType:o.type}),n.deviceIdx&&(t.deviceIdx=n.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return c(this,arguments,function*(e,t={},i=0){let n=o=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(o),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===zr&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){u.log(_.SOCKET_ACTION,"not_opened"),s.warn("Socket not opened"),o.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(u.log(_.SOCKET_ACTION,"invalid_state"),s.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(o),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((o,p)=>{let l=(b,R=!1)=>{!i||R?p(b):(s.debug("Resending a signaling message",e,m.sequence),i--,n(m))},m={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:o,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 c(this,null,function*(){return this._send(H.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return c(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return c(this,null,function*(){return this._send(H.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return c(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return c(this,null,function*(){return this._send(H.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return c(this,null,function*(){return this._send(H.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},en)})}changeParticipantState(e){return c(this,null,function*(){return this._send(H.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return c(this,null,function*(){return this._send(H.ADD_PARTICIPANT,Hi({participantId:e},t))})}removeParticipant(e,t=!1){return c(this,null,function*(){return this._send(H.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return c(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(H.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return c(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(H.ACCEPT_PRODUCER,i)})}changePriorities(e){return c(this,null,function*(){return this._send(H.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return c(this,null,function*(){return this._send(H.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return c(this,null,function*(){return this._send(H.ADD_MOVIE,e)})}updateMovie(e){return c(this,null,function*(){return this._send(H.UPDATE_MOVIE,e)})}removeMovie(e){return c(this,null,function*(){return this._send(H.REMOVE_MOVIE,e)})}startStream(e){return c(this,null,function*(){return this._send(H.RECORD_START,e)})}stopStream(){return c(this,null,function*(){return this._send(H.RECORD_STOP)})}recordSetRole(e,t){return c(this,null,function*(){return this._send(H.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return c(this,null,function*(){return this._send(H.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return c(this,null,function*(){return this._send(H.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return c(this,null,function*(){return this._send(H.REQUEST_REALLOC)})}reportPerfStat(e){return c(this,null,function*(){return this._send(H.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return c(this,null,function*(){return this._send(H.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return c(this,null,function*(){return this._send(H.CHAT_HISTORY,{count:e})})}customData(e,t){return c(this,null,function*(){return this._send(H.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return c(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 c(this,null,function*(){return this._sendRaw(H.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return c(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(H.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return c(this,null,function*(){return this._send(H.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return c(this,null,function*(){return this._send(H.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return c(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 c(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===Le.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(_.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(_.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:O.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(_.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(u.log(_.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new k(D.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(_e.NOTIFICATION,{notification:O.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 k(ee.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(u.log(_.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(_.SOCKET_ACTION,"error"),s.error("Signaling error",e)}_onClose(e){u.log(_.SOCKET_ACTION,"closed"),s.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Re.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(Re.RECONNECT_MAX_DELAY,Re.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));s.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),u.log(_.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Le.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],u.log(_.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Re.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)!==zr){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}Re._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Re.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),Re.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(n))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new k(ee.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Re.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(Le.RETRY)},Re.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},xe=Re;xe.RECONNECT_DELAY=d.signalingReconnectDelay,xe.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,xe.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,xe.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,xe.WAIT_RESPONSE_DELAY=d.waitResponseDelay,xe.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var Xr=(t=>(t.KING="KING",t.PAWN="PAWN",t))(Xr||{}),tn=Xr;var pt,ie,Mt=null,Hu={getCameras:C.getCameras,getMicrophones:C.getMicrophones,getOutput:C.getOutput,hasCamera:C.hasCamera,hasMicrophone:C.hasMicrophone,getSavedCamera:C.getSavedCamera,getSavedMicrophone:C.getSavedMicrophone,getSavedOutput:C.getSavedOutput,hasCameraPermission:C.hasCameraPermission,hasMicrophonePermission:C.hasMicrophonePermission,hasPermissions:C.hasPermissions,getUserMedia:C.getUserMedia,getUserVideo:C.getUserVideo,getUserAudio:C.getUserAudio,saveDeviceId:C.saveDeviceId,isBrowserSupported:C.isBrowserSupported,isScreenCapturingSupported:C.isScreenCapturingSupported,os:C.os,isMobile:C.isMobile,browserName:C.browserName,browserVersion:C.browserVersion,baseChromeVersion:C.baseChromeVersion,getAudioContext:C.getAudioContext};function rn(a){ie=a}function an(a){pt=a}function Gu(a){Mt=a}function Wu(a){d.videoEffects=a}function ju(a){return c(this,null,function*(){if(d.set(a),C.browserName()==="Sferum"&&(d.platform=`SFERUM:${C.browserVersion()}`),ie||rn(new Qt),pt||an(()=>new xe),d.debug&&(Zr.disableLog(!1),s.toggle(!0)),s.log(`Calls SDK ${d.sdkVersion}`,a),yield C.init(),!C.isBrowserSupported())throw new k(ee.UNSUPPORTED);ie.init()})}function Ku(n){return c(this,arguments,function*(a,e=[de.AUDIO],t="",i=!1,r=!1){let o=[],p=[];if(Array.isArray(a)?o=a.length?a:[]:a&&(o=[a]),o.length&&(p=yield ie.getOkIdsByExternalIds(o),!p.length))throw new k(D.CALLEE_IS_OFFLINE);return nn(p,Ne.USER,e,t,i,r)})}function nn(o){return c(this,arguments,function*(a,e=Ne.USER,t,i="",r=!1,n=!1){if(w.current())throw s.error("There is already active call"),new k(D.FAILED);return new w(ie,pt(),Mt).onStart(a,e,t,i,r,n)})}function $u(a){return c(this,null,function*(){return sn(a)})}function sn(i){return c(this,arguments,function*(a,e=Q.USER,t){if(a===w.id())throw new Error("Push has already been processed");return new w(ie,pt(),Mt).onPush(a,e,t)})}function qu(a){return c(this,null,function*(){return a&&(d.authToken=a),ie.authorize()})}function Ju(){return c(this,arguments,function*(a=[de.AUDIO]){let e=w.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function Yu(){return c(this,null,function*(){let a=w.current();if(a)return a.decline()})}function zu(t){return c(this,arguments,function*(a,e=[de.AUDIO]){return on(a,e)})}function on(a,e,t){return c(this,null,function*(){if(w.current())throw s.error("There is already active call"),new k(D.FAILED);return new w(ie,pt(),Mt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function Qu(r){return c(this,arguments,function*(a,e=[de.AUDIO],t,i){if(w.current())throw s.error("There is already active call"),new k(D.FAILED);return t&&(d.anonymToken=t),new w(ie,pt(),Mt).onJoin({joinLink:a,mediaOptions:e,observedIds:i})})}function Xu(){return c(this,null,function*(){let a=w.current();if(a)return a.hangup();w.hangupAfterInit()})}function Zu(a,e){return c(this,null,function*(){let t=yield ie.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return cn(t[0],e)})}function cn(a,e){return c(this,null,function*(){let t=w.current();t&&(yield t.addParticipant(T.composeUserId(a,Q.USER),e))})}function em(a,e=!1){return c(this,null,function*(){let t=yield ie.getOkIdsByExternalIds([a]);return dn(t[0],e)})}function dn(a,e=!1){return c(this,null,function*(){let t=w.current();t&&(yield t.removeParticipant(T.composeUserId(a,Q.USER),e))})}function tm(a,e){return c(this,null,function*(){let t=yield C.saveDeviceId(a,e),i=w.current();return t&&i?i.changeDevice(a):Promise.reject()})}function im(a){return c(this,null,function*(){let e=w.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function rm(a,e=!1){return c(this,null,function*(){let t=w.current();t&&(yield t.setVideoStream(a,e))})}function am(a){return c(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalVideo(a))})}function nm(a){return c(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalAudio(a))})}function sm(a,e,t){return c(this,null,function*(){let i=w.current();if(i)return i.setLocalResolution(a,e,t)})}function om(a){return c(this,null,function*(){let e=w.current();e&&(yield e.changePriorities(a))})}function cm(a){return c(this,null,function*(){let e=w.current();e&&(yield e.changeParticipantState(a))})}function dm(a){return c(this,null,function*(){let e=w.current();e&&(yield e.updateDisplayLayout(a))})}function pm(a,e,t=!1){return c(this,null,function*(){let i=yield ie.getOkIdsByExternalIds([a]);return pn(i[0],e,t)})}function pn(a,e,t=!1){return c(this,null,function*(){let i=w.current();i&&(yield i.grantRoles(T.composeUserId(a,Q.USER),e,t))})}function lm(){return c(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield ie.getOkIdsByExternalIds([a]))[0]),ln(i,e,t,me.getDeviceIdx(a))})}function ln(){return c(this,arguments,function*(a=null,e,t=[],i=0){let r=w.current();if(r){let n=a?T.composeParticipantId(a,Q.USER,i):null;yield r.muteParticipant(n,e,t)}})}function um(a,e=!1){return c(this,null,function*(){let t=yield ie.getOkIdsByExternalIds([a]);return un(t[0],e,me.getDeviceIdx(a))})}function un(a,e=!1,t=0){return c(this,null,function*(){let i=w.current();i&&(yield i.pinParticipant(T.composeParticipantId(a,Q.USER,t),e))})}function mm(a){return c(this,null,function*(){let e=w.current();e&&(yield e.updateMediaModifiers(a))})}function hm(a){return c(this,null,function*(){let e=w.current();e&&(yield e.changeOptions(a))})}function _m(a,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ie.getOkIdsByExternalIds([e]))[0]),mn(a,t)})}function mn(a,e=null){return c(this,null,function*(){let t=w.current();if(t){let i=e?T.composeUserId(e,Q.USER):null;yield t.chatMessage(a,i)}})}function gm(a=10){return c(this,null,function*(){let e=w.current();if(e)return e.chatHistory(a)})}function fm(a,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ie.getOkIdsByExternalIds([e]))[0]),hn(a,t,me.getDeviceIdx(e))})}function hn(a,e=null,t=0){return c(this,null,function*(){let i=w.current();if(i){let r=e?T.composeParticipantId(e,Q.USER,t):null;yield i.customData(a,r)}})}function Sm(a="",e=!1){return c(this,null,function*(){return(yield ie.createConversation(T.uuid(),a,e)).join_link})}function vm(){return c(this,null,function*(){let a=w.current();return a?a.createJoinLink():Promise.reject()})}function Em(){return c(this,null,function*(){let a=w.current();return a?a.removeJoinLink():Promise.reject()})}function Tm(a,e){return c(this,null,function*(){return ie.getAnonymTokenByLink(a,e)})}function Im(a){let e=w.current();e&&e.setVolume(a)}function Cm(a){d.forceRelayPolicy=a}function ym(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return c(this,null,function*(){let n=w.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function Rm(){return c(this,null,function*(){let a=w.current();return a?a.stopStream():Promise.reject()})}function bm(a,e){return c(this,null,function*(){let t=w.current();if(t){let i=yield ie.getOkIdsByExternalIds([a]),r=me.getDeviceIdx(a);return t.recordSetRole(T.composeParticipantId(i[0],Q.USER,r),e)}return Promise.reject()})}function Pm(){return c(this,null,function*(){let a=w.current();return a?a.getStreamInfo():Promise.reject()})}function Mm(a){return c(this,null,function*(){let e=w.current();return e?e.addMovie(a):Promise.reject()})}function Dm(a,e,t,i){return c(this,null,function*(){let r=w.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function Am(a){return c(this,null,function*(){let e=w.current();return e?e.removeMovie(a):Promise.reject()})}function Om(a){d.statisticsInterval=a;let e=w.current();if(e)return e.updateStatisticsInterval()}function km(a){Zr.disableLog(!a),s.toggle(a)}function wm(a,...e){!d.debugLog||s.send(a,"[external]",...e)}function xm(a){return c(this,null,function*(){let e=w.current();if(e)return e.videoEffect(a)})}function Nm(a){return c(this,null,function*(){let e=w.current();e&&(yield e.setAudioStream(a))})}function Lm(a=null,e,t=!1){return c(this,null,function*(){let i=w.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(a,e,t)})}function Um(a,e=!1){return c(this,null,function*(){let t=w.current();if(!t)throw new Error("Conversation not found");let i=yield ie.getOkIdsByExternalIds([a]);return t.promoteParticipant(T.composeUserId(i[0],Q.USER),e)})}function Bm(a){return c(this,null,function*(){yield ie.removeHistoryRecords(a)})}export{Qt as Api,ut as BaseApi,mt as BaseLogger,ht as BaseSignaling,Be as CallDirection,Ne as CallType,ei as ChatRoomEventType,ti as ConversationOption,Br as DebugMessageType,ct as ExternalIdType,Rr as FacingMode,ee as FatalError,k as HangupReason,D as HangupType,de as MediaOption,ne as MediaTrackKind,Ie as MediaType,Ve as MuteState,G as ParticipantState,q as ParticipantStatus,tn as RecordRole,xe as Signaling,H as SignalingCommandType,Le as SignalingConnectionType,O as SignalingNotification,Qe as UserRole,Q as UserType,T as Utils,Ju as acceptCall,Mm as addMovie,Zu as addParticipant,cn as addParticipantInternal,qu as authorize,Hu as browser,nn as callInternal,Ku as callTo,im as captureScreen,hm as changeConversationOptions,tm as changeDevice,cm as changeParticipantState,om as changePriorities,xm as changeVideoEffect,gm as chatHistory,_m as chatMessage,mn as chatMessageInternal,vm as createJoinLink,fm as customData,hn as customDataInternal,km as debug,wm as debugMessage,Yu as declineCall,Cm as forceRelayPolicy,Tm as getAnonymTokenByLink,Pm as getStreamInfo,Lm as getWaitingHall,pm as grantRoles,pn as grantRolesInternal,Xu as hangup,ju as init,zu as joinCall,Qu as joinCallByLink,on as joinCallInternal,lm as muteParticipant,ln as muteParticipantInternal,um as pinParticipant,un as pinParticipantInternal,$u as processPush,sn as processPushInternal,Um as promoteParticipant,bm as recordSetRole,Bm as removeHistoryRecords,Em as removeJoinLink,Am as removeMovie,em as removeParticipant,dn as removeParticipantInternal,rn as setApi,Nm as setAudioStream,sm as setLocalResolution,Gu as setLogger,mm as setMediaModifiers,an as setSignalingFactory,Om as setStatisticsInterval,Wu as setVideoEffects,rm as setVideoStream,Im as setVolume,Sm as startConversation,ym as startStream,Rm as stopStream,nm as toggleLocalAudio,am as toggleLocalVideo,dm as updateDisplayLayout,Dm as updateMovie};
7
+ var oa=Object.defineProperty,ca=Object.defineProperties;var da=Object.getOwnPropertyDescriptors;var Ki=Object.getOwnPropertySymbols;var pa=Object.prototype.hasOwnProperty,la=Object.prototype.propertyIsEnumerable;var $i=Math.pow,qi=(n,e,t)=>e in n?oa(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,rt=(n,e)=>{for(var t in e||(e={}))pa.call(e,t)&&qi(n,t,e[t]);if(Ki)for(var t of Ki(e))la.call(e,t)&&qi(n,t,e[t]);return n},si=(n,e)=>ca(n,da(e));var o=(n,e,t)=>new Promise((i,r)=>{var a=l=>{try{p(t.next(l))}catch(m){r(m)}},s=l=>{try{p(t.throw(l))}catch(m){r(m)}},p=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);p((t=t.apply(n,e)).next())});import na from"webrtc-adapter";var St=class{createJoinLink(e){return o(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return o(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return o(this,null,function*(){return""})}log(e){}prepareUserIds(e){return o(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return o(this,null,function*(){})}cleanup(){}};var vt=class{log(e,t,i=!1){}destroy(){}};var Y=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 Y{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e,t){}getNextCommandSequenceNumber(){return 0}};var Ji=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(Ji||{}),je=Ji;var Yi=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(Yi||{}),He=Yi;var zi=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(zi||{}),oi=zi;var Qi=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(Qi||{}),Xi=Qi;var Zi=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(Zi||{}),ci=Zi;function er(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}function tr(n,e){let t=new Set(n);for(let[i,r]of Object.entries(e))r?t.add(i):t.delete(i);return Array.from(t)}var ir=(j=>(j.CAMERA_PERMISSION="camera",j.MIC_PERMISSION="mic",j.CAMERA_ACCESS="cameralock",j.MIC_ACCESS="miclock",j.MIC_NOT_FOUND="nomic",j.SCREEN_PERMISSION="screenpermission",j.SCREEN_ACCESS="screenlock",j.CONNECTION="connection",j.NETWORK="network",j.UNKNOWN="unknown",j.UNSUPPORTED="unsupported",j.SIGNALING_FAILED="signalingfailed",j.API="api",j.AUTH="auth",j))(ir||{}),ae=ir;var rr=(K=>(K.CANCELED="CANCELED",K.REJECTED="REJECTED",K.REMOVED="REMOVED",K.HUNGUP="HUNGUP",K.MISSED="MISSED",K.BUSY="BUSY",K.FAILED="FAILED",K.NETWORK_ERROR="NETWORK_ERROR",K.KILLED="KILLED",K.BANNED="BANNED",K.HAS_ACTIVE_CALL="HAS_ACTIVE_CALL",K.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",K.NOT_FRIENDS="NOT_FRIENDS",K.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",K.UNKNOWN_ERROR="UNKNOWN_ERROR",K.UNSUPPORTED="UNSUPPORTED",K.OLD_VERSION="OLD_VERSION",K.SERVICE_DISABLED="SERVICE_DISABLED",K.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",K.SOCKET_CLOSED="SOCKET_CLOSED",K.ENDED="ENDED",K.KILLED_WITHOUT_DELETE="KILLED_WITHOUT_DELETE",K))(rr||{}),b=rr;var ar=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(ar||{}),he=ar;var nr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(nr||{}),Ke=nr;var sr=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(sr||{}),G=sr;var or=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(or||{}),Ge=or;var cr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(cr||{}),Te=cr;var dr=(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.MOVIE_UPDATE_NOTIFICATION="movie-update-notification",k.MOVIE_SHARE_INFO="movie-share-info",k.MOVIE_SHARE_STARTED="movie-share-started",k.MOVIE_SHARE_STOPPED="movie-share-stopped",k))(dr||{}),M=dr;var pr=(h=>(h.ERROR="callError",h.DEVICES="callDevices",h.CALL_SPEC_ERROR="callSpecError",h.ICE_CONNECTION_STATE="callIceConnectionState",h.ICE_CONNECTION_TYPE="callIceConnectionType",h.ICE_RESTART="callIceRestart",h.PUSH="callPush",h.OUTGOING_CALL="callStart",h.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",h.JOIN_CONVERSATION="callJoinConversation",h.ACCEPTED_OUTGOING="callAcceptedOutgoing",h.ACCEPT_INCOMING="callAcceptIncoming",h.DECLINE_INCOMING="callDeclineIncoming",h.ACCEPT_CONCURRENT="callAcceptConcurrent",h.HANGUP="callHangup",h.MEDIA_STATUS="callMediaStatus",h.DEVICE_CHANGED="callDeviceChanged",h.SOCKET_ACTION="callSocketAction",h.ADD_PARTICIPANT="callAddParticipant",h.REMOVE_PARTICIPANT="callRemoveParticipant",h.POOR_CONNECTION="callPoorConnection",h.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",h.RELAY_POLICY="callForceRelay",h.PAT_ALLOCATED="patAllocate",h.PAT_DEALLOCATED="patDeallocate",h.PAT_ERROR="patError",h.PAT_WAITING_TIME_ERROR="patWaitingTimeError",h.PAT_OUTDATED_RESPONSE="patOutdatedResponse",h))(pr||{}),S=pr;var lr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(lr||{}),Le=lr;var ur=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(ur||{}),mr=ur;function hr(n){switch(n){case 1:return"no-available-tracks";default:return"unknown-error"}}var _r=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(_r||{}),at=_r;function It(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}var gr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(gr||{}),ee=gr;var di=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 fr=2*1024*1024,ua=512*1024,Tt=100*1024,ma=5,pi="_okcls_logs_session_",ha=3e4,Sr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=fr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(pi)!==0)continue;let i=e.getItem(t);if(!i){Ir(t);continue}let r=Er(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(Tt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(pi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Ir(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>fr||this.length>ma-1||this.size+e>this.available);)this.deleteOldestItem()}};function vr(){return`${pi}${Date.now()}`}function Er(n){return new Blob([n]).size}function Ir(n){try{window.localStorage.removeItem(n)}catch(e){console.error("Failed to remove log from storage",e)}}function li(){let n=Ye.toString();if(!ye.available||!n)return;let e=Er(n);ye.cleanup(e);try{window.localStorage.setItem(Nt,n)}catch(t){if(console.warn("Failed to write log to storage",t),ye.storageSize=ye.size+e,ye.cleanup(Tt+e),ye.available>=Tt+e){li();return}if(e>Tt){Ye.bisect(),li();return}ye.storageSize=0;return}e>ua&&(ye.add(Nt,e),Nt=vr(),Ye.clear(),ye.cleanup(Tt))}function ui(){!ye.available||!Ye.length||li()}function _a(n=!1){let e=[];try{let r=window.localStorage;for(let s of ye.items){let p=r.getItem(s.key);e.push(p)}let a=Ye.toString();a&&e.push(a)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(n)return t;let i=`logs_${Date.now()}.json`;return ga(t,i),i}function ga(n,e){let t=document.createElement("a"),i=new Blob([n],{type:"text/json"});t.href=URL.createObjectURL(i),t.download=e,t.click()}function Tr(n,e){!ye.available||(Ye.push({t:Date.now(),l:n,d:e}),hi||(hi=window.setTimeout(()=>{hi=null,ui()},ha)))}function mi(){ye||(ye=new Sr,Ye=new di,Nt=vr(),window.addEventListener("beforeunload",ui))}var ye,Ye,Nt,hi=null;window.__VKCallsSDKLogs__=(n=!1)=>(ye||mi(),ui(),_a(n));import Cr from"@vkontakte/libvpx";var Ce=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(Ce||{});var u=class extends vt{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 Be=class{constructor(){this._worker=null}_createWorker(s,p){return o(this,arguments,function*(e,t,i=[],r={},a=[]){return new Promise((l,m)=>{let T=i.join(","),R=new Blob([e,`exports.default(${T});`],{type:"application/javascript; charset=utf-8"}),U=window.URL.createObjectURL(R);this._worker=new Worker(U),this._worker.onmessage=w=>{switch(w.data.type){case Ce.READY:l();break;case Ce.ERROR:m(w.data.error);break;case Ce.FRAME:t(w.data);break;case Ce.DEBUG:c.debug(w.data.message);break;case Ce.LOG_ERROR:u.log(S.ERROR,w.data.message);break}},this._sendToWorker(Ce.INIT,r,a)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var nt=class extends Be{init(e){return o(this,null,function*(){c.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var b=Object.defineProperty;var E=a=>b(a,"__esModule",{value:!0});var M=(a,p)=>{E(a);for(var e in p)b(a,e,{get:p[e],enumerable:!0})};var V={};M(V,{default:()=>D});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var D=(a,p)=>{let e=null,n=null,g=!0;function y(){return a({locateFile:p}).then(r=>n=r)}function s(r,m,l,R,x){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(x),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let d=e.getImageBuffer();if(!d){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let c=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(d.byteLength);if(i.set(d),R){let o=new ImageData(i,c,f);createImageBitmap(o,0,0,c,f).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:i.buffer,width:c,height:f},[i.buffer])}y().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return V;})();\n',t=>{if(t.error)c.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i)}else e(t.data)},[Cr,Cr.getUrl])})}decodeFrame(e,t,i,r){let a="ImageBitmap"in window;this._sendToWorker(Ce.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:a,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 Be{init(e){return o(this,null,function*(){c.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var l=Object.defineProperty;var u=e=>l(e,"__esModule",{value:!0});var m=(e,a)=>{u(e);for(var d in a)l(e,d,{get:a[d],enumerable:!0})};var g={};m(g,{default:()=>E});var s=(d=>(d.VP9="vp09.00.50.08",d.VP8="vp8",d))(s||{}),t=(o=>(o.INIT="init",o.READY="ready",o.FRAME="frame",o.ERROR="error",o.DEBUG="debug",o.LOG_ERROR="log_error",o))(t||{});var E=()=>{let e=null,a=!0;function d(){self.postMessage({type:t.READY})}function i(r,p,o,n=!1){if(!e||a!==o){if(!n){self.postMessage({type:t.DEBUG,message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}a=o,e?self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec changed to ${o?"VP9":"VP8"}`}):(self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec ${o?"VP9":"VP8"}`}),e=new VideoDecoder({output:c=>{self.postMessage({type:t.FRAME,data:c},[c]),c.close()},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:t.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:o?s.VP9:s.VP8})}let f=new EncodedVideoChunk({type:n?"key":"delta",timestamp:r,data:p});e.decode(f)}self.onmessage=r=>{switch(r.data.type){case t.INIT:d();break;case t.FRAME:i(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(Ce.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}};import{BitStream as Sa}from"bit-buffer";var va=65536,ze=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(c.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%va!==e.sequence){c.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:a}=ze.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:a})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((a,s)=>a+s.data.byteLength,0),i=new Uint8Array(t),r=0;for(let a of e)i.set(new Uint8Array(a.data),r),r+=a.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new Sa(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 _i="_okcls_",st=(()=>{try{let n=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(n,n),t=e.getItem(n)===n,e.removeItem(n),t?e:null}catch(n){return null}})();function Ea(n){let e=st?st.getItem(_i+n):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function Ia(n,e){try{st&&st.setItem(_i+n,JSON.stringify(e))}catch(t){}}function Ta(n){st&&st.removeItem(_i+n)}var gi;(i=>{function n(r){return Ea(r)||null}i.get=n;function e(r,a){Ia(r,a)}i.set=e;function t(r){Ta(r)}i.remove=t})(gi||(gi={}));var $e=gi;function Pr(n,e){if(n.isAudioEnabled!==e.isAudioEnabled||n.isVideoEnabled!==e.isVideoEnabled||n.isScreenSharingEnabled!==e.isScreenSharingEnabled||n.videoStreams.length!==e.videoStreams.length)return!1;for(let t of n.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function ve(n){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},n||{})}var yr=n=>n.stop(),Rr=n=>n.getTracks().forEach(yr),fi=n=>n.getVideoTracks().forEach(yr),br=n=>n.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 De=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(De||{}),le=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(le||{}),Si=class extends Y{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=ve();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return o(this,arguments,function*(e=[he.AUDIO],t=!0){if(this._stream)return;let i=e.includes(he.VIDEO),r=e.includes(he.AUDIO);if(!C.isBrowserSupported())throw new O(ae.UNSUPPORTED);try{this._stream=yield C.getUserMedia(i,r,t),this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(a=>a.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=r&&this._stream.getAudioTracks().filter(a=>a.enabled).length>0||!1}catch(a){throw new O(a)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t,i,r){let a=this.getStream(),s=this._getSendAudioTrack(),p=this.getSendVideoTrack(i);if(!a||!s&&!p&&!t)throw new Error("No local stream found");if(s&&!t){if(r){let{codecs:l}=RTCRtpSender.getCapabilities("audio"),m="audio/red",T=48e3,R=l.findIndex(U=>U.mimeType===m&&U.clockRate===T);if(R>=0){let U=[];U.push(l[R]);for(let w=0;w<l.length;w++)w!==R&&U.push(l[w]);e.getTransceivers().forEach(w=>w.setCodecPreferences(U))}}e.addTrack(s,a)}p&&!t&&e.addTrack(p,a)}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);this._onDeviceChange=()=>o(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],a=r&&r.enabled&&r.getSettings(),s=a&&a.deviceId,p=this._stream.getVideoTracks()[0],l=p&&p.enabled&&p.getSettings(),m=l&&l.deviceId;if(!s&&!m)return;let T=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!T.find(R=>R.deviceId===s)),!t&&m&&(t=!T.find(R=>R.deviceId===m)),i()}),navigator.mediaDevices.addEventListener("devicechange",this._onDeviceChange)}_destroyDeviceChangeListener(){this._onDeviceChange&&navigator.mediaDevices.removeEventListener("devicechange",this._onDeviceChange)}_changeVideoInput(e=null){return o(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield C.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{d.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),a=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),u.log(S.DEVICE_CHANGED,t),c.log("Video stream changed"),yield this._replaceLocalTrack(a),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(S.ERROR,"change_video"),c.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=br(e)),t=this._trackVideoStreamBackup.clone(),fi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),fi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return o(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return o(this,null,function*(){try{if(e=e||(yield C.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),u.log(S.DEVICE_CHANGED,"audio"),c.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(S.ERROR,"change_audio"),c.error("Microphone change failed",t),t}})}_changeScreen(e){return o(this,null,function*(){try{if(e=e||(yield C.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=d.consumerScreenTrack?t:yield this._videoEffect(null,t);u.log(S.DEVICE_CHANGED,"screen"),c.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,d.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=d.consumerScreenDataChannel?C.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(S.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,a;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(a=this._stream)==null||a.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(S.DEVICE_CHANGED,`effect_${e}`),d.videoEffects.setEffect(e,t)}catch(i){return c.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){this._destroyDeviceChangeListener(),d.videoEffects&&(this._effect=null,d.videoEffects.destroy()),this._stream&&(Rr(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return o(this,null,function*(){return e?this._changeScreen():d.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return o(this,null,function*(){if(!this._stream)return;d.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield C.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=C.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return o(this,null,function*(){if(!this._stream)return;let t;e?t=(yield C.getUserAudio()).getAudioTracks()[0]:t=C.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return o(this,null,function*(){if(!d.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return o(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks()[0];if(!e)throw new Error("Local audio track not found");if(!!e.enabled)return e.applyConstraints({noiseSuppression:d.noiseSuppression})})}videoEffect(e){return o(this,null,function*(){if(!d.videoEffects)throw new Error("Video Effects library is not set");if(!d.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var ot=":",Ut="d",vi;(ji=>{function n(I,h,y,H,x=!1,$=!1){let z=/[\r\n]+/,A=`\r
8
+ `;if(!h&&!y&&!H&&!$)return x?Q(I.split(z)).join(A):I;function Q(pe){let Ue=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],ge="a=rtcp-fb:111",se=pe.findIndex(Z=>Z.startsWith(ge));return~se&&(pe[se]=pe[se]+A+Ue.join(A)),pe}function D(pe,Ue,ge){let se=pe.split(" "),Z=se.slice(0,3),me;for(me=3;me<se.length;me++)ge.includes(se[me])&&Z.push(se[me]);for(me=3;me<se.length;me++)!ge.includes(se[me])&&!Ue.includes(se[me])&&Z.push(se[me]);return Z.join(" ")}function X(pe,Ue){let ge=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),se,Z=[];for(se=0;se<pe.length;++se){let me=pe[se].match(ge);me&&me.length===3&&me[2]===Ue&&Z.push(me[1])}return Z}function Ie(pe,Ue,ge,se){let Z,me="m="+Ue;for(Z=0;Z<pe.length;++Z)if(pe[Z].startsWith(me)){pe[Z]=D(pe[Z],ge,se);break}}let Se=[],re=I.split(z);(y||h)&&(Se=X(re,"H264"));let k=[];H&&(k=X(re,"VP9"));let xe=[];if($&&(xe=X(re,"red")),y){let pe=Se.slice(0),Ue=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),ge;for(ge=0;ge<re.length;++ge){let Z=re[ge].match(Ue);Z&&Z.length===3&&pe.includes(Z[2])&&pe.push(Z[1])}let se=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(ge=re.length;ge--;){let Z=re[ge].match(se);Z&&Z.length===3&&pe.includes(Z[2])&&re.splice(ge,1)}Ie(re,"video",pe,[])}else h&&Ie(re,"video",[],Se);return H&&Ie(re,"video",[],k),$&&xe.length>0&&Ie(re,"audio",[],xe),x&&Q(re),re.join(A)}ji.patchSDP=n;function e(I){return I?`${I.type||"WEB_SOCKET"}_${I.id}`:"_"}ji.getPeerIdString=e;function t(I,h){return I&&I.id===h.id&&(I.type||"WEB_SOCKET")===(h.type||"WEB_SOCKET")}ji.comparePeerId=t;function i(I){return o(this,null,function*(){return!I||!I.getStats?Promise.resolve(null):I.getStats(null).then(h=>{let y=null,H=null;if(h.forEach(x=>{x.type==="transport"&&x.selectedCandidatePairId?H=h.get(x.selectedCandidatePairId):x.type==="candidate-pair"&&x.state==="succeeded"&&!H&&(!x.hasOwnProperty("selected")||x.selected)&&(H=x)}),H&&H.localCandidateId){let x=h.get(H.localCandidateId);x&&(y={type:x.candidateType,ip:x.ip||x.ipAddress,port:x.port||x.portNumber})}return y}).catch(()=>null)})}ji.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,a=/^([gu])([0-9]+)$/;function s(I,h){let y=String(I);return a.test(y)?(c.warn(`Already composite id [${I}] type supplied [${h}]`),y):h===ee.GROUP?"g"+y:h===ee.USER?"u"+y:(c.warn(`Unknown type [${h}] for id [${I}]`),y.match(r)?"u"+y:y)}ji.composeUserId=s;function p(I,h,y){let H=s(I,h);return l(H,y)}ji.composeParticipantId=p;function l(I,h){return h?I+ot+Ut+h:I}ji.compose=l;function m(I){return p(I.id,I.idType||ee.USER,I.deviceIdx||0)}ji.composeId=m;function T(I){return I.participant?m(I.participant):p(I.participantId,I.participantType||ee.USER,I.deviceIdx||0)}ji.composeMessageId=T;function R(I){let h=String(I),y=h.match(a);return y?{id:Number(y[2]),type:y[1]==="g"?ee.GROUP:ee.USER}:(c.warn(`Unsupported compositeId [${I}]`),{id:Number(h),type:ee.USER})}ji.decomposeId=R;function U(I){let h=I.split(ot+Ut);return{compositeUserId:h[0],deviceIdx:h.length>1?parseInt(h[1],10):0}}ji.decomposeParticipantId=U;function w(){var z,A;let I=(A=(z=window.crypto)==null?void 0:z.randomUUID)==null?void 0:A.call(z);if(I)return I;let h="0123456789abcdefghijklmnopqrstuvwxyz".split(""),y=new Array(36),H=0,x,$;for($=0;$<36;$++)$===8||$===13||$===18||$===23?y[$]="-":$===14?y[$]="4":(H<=2&&(H=33554432+Math.random()*16777216|0),x=H&15,H=H>>4,y[$]=h[$===19?x&3|8:x]);return y.join("")}ji.uuid=w;function j(I,h){let y;function H(){let x=this,$=arguments;y&&window.clearTimeout(y),y=window.setTimeout(()=>{I.apply(x,$)},h)}return H}ji.throttle=j;function ie(I){if(!window.BigInt)return null;let h="",y=I.split(`
9
+ `);for(let $ of y)if($.startsWith("a=fingerprint")){let z=$.split(" ");if(z.length===2){h=z[1];break}}if(!h)return BigInt(-1);let H=h.split(":"),x=BigInt(0);for(let $=Math.min(7,H.length-1);$>=0;$--){let z=BigInt(parseInt(H[$],16));x<<=BigInt(8),x|=z}return BigInt.asIntN(64,x)}ji.sdpFingerprint=ie;function Pe(I){return o(this,null,function*(){return new Promise(h=>window.setTimeout(h,I))})}ji.delay=Pe;function ne(I,h,y){let H=[];return I.getSenders().forEach(x=>Fe(h,x,x.track,y,H)),H}ji.applySettings=ne;function Fe(I,h,y,H,x){var $;if(I&&y&&y.kind===le.video){let z=y.getSettings();if(z){let A=I.maxBitrateK?I.maxBitrateK*1024:null,Q=z.width,D=z.height,X=Q&&D&&I.maxDimension?Math.max(1,Math.max(Q,D)/I.maxDimension):null,Ie=I.maxFramerate?I.maxFramerate:null,Se=I.degradationPreference?I.degradationPreference:"balanced",re=H[y.id];if(re&&re.bitrate===A&&re.scaleResolutionDownBy===X&&re.maxFramerate===Ie&&re.degradationPreference===Se){x[y.id]=re;return}x[y.id]={bitrate:A,scaleResolutionDownBy:X,maxFramerate:Ie,degradationPreference:Se};let k=h.getParameters();k.encodings||(k.encodings=[{}]),k.encodings.forEach(xe=>{A?xe.maxBitrate=A:delete xe.maxBitrate,X?xe.scaleResolutionDownBy=X:delete xe.scaleResolutionDownBy,Ie?xe.maxFramerate=Ie:delete xe.maxFramerate}),k.degradationPreference=Se,($=h.setParameters)==null||$.call(h,k)}}}ji.applyVideoTrackSettings=Fe;function ce(I,h){Array.isArray(h)||(h=[h]);for(let y of h)if(I.includes(y))return!0;return!1}ji.includesOneOf=ce;function be(I){var h;return Object.entries(((h=I.participantState)==null?void 0:h.state)||{}).reduce((y,[H,x])=>(I.participantState&&(y[H]={ts:I.participantState.stateUpdateTs[H],state:x}),y),{})}ji.mapParticipantState=be;function Me(I){let h=I.map(y=>({uid:y.externalId,mediaSettings:y.mediaSettings,status:y.status,muteStates:y.muteStates,unmuteOptions:y.unmuteOptions,participantState:y.participantState,markers:y.markers,movieShareInfos:y.movieShareInfos}));return d.filterObservers?h.filter(y=>!y.uid.observer):h}ji.mapSharedParticipants=Me;function K(I,h){let y=Object.keys(I),H=Object.keys(h);if(y.length!==H.length)return!1;for(let x of y)if(!H.hasOwnProperty(x)||I[x].state!==h[x].state||I[x].ts!==h[x].ts)return!1;return!0}ji.isEqualParticipantState=K;function Hi(I,h){let y=Object.keys(I),H=Object.keys(h);if(y.length!==H.length)return!1;for(let x of y)if(!h.hasOwnProperty(x)||I[x]!==h[x])return!1;return!0}ji.isObjectsEquals=Hi;function Gi(I,h){if(I.length!==h.length)return!1;for(let y of I)if(h.indexOf(y)<0)return!1;return!0}ji.isArraysEquals=Gi;function Wi(I){return!Object.keys(I).length}ji.isEmptyObject=Wi})(vi||(vi={}));var v=vi;var Qe=null,Ei=null,Bt=[],Vt=[],Ii=[],Ct=null,Pt=null,Ti=null,Ci=!1,Pi=!1,Ft,ct,Ht,Mr=!1,Dr=!1,yi=null,Ri="",Gt=[],bi=null,Ar=navigator.appVersion,Ca=navigator.appName,Ae=navigator.userAgent,kr=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(kr||{}),yt=class{constructor(e,t=!1,i=d.videoMaxWidth,r=d.videoMaxHeight){let a=!1;if(e){a={noiseSuppression:d.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let p;Pt&&(p=Pt.deviceId),typeof e=="string"&&(p=e),p&&(a.deviceId={ideal:p})}let s=!1;if(t){s={width:{min:d.videoMinWidth,max:i,ideal:i},height:{min:d.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:d.videoAspectRatio},frameRate:{ideal:d.videoFrameRate}};let p;Ct&&(p=Ct.deviceId),typeof t=="string"&&(p=t),p&&(s.deviceId={ideal:p}),d.videoFacingMode&&(s.facingMode={ideal:d.videoFacingMode})}this.audio=a,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let 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}},Or=class extends yt{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 Pa(){return o(this,null,function*(){Qe=null,yield Wt()})}function ya(){Qe=null,Wt().then(()=>g.onDeviceChange())}function Wt(){return o(this,null,function*(){return Qe||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Ei&&navigator.mediaDevices.addEventListener&&(Ei=v.throttle(ya,1e3),navigator.mediaDevices.addEventListener("devicechange",Ei)),Qe=navigator.mediaDevices.enumerateDevices().then(n=>{Bt=n.filter(r=>r.kind==="videoinput"?(r.label&&(Ci=!0),!0):!1),Vt=n.filter(r=>r.kind==="audioinput"?(r.label?Pi=!0:Xe.isMobile()&&Xe.browserName()==="Firefox"&&(Pi=Ci),!0):!1),Ii=n.filter(r=>r.kind==="audiooutput");let e=$e.get("videoinput"),t=$e.get("audioinput"),i=$e.get("audiooutput");return Ct=Bt.find(r=>r.deviceId===e)||null,Pt=Vt.find(r=>r.deviceId===t)||null,Ti=Ii.find(r=>r.deviceId===i)||null,Qe=Promise.resolve(n),n}).catch(()=>(Qe=null,[]))))})}function Ra(){return o(this,null,function*(){return Xe.isBrowserSupported()?new Promise(n=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(Mr=!0),/^a=mid:0$/m.test(t.sdp)&&(Dr=!0),n()}).catch(n)}):Promise.resolve()})}function jt(n,e){return o(this,null,function*(){c.debug("Try to get media",n.getNative());let t=Xe.hasPermissions(n.isVideo());!t&&!e&&g.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(n.getNative());return t||(yield Pa()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=n.isVideo()?ae.CAMERA_PERMISSION:ae.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=n.isVideo()?ae.CAMERA_ACCESS:ae.MIC_ACCESS;break}if(n.canSimplify())return jt(n.simplify(),e);let r=e||ae.UNKNOWN;throw g.onPermissionsError(r),r}})}function ba(n){return o(this,null,function*(){c.debug("Try to get screen",n.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(n.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 ae.SCREEN_PERMISSION;default:throw ae.SCREEN_ACCESS}}})}function Kt(){return Gt.length||(Gt=(()=>{let n,e=!1,t=0,i="0",r=Ae.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return n=/\brv[ :]+(\d+)/g.exec(Ae),["IE",n&&n[1]||"Unknown",e,t,i];if(r[1]==="Safari"){if(n=Ae.match(/\bEdge\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t,i];if(n=Ae.match(/\bCriOS\/(\d+)/),n)return["Chrome",n[1],!0,Number(n[1]),i];if(n=Ae.match(/\bFxiOS\/(\d+)/),n)return["Firefox",n[1],!1,t,i];if(n=Ae.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1],!1,t,i];if(n=Ae.match(/\bOPT\/(\d+)/),n)return["Opera",n[1],!1,t,i]}if(r[1]==="Chrome"){if(e=!0,t=Number(r[2]),n=Ae.match(/\bOPR\/(\d+)/),n)return["Opera",n[1]||"Unknown",e,t,i];if(n=Ae.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1]||"Unknown",e,t,i];if(n=Ae.match(/\bSferum\/((\d+)(?:\.\d+)*)/),n)return["Sferum",n[1]||"Unknown",e,t,i];if(n=Ae.match(/\bEdge?\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t,i];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t,i]}return n=Ae.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),n&&n[2]!==void 0&&(i=n[2]),[r[2]?r[1]:Ca,n&&n[1]||r[2]||Ar,e,t,i]})()),Gt}var Xe;(z=>{function n(){return o(this,null,function*(){return yield Ra(),Wt()})}z.init=n;function e(){return Bt}z.getCameras=e;function t(){return Vt}z.getMicrophones=t;function i(){return Ii}z.getOutput=i;function r(){return Bt.length>0}z.hasCamera=r;function a(){return Vt.length>0}z.hasMicrophone=a;function s(){return Ct}z.getSavedCamera=s;function p(){return Pt}z.getSavedMicrophone=p;function l(){return Ti}z.getSavedOutput=l;function m(){return Ci}z.hasCameraPermission=m;function T(){return Pi}z.hasMicrophonePermission=T;function R(A=!1){return T()?r()&&A?m():!0:!1}z.hasPermissions=R;function U(A=!1,Q=!0,D=!0){return o(this,null,function*(){let X=a()&&Q,Ie=r()&&A,Se;if(!X&&!Ie)Se=new MediaStream;else try{Se=yield jt(new yt(X,Ie))}catch(re){Se=new MediaStream}return!Se.getVideoTracks().length&&D&&Se.addTrack(Fe()),!Se.getAudioTracks().length&&D&&Se.addTrack(ne()),Se})}z.getUserMedia=U;function w(){return o(this,null,function*(){return ba(new Or(window.screen.width,window.screen.height))})}z.getScreenMedia=w;function j(A,Q=!1){return o(this,null,function*(){let D=Q?d.videoEffectMaxWidth:d.videoMaxWidth,X=Q?d.videoEffectMaxHeight:d.videoMaxHeight;return jt(new yt(!1,A||!0,D,X))})}z.getUserVideo=j;function ie(A){return o(this,null,function*(){return jt(new yt(A||!0,!1))})}z.getUserAudio=ie;function Pe(A,Q){return o(this,null,function*(){let X=(yield Wt()).find(Ie=>Ie.kind===A&&Ie.deviceId===Q);return X?(A==="videoinput"?Ct=X:A==="audioinput"?Pt=X:A==="audiooutput"&&(Ti=X),$e.set(A,Q),X):null})}z.saveDeviceId=Pe;function ne(){if(!Ht||Ht.readyState==="ended"){let A=x(),Q=A.createMediaStreamDestination(),D=A.createGain();D.gain.value=1e-5,D.connect(Q),D.connect(A.destination);let X=A.createOscillator();X.type="sine",X.frequency.value=0,X.connect(D),X.start(),Ht=Q.stream.getAudioTracks()[0]}return Object.assign(Ht.clone(),{enabled:!1})}z.getSilentMediaTrack=ne;function Fe(A=d.videoMinWidth,Q=d.videoMinHeight){return ct||(ct=document.createElement("canvas"),ct.getContext("2d")),ct.width=A,ct.height=Q,(!Ft||Ft.readyState==="ended")&&(Ft=ct.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(Ft.clone(),{enabled:!1})}z.getBlackMediaTrack=Fe;function ce(){if(h()==="Edge"&&Number(y())<70)return!1;try{let A=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&A.RTCPeerConnection&&A.RTCIceCandidate&&A.RTCSessionDescription&&A.HTMLCanvasElement&&A.HTMLCanvasElement.prototype.captureStream&&A.RTCRtpSender&&A.RTCRtpSender.prototype.replaceTrack&&A.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(A){return!1}}z.isBrowserSupported=ce;function be(){return!!navigator.mediaDevices.getDisplayMedia}z.isScreenCapturingSupported=be;function Me(){return Mr}z.canVP8=Me;function K(){return Dr}z.isUnifiedPlan=K;function Hi(){let A=z.browserName()==="Safari"&&z.browserVersion()==="15"&&z.browserSubVersion()==="1",Q=z.browserName()==="Opera"&&z.os()==="Windows";return A||Q}z.isBrokenH264=Hi;function Gi(){return!(z.baseChromeVersion()&&z.isMobile())}z.canPreferH264=Gi;function Wi(){var A;return((A=window.RTCRtpTransceiver)==null?void 0:A.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}z.canPreferRed=Wi;function ji(){return Ri||(Ri=(()=>{let A={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 Q in A)if(A.hasOwnProperty(Q)&&A[Q].test(Ae))return Q;return"Unknown"})()),Ri}z.os=ji;function I(){return yi===null&&(yi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Ar)),yi}z.isMobile=I;function h(){return Kt()[0]}z.browserName=h;function y(){return Kt()[1]}z.browserVersion=y;function H(){return Kt()[3]}z.baseChromeVersion=H;function x(){return bi||(bi=new(window.AudioContext||window.webkitAudioContext)),bi}z.getAudioContext=x;function $(){return Kt()[4]}z.browserSubVersion=$})(Xe||(Xe={}));var C=Xe;var dt=class{constructor(e){this._onStream=e}drawFrame(e){return o(this,null,function*(){throw new Error("Method `drawFrame` is not supported by this implementation")})}drawImage(e){throw new Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Rt=class extends dt{constructor(e){super(e);this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;c.debug("CanvasRenderer started"),this._useImageBitmap="ImageBitmap"in window}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}drawFrame(e){return o(this,null,function*(){let t="createImageBitmap"in e?yield e.createImageBitmap():yield createImageBitmap(e);this.drawImage(t),t.close()})}drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}destroy(){this._removeStream(),c.debug("CanvasRenderer destroyed")}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(C.browserName()==="Safari"&&Number(C.browserVersion())===15)}};var pt=class extends dt{constructor(e){super(e);c.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:le.video}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}drawFrame(e){return o(this,null,function*(){yield this._writer.write(e)})}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),c.debug("TrackGeneratorRenderer destroyed")}static isBrowserSupported(){return"VideoFrame"in window&&"MediaStreamTrackGenerator"in window&&We.isBrowserSupported()}};var bt=class extends ze{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];c.debug(`StreamBuilder started for participant [${e}]`),pt.isBrowserSupported()?this._renderer=new pt(t):this._renderer=new Rt(t),We.isBrowserSupported()?this._decoder=new We:this._decoder=new nt;let i=r=>o(this,null,function*(){"VideoFrame"in window&&r instanceof VideoFrame?yield this._renderer.drawFrame(r):this._renderer.drawImage(r)});this._decoder.init(i).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._renderer.destroy(),c.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return Rt.isBrowserSupported()||pt.isBrowserSupported()}};var $t=1,Ma=1,wr=0,xr=11,Lr=1,Nr=2,Ur=4,Br=8;function Vr(n,e,t,i,r,a,s){let p=0;e&&(p|=Lr),t&&(p|=Nr),i&&(p|=Ur),s||(p|=Br);let l=new ArrayBuffer(xr),m=new DataView(l);if(m.setUint8(0,$t),m.setUint16(1,r),m.setUint32(3,n),m.setUint8(7,a?1:0),m.setUint16(8,wr),m.setUint8(10,p),!s)return l;let T=new Uint8Array(l.byteLength+s.byteLength);return T.set(new Uint8Array(l),0),T.set(new Uint8Array(s),l.byteLength),T.buffer}function Fr(n){let e=new DataView(n),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),a=e.getUint8(7)===1,s=e.getUint16(8),p=e.getUint8(10),l=!!(p&Lr),m=!!(p&Nr),T=!!(p&Ur),R=!!(p&Br);if(t!==$t)throw new Error(`Unexpected protocol version. Got ${t}, expected ${$t}`);return{timestamp:r,start:l,end:m,keyframe:T,sequence:i,isVP9:a,ssrc:s,eos:R,data:n.slice(xr)}}function Hr(n){if(!n||!n.byteLength||n.byteLength!==4)return!1;let e=new DataView(n);return!(e.getUint8(0)!==$t||e.getUint8(1)!==Ma||e.getUint16(2)!==wr)}import*as E from"simple-ebml-builder";var Da=$i(2,15)-1,Mi=1,Aa=5,ka=5;var qt=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=qt._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return E.build(e[0])}else return new Uint8Array;let t=e.reduce((a,s)=>a+s.countSize(),0),i=new Uint8Array(t),r=0;for(let a of e){let s=E.build(a);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 a,s,p;((a=this._mediaSource)==null?void 0:a.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let e=(p=this._sourceBuffer)==null?void 0:p.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-Aa);r-i>ka&&(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}},Ne=class extends ze{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;c.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return E.element(E.ID.EBML,[E.element(E.ID.EBMLVersion,E.number(1)),E.element(E.ID.EBMLReadVersion,E.number(1)),E.element(E.ID.EBMLMaxIDLength,E.number(4)),E.element(E.ID.EBMLMaxSizeLength,E.number(8)),E.element(E.ID.DocType,E.string("webm")),E.element(E.ID.DocTypeVersion,E.number(2)),E.element(E.ID.DocTypeReadVersion,E.number(2))])}static _genSegmentHeader(e,t,i){let r=E.element(E.ID.Info,[E.element(E.ID.TimecodeScale,E.number(1e6)),E.element(E.ID.MuxingApp,E.string("vk-webm-builder")),E.element(E.ID.WritingApp,E.string("vk-webm-builder"))]),a=[E.element(E.ID.PixelWidth,E.number(e)),E.element(E.ID.PixelHeight,E.number(t))],s=E.element(E.ID.Tracks,E.element(E.ID.TrackEntry,[E.element(E.ID.TrackNumber,E.number(Mi)),E.element(E.ID.TrackUID,E.number(Mi)),E.element(E.ID.TrackType,E.number(1)),E.element(E.ID.FlagLacing,E.number(0)),E.element(E.ID.DefaultDuration,E.number(1e9)),E.element(E.ID.CodecID,E.string(`V_${i.toUpperCase()}`)),E.element(E.ID.Video,a)]));return E.unknownSizeElement(E.ID.Segment,[r,s])}static _genClusterHeader(e){return E.unknownSizeElement(E.ID.Cluster,[E.element(E.ID.Timecode,E.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new qt(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){c.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>c.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,c.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),c.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=Ne._genWebmHeader();this._mediaBuffer.append(s);let p=Ne._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(p)}let r=Math.round(i-this._clusterStartTime);if(r>Da&&(this._clusterStartTime=i,r=0),r===0){c.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=Ne._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let a=E.element(E.ID.SimpleBlock,[E.vintEncodedNumber(Mi),E.bytes(Ne._intToU16BE(r)),E.number((e.keyframe?1:0)<<7),E.bytes(e.frameData)]);this._mediaBuffer.append(a,!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 lt=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=a=>this._onDataChannelMessage(a.data)}_onDataChannelMessage(e){var a,s;let t=Fr(e),i=(s=(a=this._participantIdRegistry)==null?void 0:a.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&&Ne.isBrowserSupported()?r=new Ne(i,p):r=new bt(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()||nt.isBrowserSupported())&&(bt.isBrowserSupported()||Ne.isBrowserSupported())}};import Gr from"@vkontakte/libvpx";var Oa=1e3,Mt=class extends Be{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 a=r.play(),s=()=>i(new Error("Autoplay is disabled"));a?a.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})},[Gr,Gr.getUrl],{isVP9:this.isVP9(),debug:c.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(Ce.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)},Oa),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 ut=class extends Be{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return o(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;c.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var E=Object.defineProperty;var g=i=>E(i,"__esModule",{value:!0});var F=(i,l)=>{g(i);for(var r in l)E(i,r,{get:l[r],enumerable:!0})};var A={};F(A,{default:()=>h});var n=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(n||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,l,r,c,s,f,t,a=null,p=0,u=!1;function V(e){l=e.readable,r=l.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&b(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),l.cancel();return}a=R,b(R,e)}}))}function b(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
11
+ `,r=>{var a;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(a=r.data)==null?void 0:a.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:d.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(Ce.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),c.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var wa=16*1024,xa=11,Wr=wa-xa,La=65536,Di=0,mt=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;c.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,a)=>{if(!this._destroyed){if(!r){c.warn("requestFrame failed, keyFrame: "+this._needKeyframe,a),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{c.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};ut.isBrowserSupported()?this._encoder=new ut(e,i):this._encoder=new Mt(e,i),this._datachannel.onmessage=r=>{Hr(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,a){let s=Vr(e,t,i,r,Di,this._encoder.isVP9(),a);return Di=(Di+1)%La,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 a=e.data.slice(t,t+Wr),s=e.data.byteLength<=t+a.byteLength,p=this._wrapHeader(e.timestamp,!t,s,e.type==="key",a);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+Wr,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 ut.isBrowserSupported()||Mt.isBrowserSupported()}};var te=class{static get sessionKey(){return te._sessionKey}static set sessionKey(e){te._sessionKey=e}static get sessionSecretKey(){return te._sessionSecretKey}static set sessionSecretKey(e){te._sessionSecretKey=e}static get accessToken(){return te._accessToken}static set accessToken(e){te._accessToken=e}static isEmpty(){return!te._sessionKey||!te._sessionSecretKey}};var f=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(f._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(f._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(f._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(te.accessToken=e.apiAuth.accessToken,te.sessionKey=e.apiAuth.sessionKey,te.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(f._params,e)}static get(e){return f._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.5.3-dev.18fb1f2.0"}static get debug(){return undefined}static get protocolVersion(){return f._params.joinFromMultipleDevices?6:5}static get platform(){return f._params.platform}static set platform(e){f._params.platform=e}static get clientType(){return f._params.clientType}static set clientType(e){f._params.clientType=e}static get device(){return f._params.device}static get apiKey(){return f._params.apiKey}static get apiEnv(){return f._params.apiEnv}static get apiEndpoint(){switch(f.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return f._params.apiEnv}}static get authToken(){return f._params.authToken}static set authToken(e){f._params.authToken=e}static get anonymToken(){return f._params.anonymToken}static set anonymToken(e){f._params.anonymToken=e}static get domain(){return f._params.domain}static get iceServers(){return f._params.iceServers}static set iceServers(e){f._params.iceServers=e}static get wssBase(){return f._params.wssBase}static set wssBase(e){f._params.wssBase=e}static get wssToken(){return f._params.wssToken}static set wssToken(e){f._params.wssToken=e}static get signalingReconnectDelay(){return f._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return f._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return f._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return f._params.waitConnectionDelay}static get waitResponseDelay(){return f._params.waitResponseDelay}static get waitMessageDelay(){return f._params.waitMessageDelay}static get waitAnotherTabDelay(){return f._params.waitAnotherTabDelay}static get debugLog(){return f._params.debugLog}static get forceRelayPolicy(){return f._params.forceRelayPolicy}static set forceRelayPolicy(e){f._params.forceRelayPolicy=e}static get videoMinWidth(){return f._params.videoMinWidth}static get videoMaxWidth(){return f._params.videoMaxWidth}static set videoMaxWidth(e){f._params.videoMaxWidth=e}static get videoMinHeight(){return f._params.videoMinHeight}static get videoMaxHeight(){return f._params.videoMaxHeight}static set videoMaxHeight(e){f._params.videoMaxHeight=e}static get videoAspectRatio(){return f._params.videoAspectRatio}static get videoFrameRate(){return f._params.videoFrameRate}static get videoFacingMode(){return f._params.videoFacingMode}static get screenFrameRate(){return f._params.screenFrameRate}static get videoEffects(){return f._params.videoEffects}static set videoEffects(e){f._params.videoEffects=e}static get videoEffectMaxWidth(){return f._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){f._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return f._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){f._params.videoEffectMaxHeight=e}static get voiceParams(){return f._params.voiceParams}static get specListenerParams(){return f._params.specListenerParams}static get iceRestartWaitTime(){return f._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return f._params.transportConnectionWaitTime}static get statisticsInterval(){return f._params.statisticsInterval}static set statisticsInterval(e){f._params.statisticsInterval=e}static get networkStatisticsInterval(){return f._params.networkStatisticsInterval}static get perfStatReportEnabled(){return f._params.perfStatReportEnabled}static get callStatReportEnabled(){return f._params.callStatReportEnabled}static get producerNotificationDataChannel(){return f._params.producerNotificationDataChannel&&lt.isBrowserSupported()}static get producerCommandDataChannel(){return f._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return f._params.consumerScreenDataChannel&&mt.isBrowserSupported()}static get producerScreenDataChannel(){return f._params.producerScreenDataChannel&&f.producerNotificationDataChannel}static get screenShareWebmBuilder(){return f._params.screenShareWebmBuilder}static get noiseSuppression(){return f._params.noiseSuppression}static set noiseSuppression(e){f._params.noiseSuppression=e}static get preferH264(){return f._params.preferH264}static get preferVP9(){return f._params.preferVP9}static get audioNack(){return f._params.audioNack}static get consumerScreenTrack(){return f._params.consumerScreenTrack&&f.consumerScreenDataChannel}static get producerScreenTrack(){return f._params.producerScreenTrack&&f.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=f._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return f._params.movieShare&&f.videoTracksCount>0}static get videoTracksCount(){return f.producerNotificationDataChannel?f._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return f._params.breakVideoPayloadTypes}static get filteredMessages(){return f._params.filteredMessages}static get useParticipantListChunk(){return f._params.useParticipantListChunk&&f._params.videoTracksCount>0}static get participantListChunkInitIndex(){var e;return(e=f._params.participantListChunkInitIndex)!=null?e:0}static get participantListChunkInitCount(){var e;return(e=f._params.participantListChunkInitCount)!=null?e:null}static get serverAudioRed(){return f._params.serverAudioRed&&C.canPreferRed()}static get p2pAudioRed(){return f._params.p2pAudioRed&&C.canPreferRed()}static get batchParticipantsOnStart(){return f._params.batchParticipantsOnStart}static get filterObservers(){return f._params.filterObservers}static get muteMode(){return f._params.muteMode}static get preserveAudioTracks(){return f._params.preserveAudioTracks}},d=f;d._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,useParticipantListChunk:!1,participantListChunkInitIndex:0,participantListChunkInitCount:null,serverAudioRed:!1,p2pAudioRed:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1};var J=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))(J||{});function W(n,...e){let t=d.get(n);t&&setTimeout(t,0,...e)}function oe(n,e,...t){if(d.filterObservers){if(Array.isArray(e)){if(e=e.filter(i=>!i.observer),!e.length)return}else if(e.observer)return}W(n,e,...t)}function Re(n){return Object.assign({},n)}function ht(n){return n.slice()}var Ai;(An=>{function n(_,P){W("onLocalStream",_,Re(P))}An.onLocalStream=n;function e(_,P){W("onScreenStream",_,Re(P))}An.onScreenStream=e;function t(_,P){W("onLocalStreamUpdate",Re(_),P)}An.onLocalStreamUpdate=t;function i(_){W("onLocalStatus",_)}An.onLocalStatus=i;function r(_,P){oe("onRemoteStream",_,P)}An.onRemoteStream=r;function a(_,P,q){oe("onRemoteLive",_,P,q)}An.onRemoteLive=a;function s(_,P,q){oe("onLocalLive",_,P,q)}An.onLocalLive=s;function p(_,P){oe("onRemoteLiveUpdate",_,P)}An.onRemoteLiveUpdate=p;function l(_,P){oe("onLocalLiveUpdate",_,P)}An.onLocalLiveUpdate=l;function m(_,P){oe("onRemoteScreenStream",_,P)}An.onRemoteScreenStream=m;function T(_,P,q,ft){oe("onConversation",_,Re(P),Re(q),ft)}An.onConversation=T;function R(_){_&&W("onConversationParticipantListChunk",_)}An.onConversationParticipantListChunk=R;function U(_,P,q){oe("onRemoteMediaSettings",_,Re(P),q)}An.onRemoteMediaSettings=U;function w(_,P){oe("onLocalMediaSettings",_,Re(P))}An.onLocalMediaSettings=w;function j(_,P){oe("onRemoteSharedMovieInfo",_,Re(P))}An.onRemoteSharedMovieInfo=j;function ie(_,P){oe("onRemoteSharedMovieStoppedInfo",_,Re(P))}An.onRemoteSharedMovieStoppedInfo=ie;function Pe(_,P){oe("onLocalSharedMovieInfo",_,Re(P))}An.onLocalSharedMovieInfo=Pe;function ne(_,P){oe("onLocalSharedMovieStoppedInfo",_,Re(P))}An.onLocalSharedMovieStoppedInfo=ne;function Fe(_,P){oe("onParticipantAdded",_,P)}An.onParticipantAdded=Fe;function ce(_,P){oe("onParticipantJoined",_,P)}An.onParticipantJoined=ce;function be(_,P,q){oe("onRemoteParticipantState",_,Re(P),q)}An.onRemoteParticipantState=be;function Me(_,P,q=null){oe("onRemoteStatus",_,P,q)}An.onRemoteStatus=Me;function K(_,P,q=null){oe("onParticipantStatus",_,P,q)}An.onParticipantStatus=K;function Hi(){W("onPermissionsRequested")}An.onPermissionsRequested=Hi;function Gi(_){W("onPermissionsError",_)}An.onPermissionsError=Gi;function Wi(_,P){oe("onRemoteRemoved",_,P)}An.onRemoteRemoved=Wi;function ji(_,P,q){W("onCallState",_,P,Re(q))}An.onCallState=ji;function I(_,P){W("onDeviceSwitched",_,P)}An.onDeviceSwitched=I;function h(_,P,q,ft=!1,ai=!1,ni=null,sa=null){W("onMuteStates",Re(_),ht(P),ht(q),ft,ai,ni,sa)}An.onMuteStates=h;function y(_,P){oe("onRolesChanged",_,ht(P))}An.onRolesChanged=y;function H(_){W("onLocalRolesChanged",ht(_))}An.onLocalRolesChanged=H;function x(_,P,q){oe("onPinnedParticipant",_,P,q)}An.onPinnedParticipant=x;function $(_){W("onLocalPin",_)}An.onLocalPin=$;function z(_){W("onOptionsChanged",ht(_))}An.onOptionsChanged=z;function A(){W("onCallAccepted")}An.onCallAccepted=A;function Q(){W("onRateNeeded")}An.onRateNeeded=Q;function D(_){oe("onSpeakerChanged",_)}An.onSpeakerChanged=D;function X(_){W("onVolumesDetected",ht(_))}An.onVolumesDetected=X;function Ie(_,P){W("onLocalVolume",_,P)}An.onLocalVolume=Ie;function Se(_,P){W("onJoinStatus",_,P)}An.onJoinStatus=Se;function re(_,P){W("onHangup",_,P)}An.onHangup=re;function k(_){W("onMultipartyChatCreated",Re(_))}An.onMultipartyChatCreated=k;function xe(){W("onDeviceChange")}An.onDeviceChange=xe;function pe(_){W("onFingerprintChange",_)}An.onFingerprintChange=pe;function Ue(){W("onTokenExpired")}An.onTokenExpired=Ue;function ge(_,P,q=!1){W("onChatMessage",_,P,q)}An.onChatMessage=ge;function se(_,P,q=!1){W("onCustomData",_,P,q)}An.onCustomData=se;function Z(_,P,q,ft,ai,ni){W("onRecordStarted",_,P,q,ft,ai,ni)}An.onRecordStarted=Z;function me(){W("onRecordStopped")}An.onRecordStopped=me;function Cn(_){W("onLocalNetworkStatusChanged",_)}An.onLocalNetworkStatusChanged=Cn;function Pn(_){W("onNetworkStatusChanged",_)}An.onNetworkStatusChanged=Pn;function yn(_,...P){W("onDebugMessage",_,...P)}An.onDebugMessage=yn;function Rn(_,P){let q=Object.assign({},_,{memory:P});W("onStatistics",q)}An.onStatistics=Rn;function bn(){W("onAutoplayError")}An.onAutoplayError=bn;function Mn(_,P,q){W("onChatRoomUpdated",_,P,q)}An.onChatRoomUpdated=Mn;function Dn(_){W("onRemoteMixedAudioStream",_)}An.onRemoteMixedAudioStream=Dn})(Ai||(Ai={}));var g=Ai;var jr=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(jr||{}),ki;(ce=>{let n="📞",e=(be,...Me)=>{g.onDebugMessage(be,...Me)},t=!1,i=(be,Me)=>(...K)=>{be(...K),Tr(Me,K)},r=console.debug.bind(console,n),a=console.log.bind(console,n),s=console.warn.bind(console,n),p=console.error.bind(console,n),l=e.bind(null,"DEBUG"),m=e.bind(null,"LOG"),T=e.bind(null,"WARN"),R=e.bind(null,"ERROR");ce.debug=l,ce.log=m,ce.warn=T,ce.error=R;function Pe(){return t}ce.enabled=Pe;function ne(be){t=be,d.debugLog&&mi(),be?(ce.debug=d.debugLog?i(r,"DEBUG"):r,ce.log=d.debugLog?i(a,"LOG"):a,ce.warn=d.debugLog?i(s,"WARN"):s,ce.error=d.debugLog?i(p,"ERROR"):p):(ce.debug=d.debugLog?i(l,"DEBUG"):l,ce.log=d.debugLog?i(m,"LOG"):m,ce.warn=d.debugLog?i(T,"WARN"):T,ce.error=d.debugLog?i(R,"ERROR"):R)}ce.toggle=ne;function Fe(be,...Me){switch(be){case"DEBUG":ce.debug(...Me);break;case"LOG":ce.log(...Me);break;case"WARN":ce.warn(...Me);break;case"ERROR":ce.error(...Me);break}}ce.send=Fe})(ki||(ki={}));var c=ki;var _t=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(_t||{}),Ee;(p=>{function n(l){return l.length?typeof l[0]=="object"?l:l.map(m=>e(m)):[]}p.fromIds=n;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 a(l){try{return JSON.parse(l)}catch(m){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}p.fromString=a;function s(l,m){return l.id===m.id&&l.type===m.type}p.compare=s})(Ee||(Ee={}));var fe;(r=>{function n(a,s="USER",p=0){return{id:a,type:s,deviceIdx:p}}r.fromId=n;function e(a){return`{"id":"${a.id}","type":"${a.type}","deviceIdx":"${a.deviceIdx}"}`}r.toString=e;function t(a,s){return Object.assign({deviceIdx:s},Ee.fromSignaling(a))}r.fromSignaling=t;function i(a){return a&&typeof a=="object"?a.deviceIdx:0}r.getDeviceIdx=i})(fe||(fe={}));var ke=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(ke||{}),Kr="s",$r="m";function qe(n){return n.participantId+(n.mediaType?ot+Kr+n.mediaType:"")+(n.streamName?ot+$r+n.streamName:"")}function Dt(n){let e=n.split(ot),t=e.shift();if(!t)throw new Error("Illegal stream description: "+n);let i=null,r,a=0;for(let p of e)switch(p.charAt(0)){case Kr:i=Na(p.slice(1));break;case $r:r=p.slice(1);break;case Ut:a=Number.parseInt(p.slice(1),10);break;default:throw new Error("Unexpected parameter type "+p.charAt(0)+" in stream description "+n)}return{participantId:v.compose(t,a),mediaType:i,streamName:r}}function Na(n){for(let e of Object.keys(ke))if(e===n)return ke[e];return null}function Oi(n,e){return n===null||e===null?n===null&&e===null:!(n.maxDimension!==e.maxDimension||n.maxBitrateK!==e.maxBitrateK||n.maxFramerate!==e.maxFramerate||n.degradationPreference!==e.degradationPreference)}function Jt(n,e){return!(!Oi(n.camera,e.camera)||!Oi(n.screenSharing,e.screenSharing))}function wi(n,e){return{camera:Object.assign({},n.camera,e.camera),screenSharing:Object.assign({},n.screenSharing,e.screenSharing)}}function qr(n){try{return btoa(JSON.stringify(n))}catch(e){c.warn("WaitingParticipant: failed convert to string",n,e)}return null}function Jr(n){try{return JSON.parse(atob(n))}catch(e){c.warn("WaitingParticipant: failed convert from string",n,e)}return null}var At=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,u.log(S.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,u.log(S.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(c.log("Failed to fix RV"),u.log(S.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),u.log(S.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===le.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Yt=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(d.muteMode||!((s=this._output)==null?void 0:s.audioTrack))return;let e=C.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{c.warn("Error on play audio"),g.onAutoplayError()},r=p=>{t.srcObject=new MediaStream([p]),t.load();let l=t.play();l?l.catch(i):i()},a=()=>{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=a,t.onstalled=a,t.onerror=a,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return o(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=C.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw u.log(S.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var Ua=90,Ba=3,zt=class extends Y{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}),g.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>Ua?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Ba)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var Va=44100,kt=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=C.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=Va/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((a,s)=>a+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 Qt=class extends Y{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&g.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,d.voiceParams.interval)};this._interval=window.setTimeout(t,d.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,De.SOURCE_CHANGED,r=>{r.kind===le.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new kt("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 Yr="videochat-epi",Fa=5e3,Ha=3e4,Ze=class extends Y{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,B.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Yr)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return o(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&d.perfStatReportEnabled&&this._previousTimestamp+Fa<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),d.callStatReportEnabled&&this._previousCallStatReportTimestamp+Ha<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return o(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(Yr,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,a)=>(a.kind==="video"?(a.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+a.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+a.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=a.framesDropped,r.nack_sent+=a.nackCount,r.pli_sent+=a.pliCount,r.fir_sent+=a.firCount):(a.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+a.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+a.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=a.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=a.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=a.removedSamplesForAcceleration,r.concealed_audio_samples+=a.concealedSamples,r.silent_concealed_audio_samples+=a.silentConcealedSamples,r.audio_concealment_events+=a.concealmentEvents),r),t),e.outbound.rtps.reduce((r,a)=>(a.kind==="video"&&(r.nack_received+=a.nackCount,r.pli_received+=a.pliCount,r.fir_received+=a.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,a=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,p=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,l=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,m=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=a/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=p/r*1e3,i.concealed_silent_audio_samples=l/r*1e3,i.concealment_audio_avg_size=p/m,i.total_audio_energy=t.total_audio_energy}u.logCustom("callStat",i),c.log("Sent call stats",i),this._previousCallStatReport=t}};var Ga=1e3;function ue(n,e,t=0){return e in n&&n[e]?n[e]:t}function zr(...n){return e=>{for(let t of n)if(t(e))return!0;return!1}}function Je(n,e){return t=>t[n]===e}function Wa(n){return(e,t)=>e[n]-t[n]}function Xt(n,e){return e.reduce((t,i)=>(t[i[n]]=i,t),{})}function ja(n){let e={},t=[];for(let i of n)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Ka(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function xi(n){return Object.keys(n).filter(e=>n[e]!==void 0).map(e=>[e,n[e]]).reduce((e,t)=>(e[t[0]]=Ka(t[1])?xi(t[1]):t[1],e),{})}function $a(n){let e=[];for(let t of n)t.forEach(i=>e.push(i));return e}function qa(n){return o(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...n.getReceivers().map(t=>t.getStats())),e.push(...n.getSenders().map(t=>t.getStats()))):e.push(n.getStats()),Promise.all(e).then($a).then(ja)})}function Ja(n){let e=n.filter(Je("type","candidate-pair")).sort(Wa("priority")).find(zr(Je("nominated",!0),Je("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=n.find(Je("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=n.find(Je("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),xi(t)}function Ya(n,e){let t=Xt("id",n),i=n.filter(zr(Je("type","inbound-rtp"),Je("type","outbound-rtp")));C.browserName()==="Firefox"&&(i=Object.values(i.reduce((a,s)=>{if(!a[s.ssrc])a[s.ssrc]=s;else{let p=Object.assign({},a[s.ssrc],s),l=a[s.ssrc].isRemote?s:a[s.ssrc];p.id=l.id,p.type=l.type,delete p.isRemote,delete p.remoteId,a[p.ssrc]=p}return a},{})));let r={};if(C.browserName()==="Safari"){let a=n.filter(Je("type","track"));r=Xt("trackIdentifier",a)}return i.map(a=>{let s=Number(a.ssrc),p=a.mediaType||a.kind,l=a.trackId,m=a.type,T=a.codecId;if(C.browserName()==="Safari"){let U=/^.+_([\d]+)$/.exec(a.id);if(U&&(s=parseInt(U[1],10)),p=a.id.indexOf("Audio")>0?"audio":"video",e[s]){let w=p+"-"+e[s];r[w]&&(l=r[w].id)}}if(!m||!s||!p)return null;let R={ssrc:s,type:m,kind:p,bytesReceived:ue(a,"bytesReceived"),bytesSent:ue(a,"bytesSent"),jitter:ue(a,"jitter"),packetsLost:ue(a,"packetsLost"),packetsReceived:ue(a,"packetsReceived"),packetsSent:ue(a,"packetsSent"),fractionLost:ue(a,"fractionLost"),pliCount:ue(a,"pliCount"),firCount:ue(a,"firCount"),nackCount:ue(a,"nackCount"),userId:e[s]};if(p==="video"){let U=ue(a,"framesDecoded"),w=ue(a,"totalInterFrameDelay"),j=ue(a,"totalSquaredInterFrameDelay");R.interframeDelayVariance=(j-w*w/U)/U}if(p==="audio"&&(R.totalSamplesReceived=ue(a,"totalSamplesReceived"),R.concealedSamples=ue(a,"concealedSamples"),R.insertedSamplesForDeceleration=ue(a,"insertedSamplesForDeceleration"),R.removedSamplesForAcceleration=ue(a,"removedSamplesForAcceleration"),R.silentConcealedSamples=ue(a,"silentConcealedSamples"),R.concealmentEvents=ue(a,"concealmentEvents"),R.totalAudioEnergy=ue(a,"totalAudioEnergy")),T&&t[T]){let U=t[T];R.clockRate=U.clockRate,R.mimeType=U.mimeType}if(l&&t[l]){let U=t[l];R.frameHeight=U.frameHeight,R.frameWidth=U.frameWidth,R.framesDecoded=U.framesDecoded,R.framesReceived=U.framesReceived,R.framesDropped=U.framesDropped}return xi(R)}).filter(a=>!!a)}function za(n,e){if(!e||!e.rtps||!n.rtps)return n;let t=Xt("ssrc",n.rtps),i=Xt("ssrc",e.rtps),r=(n.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(a=>{let s=t[a],p=i[a];if(!(!s||!p)){if(s.bytesReceived&&s.bytesReceived>p.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-p.bytesReceived)/r)),s.bytesSent&&s.bytesSent>p.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-p.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>p.packetsReceived||s.packetsLost>p.packetsLost){let l=s.packetsLost-p.packetsLost,m=s.packetsReceived-p.packetsReceived;s.packetLoss=parseFloat((100*l/(l+m)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&p.framesDropped&&s.framesDropped>p.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-p.framesDropped)/r).toFixed(0)))}}),n}function Ot(i,r){return o(this,arguments,function*(n,e,t={}){let a=yield qa(n),s={timestamp:Date.now(),transport:Ja(a),rtps:Ya(a,t)};return e?za(s,e):(yield v.delay(Ga),Ot(n,s,t))})}var Zt=.8,et=class extends Y{constructor(e,t,i,r,a){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=a,this._perfStatReporter=new Ze(this,i,!0),this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,De.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,De.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:d.iceServers,iceTransportPolicy:d.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,d.p2pAudioRed),this._applySettings()}catch(s){u.log(S.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,!1,!0,d.p2pAudioRed),this._applySettings()}catch(i){u.log(S.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={}})}updateSettings(e){Jt(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(B.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(B.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(B.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,a;switch(e.notification){case M.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case M.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 M.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((a=e.data.sdk)==null?void 0:a.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 u.log(S.ERROR,"addIceCandidate-direct"),c.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else c.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return o(this,null,function*(){if(!this._remoteCandidates[e]){c.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){c.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw u.log(S.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(B.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(B.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}),u.log(S.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&&u.log(S.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(_e.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(u.log(S.ICE_RESTART),c.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):c.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,c.error("Ice restart failed",{participantId:this._participantId}),u.log(S.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return o(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return c.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw c.error("Unable to create offer",i,{participantId:this._participantId}),u.log(S.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=et._patchDescription(i),c.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw c.error("Unable to set local description",i,{participantId:this._participantId}),u.log(S.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return o(this,null,function*(){return c.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw c.error("Unable to create answer",e,{participantId:this._participantId}),u.log(S.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=et._patchDescription(e),c.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw c.error("Unable to set local description",e,{participantId:this._participantId}),u.log(S.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!C.baseChromeVersion();return e.sdp=v.patchSDP(e.sdp,d.preferH264&&C.canPreferH264(),C.isBrokenH264(),d.preferVP9,t&&d.audioNack,d.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{c.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),u.log(S.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Ot(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:_e.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:_e.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(B.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=ne=>ne.rtt<=this._networkLimits.goodNet.rtt&&ne.loss<=this._networkLimits.goodNet.loss,i=ne=>ne.rtt>=this._networkLimits.badNet.rtt||ne.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,a=e.inbound.rtps.reduce((ne,Fe)=>Math.max(ne,Fe.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-Zt)+r*Zt,loss:this._lastNetworkStat.loss*(1-Zt)+a*Zt},p=i(s),l=t(s),m=i(this._remoteNetworkStat),T=t(this._remoteNetworkStat),R=i(this._lastNetworkStat),U=t(this._lastNetworkStat),ie=p||m?.2:l&&T?1:0,Pe=Date.now();if((R!==p||U!==l||Pe-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(ne=>{c.warn("Unable to send [bad-net]",ne)})),ie){let ne={};ne[this._participantId]=ne[""]=ie,this._triggerEvent(B.NETWORK_STATUS,ne)}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);if(t===null){c.warn("Fingerprint calculation is unsupported");return}this._fingerprint===null?this._fingerprint=t:(g.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=v.applySettings(this._pc,e,this._prevConsumerSettings))}};var Qr=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Qr||{}),wt=Qr;import{decode as tt}from"messagepack";var Li=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var a,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let p=tt(r);return Object.entries(p).forEach(([j,ie])=>{let Pe=Dt(j);this.streamDescriptionByCompactId.set(ie,Pe)}),null;case 2:case 4:let l=tt(r),m=[];for(let j of l){let ie=this.getStreamDescription(j);ie&&m.push(ie.participantId)}return i===2?{type:"notification",notification:M.AUDIO_ACTIVITY,activeParticipants:m}:{type:"notification",notification:M.STALLED_ACTIVITY,stalledParticipants:m};case 3:let T=tt(r);return{type:"notification",notification:M.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(T))==null?void 0:a.participantId};case 5:let R=tt(r);return{type:"notification",notification:M.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:R[0],maxDimension:R[1]}};case 6:let U=tt(r),w={};for(let[j,ie]of Object.entries(U)){let Pe=(s=this.getStreamDescription(Number(j)))==null?void 0:s.participantId;Pe&&(w[Pe]=ie/100)}return{type:"notification",notification:M.NETWORK_STATUS,statuses:w};case 7:return this._createParticipantSourcesUpdateNotification(r);case 8:{let ie=tt(r).map(Pe=>{var K;let[ne,Fe,ce,be,Me]=Pe;return{participantId:(K=this.getStreamDescription(ne))==null?void 0:K.participantId,gain:Fe,pause:ce,offset:be,duration:Me}});return{type:"notification",notification:M.MOVIE_UPDATE_NOTIFICATION,data:ie}}default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=tt(e),i=[];for(let[r,a]of Object.entries(t)){let s=a[0],p=a[1],l=a[2],m;if(s!==null){if(m=this.getStreamDescription(s),!m){c.error(`could not uncompress participant ID ${s}`);continue}}else m=null;if(l===null){c.error("unexpected null sequenceNumber",r,a);continue}let T=Le.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,R=p?p>>>0:null;i.push({participantStreamDescription:m,streamId:T,rtpTimestamp:R,sequenceNumber:l})}return{type:"notification",notification:M.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Qa=90,Xa=4294967295,Oe=class extends Y{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=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,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,De.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,De.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,De.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Ze(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(e=!1){if(this._isOpen){c.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(c.error("ServerTransport: Closed",e),this._setState(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){Jt(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,Oe._closeDataChannel(this._producerNotification),Oe._closeDataChannel(this._producerCommand),Oe._closeDataChannel(this._producerScreen),Oe._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(B.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let a=r.readyState;a==="open"?(c.debug(`[${t}] data channel opened`),r.onerror=s=>{c.error(`[${t}] data channel error`,s)},i(r)):c.error(`[${t}] data channel open failed, state [${a}]`)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection");let t={};C.baseChromeVersion()&&(t.sdpSemantics=Oe._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=Oe._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,wt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Li,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,wt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,wt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,d.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){c.error("ServerTransport: Unable to add media source tracks",i),u.log(S.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,wt.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(B.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(B.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(B.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(B.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
+ `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Le.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 mt(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 lt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(B.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(B.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!==le.video)return;let r=!this._disabledSenders.has(i),a=e.maxDimension!==0;if(r&&!a){c.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(C.getBlackMediaTrack()).catch(p=>{c.error("Could not disable video upload",p)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&a&&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(B.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 Ot(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(B.REMOTE_DATA_STATS,{inbound:{topology:_e.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:_e.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=Le.AUDIO_MIX,r=this._statBytes[i],a=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(a=!0),r.stalled!==a&&this._triggerEvent(B.REMOTE_ALL_STALL,a)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:a}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Ze.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:d.producerNotificationDataChannel?7:0,producerCommandDataChannelVersion:d.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:d.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:d.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:Oe._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount,red:d.serverAudioRed};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return o(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,c.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(c.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw c.error("[single] unable to set remote offer",i),u.log(S.ERROR,"setRemoteDescription-single"),i}).then(()=>o(this,null,function*(){if(c.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw c.error("[single] unable to create answer",i),u.log(S.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=v.patchSDP(i.sdp,!1,C.isBrokenH264(),!1),i)).then(i=>o(this,null,function*(){if(c.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw c.error("[single] unable to set local answer",i),u.log(S.ERROR,"setLocalDescription-single"),i}).then(i=>o(this,null,function*(){c.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),c.debug("[single] remote offer has been processed")})).catch(i=>{c.warn("[single] unable to send local answer",i),u.log(S.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 M.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case M.REALLOC_CON:this._reconnect();break;case M.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case M.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case M.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case M.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return o(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),d.breakVideoPayloadTypes&&(c.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes",null)),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){c.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=a=>{this._triggerEvent(B.REMOTE_TRACK_REMOVED,i.id,i,a.track)}),i.getTracks().find(a=>a.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(B.REMOTE_TRACK_ADDED,i.id,i,t.track)):c.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){c.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(c.debug("[single] connection state changed",{state:e.connectionState},t),u.log(S.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&&u.log(S.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(d.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{c.error("ServerTransport: Unable to replace track",r),u.log(S.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=C.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(C.browserName(),Number(C.browserVersion()))}getStreamWaitingTimeMs(e,t){if(!this._pc)return u.log(S.PAT_WAITING_TIME_ERROR,"noConnection"),c.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return u.log(S.PAT_WAITING_TIME_ERROR,"noReceiver"),c.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return c.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return u.log(S.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&Xa,l=Math.ceil(p/Qa);return Math.min(100,Math.max(0,l))}};var B=(w=>(w.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",w.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",w.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",w.REMOTE_ALL_STALL="REMOTE_ALL_STALL",w.REMOTE_DATA_STATS="REMOTE_DATA_STATS",w.STATE_CHANGED="STATE_CHANGED",w.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",w.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",w.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",w.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",w.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",w.NETWORK_STATUS="NETWORK_STATUS",w.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",w))(B||{}),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||{}),_e=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(_e||{}),Ni=class extends Y{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,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){c.log("Update transport settings",e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){c.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,i=!1){let r=!1;for(let a of e){if(this._opened.indexOf(a)!==-1){c.warn(`The participant [${a}] has already had opened transport`);continue}if(this._allocated.indexOf(a)===-1){c.warn(`The participant [${a}] has no allocated transport`);continue}this._opened.push(a),r=!0}!r||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),c.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&c.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}getState(){return this._topology==="SERVER"?this._serverTransport.getState():this._directTransport.getState()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===M.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===M.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),u.log(S.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||[],a=e.offerToDeviceIdxs||[],s=i.length&&r.length?v.composeParticipantId(i[0],r[0],a[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 et(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._dtListeners&&this._dtListeners.length>0&&c.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new Oe(this._signaling,this._mediaSource,this._serverSettings);return this._stListeners&&this._stListeners.length>0&&c.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;d.noiseSuppression!==e&&(d.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(u.log(S.PAT_WAITING_TIME_ERROR,"wrongTopology"),c.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(u.log(S.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var it=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(it||{}),Ui=class extends Y{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,B.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,B.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,B.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,B.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===le.audio&&((r=this._detector)==null||r.destroy(),this._detector=new kt(e,t),!this._interval)){let a=()=>{this._collectVolumes(),this._interval=window.setTimeout(a,d.voiceParams.interval)};this._interval=window.setTimeout(a,d.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===le.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===Le.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e===_e.DIRECT&&(this._activeParticipants=null)}};var Bi=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(Bi||{}),Vi=class extends Y{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i===_e.SERVER,this.subscribe(e,it.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,B.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,B.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let a=e[r].smoothed;a>t&&a>d.voiceParams.threshold&&(t=a,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*d.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent("SPEAKER_CHANGED",e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e===_e.SERVER}};var ei=class extends Y{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,B.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,it.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"),u.log(S.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"),u.log(S.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(S.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&c.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Za=1e3,en=1e4;var tn=15,V=class extends Y{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 Yt,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Za))}static current(){return V._current}static hangupAfterInit(){V._activationMutex&&!V._current&&(V._delayedHangup=!0)}static id(){var e,t;return((t=(e=V._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",a=!1,s=!1){return o(this,null,function*(){if(V._activationMutex)throw u.log(S.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new O(b.FAILED);V._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let p=this._mediaSource.getMediaSettings();t===He.CHAT||e.length>1?this._logWithMediaSettings(S.OUTGOING_MULTIPARTY_CALL,p):this._logWithMediaSettings(S.OUTGOING_CALL,p);let l=yield this._startConversation(e,t,je.OUTGOING,i,r,a,s);if(!this._conversation)throw new O(b.UNKNOWN_ERROR);if(this._participantState=G.ACCEPTED,this._signaling.changeMediaSettings(p),yield this._processConnection(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),V._delayedHangup)throw new O(b.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let m=Object.values(this._participants),T;return d.batchParticipantsOnStart&&(T=v.mapSharedParticipants(m)),g.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,T),this._onConversationParticipantListChunk(l),g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),V._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(m,J.WAITING),this._conversation}catch(p){throw this._close(p,"Unable to start conversation"),p}finally{V._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){var t;if(V._activationMutex)throw u.log(S.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new O(b.FAILED);V._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(S.JOIN_CONVERSATION,r);let a=yield this._joinConversation(e);if(!this._conversation)throw new O(b.UNKNOWN_ERROR);return this._conversation.observer=i,g.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(c.log("In waiting hall"),V._current=this,V._activationMutex=!1,this._signaling.readyToSend(),g.onLocalStatus(J.WAITING_HALL),this._conversation):this._onJoinPart2(a)}catch(i){throw V._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return o(this,null,function*(){c.debug("Join conversation part 2"),V._activationMutex=!0;try{if(this._participantState=G.ACCEPTED,!this._conversation||!this._mediaSource)throw new O(b.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._processConnection(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),V._delayedHangup)throw new O(b.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=v.mapSharedParticipants(t)),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),this._onConversationParticipantListChunk(e),g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),V._current=this,d.batchParticipantsOnStart||this._setParticipantsStatus(t,J.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{V._activationMutex=!1}})}onPush(r){return o(this,arguments,function*(e,t=ee.USER,i){if(V._activationMutex)throw c.warn("Conversation: there is already running activation"),new O(b.REJECTED);V._activationMutex=!0;try{let a=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new O(b.UNKNOWN_ERROR);if(!a.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)"),u.log(S.PUSH,"rejected"),new O(b.REJECTED);if(yield this._processConnection(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),u.log(S.PUSH,"accepted"),V._current=this,V._delayedHangup)throw new O(b.CANCELED);V._activationMutex=!1}catch(a){throw V._activationMutex=!1,this._close(a,"Unable to handle inbound call push"),a}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(ci.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(S.ACCEPT_CONCURRENT,e),c.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),g.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(S.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(S.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)),g.onCallAccepted(),g.onLocalStream(this._mediaSource.getStream(),t),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let a=Object.values(this._conversation.muteStates);return(a.includes(Ke.MUTE)||a.includes(Ke.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),d.batchParticipantsOnStart||this._setParticipantsStatus(i,J.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return o(this,null,function*(){var e;if(this._state!=="IDLE")throw u.log(S.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(S.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;u.log(S.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new O(e))):g.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 a=i.participant;yield this._onAddParticipant(v.composeId(a),a,r)})}removeParticipant(e,t=!1){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let a of e)(a.state===G.CALLED||a.state===G.ACCEPTED)&&(this._transport.isAllocated(a.id)||this._transport.allocate(a.id,t)),a.state===G.ACCEPTED&&i.push(a.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&c.error(t,e),c.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(b.FAILED):u.log(S.ERROR,e.hangup),V._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){g.onHangup(e,i),this.destroy();return}if(e.hangup===b.HUNGUP&&(!e.remote||this._participantState===G.CALLED)){g.onHangup(e,i),this.destroy();return}if(e.hangup===b.MISSED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===b.SOCKET_CLOSED&&V._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(),u.destroy(),this._conversation=null,V._current=null,V._delayedHangup=!1,g.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(),u.destroy(),this._conversation=null,V._current=null,V._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:a}=t;if(a&&i.push(a),r){let s=r.urls.filter((p,l,m)=>m.indexOf(p)===l);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return d.iceServers=i,d.wssBase=t.endpoint,d.wssToken=t.token,t.client_type&&(d.clientType=t.client_type),t})}_addGeoParamsToEndpoint(e,t){return t.isp_as_no&&(e+=`&ispAsNo=${t.isp_as_no}`),t.isp_as_org&&(e+=`&ispAsOrg=${t.isp_as_org}`),t.loc_cc&&(e+=`&locCc=${t.loc_cc}`),t.loc_reg&&(e+=`&locReg=${t.loc_reg}`),e}_startConversation(e,t,i,r,a="",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 m=r.includes(he.VIDEO),T=yield this._api.startConversation(l,e,t,m,a,s,p);c.debug("Api.startConversation",T);let R=yield this._getConversationParams(T.id);T.endpoint=this._addGeoParamsToEndpoint(T.endpoint,R);let U=yield this._connectSignaling(Ge.START,T);return yield this._setConversation(T,U,i),U})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:a,observedIds:s}=e;c.debug("Conversation: join",{conversationId:t,joinLink:a,observedIds:s});let p=i.includes(he.VIDEO),l;if(t)l=yield this._api.joinConversation(t,p,r);else if(a)l=yield this._api.joinConversationByLink(a,p,s);else throw new O(b.UNKNOWN_ERROR);c.debug("Api.joinConversation",l),yield this._getConversationParams(l.id);let m=yield this._connectSignaling(Ge.JOIN,l);return yield this._setConversation(l,m,je.JOINING),m})}_prepareConversation(r){return o(this,arguments,function*(e,t=ee.USER,i){c.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let a=this._api.getUserId();if(!a)throw new O(b.UNKNOWN_ERROR);let s=yield this._getConversationParams(e),p=s.device_idx||0,l=`${d.wssBase}?userId=${a}&entityType=${t}&deviceIdx=${p}&conversationId=${e}&token=${d.wssToken}`;l=this._addGeoParamsToEndpoint(l,s);let m={id:e,peerId:i,endpoint:l,is_concurrent:!1,p2p_forbidden:!1,device_idx:p},T=yield this._connectSignaling(Ge.ACCEPT,m);return V._current&&(V._current._participantState===G.ACCEPTED||V._current._participantState===G.CALLED)?(c.log("Push rejected (busy)"),u.log(S.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(b.BUSY),Promise.reject({hangup:b.BUSY})):(V._current&&(V._current.destroy(),V._current=null),yield this._setConversation(m,T,je.INCOMING,t),T)})}_createParticipant(e){return o(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:ve(),participantState:{},state:G.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[]},e);if(e.externalId){let r=v.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(r,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return((i=t.observedIds)==null?void 0:i.length)&&(t.externalId.observer=!0),this._setParticipantMarkers(t,t.markers),t})}_getParticipantId(e){return o(this,null,function*(){try{let t=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(a,s,p){return o(this,arguments,function*(e,t,i,r=ee.USER){yield this._prepareParticipants(t.conversation.participants);let l=this._api.getUserId(),m=e.device_idx||0;if(!l){let U=(t.conversation.participants||[]).find(w=>v.comparePeerId(w.peerId,t.peerId));if(!U)throw new O(b.UNKNOWN_ERROR);l=Number(U.id),U.idType&&(r=U.idType),U.deviceIdx&&(m=U.deviceIdx),this._api.setUserId(l)}let T=v.composeParticipantId(l,r,m),R=yield this._getParticipantId(T);this._conversation={userId:l,compositeUserId:T,externalId:R,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||_e.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),u.log(S.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||_e.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 Si;return this.subscribe(e,De.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,De.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new At(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,Te.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,Te.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_processConnection(e){return o(this,null,function*(){yield this._registerConnectionParticipants(e),this._processConnectionData(e)})}_prepareParticipants(e){return o(this,null,function*(){let t=e.map(i=>i.id);t.length&&(yield this._api.prepareUserIds(t))})}_onConversationParticipantListChunk(e){let t=e.participants;t&&g.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(t))}_participantListChunkToExternalChunk(e){let t=v.mapSharedParticipants(e.participants.map(i=>{let r=v.composeId(i);return this._participants[r]}));return si(rt({},e),{participants:t})}_registerConnectionParticipants(e){return o(this,null,function*(){var t,i;yield this._registerParticipants(e.conversation.participants),((t=e.participants)==null?void 0:t.participants)&&(yield this._registerParticipants((i=e.participants)==null?void 0:i.participants))})}_registerParticipants(e){return o(this,null,function*(){if(!!this._conversation)for(let t of e){let i=v.composeId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(c.debug(`Local roles changed: ${t.roles}`),g.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._registerParticipantInCache(yield this._createParticipant({id:i,externalId:t.externalId&&fe.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:ve(t.mediaSettings),participantState:v.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?J.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[],markers:this._denormalizeMarkers(i,t.markers),movieShareInfos:t.movieShareInfos})),t.roles&&t.roles.length&&(c.debug(`Roles for participant [${i}] changed: ${t.roles}`),g.onRolesChanged(this._participants[i].externalId,t.roles))}})}_getClientType(){return d.clientType}_getStatusByTransportState(e){let t;return e===N.CONNECTED?t=J.CONNECTED:e===N.CONNECTING||e===N.OPENED?t=J.CONNECTING:e===N.RECONNECTING&&(t=J.RECONNECT),t}_registerParticipantInCache(e){return this._participants[e.id]=e}_getExistedParticipantByIdOrCreate(e){return o(this,null,function*(){return this._participants[e]||this._createParticipant({id:e})})}_getExternalIdByParticipantId(e){return o(this,null,function*(){var t;return d.useParticipantListChunk?(yield this._getExistedParticipantByIdOrCreate(e)).externalId:(t=this._participants[e])==null?void 0:t.externalId})}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){return o(this,null,function*(){if(d.useParticipantListChunk){let i=this._registerParticipantInCache(yield this._getExistedParticipantByIdOrCreate(e));return this._setParticipantMarkers(i,t),i}return this._participants[e]})}_warnParticipantNotInConversation(e){c.warn(`Participant [${e}] isn't in conversation`)}_setParticipantMarkers(e,t){return e.markers=this._denormalizeMarkers(e.id,t),e}_denormalizeMarkers(e,t){if(!t)return null;let i=Object.values(t).find(r=>"ts"in r&&"rank"in r);return Object.entries(t).reduce((r,[a,s])=>(r[a]=si(rt(rt({},i),s),{id:e}),r),{})}_processConnectionData(e){return o(this,null,function*(){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&&(yield this._onPinParticipant(e.conversation.pinnedParticipantId)),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(oi.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)})}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Ni(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new zt,this.subscribe(this._transport,B.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,B.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,B.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,B.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,B.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,B.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,B.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,B.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,B.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,B.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,B.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===je.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===G.ACCEPTED||t.state===G.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new Ui(this._transport),this.subscribe(this._volumesDetector,it.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Vi(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,Bi.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Qt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new ei(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=C.getCameras().length,t=C.getMicrophones().length;c.debug("Cameras: "+e+(C.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(C.hasMicrophonePermission()?"✔":"✖")),u.log(S.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"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),!!this._participants[e.id]&&(t===b.HUNGUP?this._setParticipantsStatus([e],J.HANGUP):this._setParticipantsStatus([e],J.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:ke.CAMERA,stopStream:!0}]),delete this._participants[e.id],g.onRemoteRemoved(e.externalId,e.markers)))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(a=>a.stop()),(i=e.secondStream)==null||i.getTracks().forEach(a=>a.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||(r=this._registerParticipantInCache(yield this._createParticipant({id:e,externalId:t.externalId&&fe.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:ve(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}))),this._setParticipantsStatus([r],J.WAITING),i?(r.state=G.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=G.CALLED,this._transport.allocate(r.id,!0),u.log(S.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){c.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=tn;i++){let r=v.compose(e,i),a=this._participants[r];a&&t.push(a)}if(!t.length){this._warnParticipantNotInConversation(e);return}if(this._transport)for(let i of t)this._transport.close(i.id);u.log(S.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new At(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ae.UNKNOWN)})}toggleScreenCapturing(e){return o(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ae.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(S.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return u.log(S.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 a=typeof r.uid=="object"?r.uid:fe.fromId(r.uid),s=fe.toString(a);i[s]=r.priority}for(let r of Object.values(this._participants)){let a=fe.toString(r.externalId);i.hasOwnProperty(a)&&(t[r.id]=i[a])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return o(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return o(this,null,function*(){let t={};return t[qe(e)]="kf",this._signaling.updateDisplayLayout(t)})}requestTestMode(e,t){return o(this,null,function*(){return this._signaling.requestTestMode(e,t)})}updateDisplayLayout(e){return o(this,null,function*(){if(e.length<1||!this._signaling.ready)return;c.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let a=typeof r.uid=="object"?r.uid:fe.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(a);if(!s){let T=fe.toString(a);c.log(`Unknown participant external ID ${T}`);continue}let p=v.compose(s,a.deviceIdx),l=qe({participantId:p,mediaType:r.mediaType,streamName:r.streamName}),m=this._participants[p];m&&(m.lastRequestedLayouts[l]=r),V._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]=V._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]=V._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=Dt(e),r=this._participants[i.participantId],{compositeUserId:a,externalId:s}=this._conversation,p=a===i.participantId;!r&&!p&&c.log(`Cannot find participant to stop streaming: ${i.participantId}`),i.streamName&&(i.mediaType===ke.STREAM||i.mediaType===ke.MOVIE)?p?g.onLocalLive(s,i.streamName,null):g.onRemoteLive(r.externalId,i.streamName,null):p||g.onRemoteStream(r.externalId,null),u.log(S.PAT_DEALLOCATED)}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,a]of Object.entries(t.errorCodeByParticipantId||{})){let s=Dt(r),p=this._participants[s.participantId];if(p){let l;typeof a!="number"?(c.warn(`Unexpected error code ${a} received for participant ${s.participantId}`),l=mr.UNKNOWN_ERROR):l=hr(a),i.push({externalId:p.externalId,errorReason:l})}}if(i&&i.length)throw new ti("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+en>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=V._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(V._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),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 a=[],s=[];i.length&&(i.forEach(p=>{if(p.externalId){let l=Ee.fromSignaling(p.externalId);a.push(l),this._api.cacheExternalId(p.id.id,l)}else s.push(v.decomposeId(p.id.id).id)}),s.length&&!a.length&&(a=yield this._api.getExternalIdsByOkIds(s))),g.onChatRoomUpdated(e,t,a)})}_onSharedMovieUpdate(e){c.log(`Shared movie updated: ${e.notification}`);let{compositeUserId:t,externalId:i}=this._conversation,{data:r}=e;for(let a of r)if(a.participantId===t)g.onLocalLiveUpdate(i,a);else{let p=this._participants[a.participantId];p&&g.onRemoteLiveUpdate(p.externalId,a)}}_onSharedMovieInfoStarted(e){c.log(`Shared movie started data received: ${e.notification}`);let{compositeUserId:t,externalId:i}=this._conversation,{movieShareInfo:r}=e;if(r.initiatorId===t)g.onLocalSharedMovieInfo(i,r);else{let s=this._participants[r.initiatorId];s&&g.onRemoteSharedMovieInfo(s.externalId,r)}}_onSharedMovieInfoStopped(e){c.log(`Shared movie stopped data received: ${e.notification}`);let{compositeUserId:t,externalId:i}=this._conversation,{initiatorId:r,movieId:a,source:s}=e,p={initiatorId:r,movieId:a,source:s};if(r===t)g.onLocalSharedMovieStoppedInfo(i,p);else{let m=this._participants[r];m&&g.onRemoteSharedMovieStoppedInfo(m.externalId,p)}}_waitForStreamIfNeeded(e){var p,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===ke.SCREEN)return;let i=qe(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){c.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),u.log(S.PAT_OUTDATED_RESPONSE);return}let a=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(a,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let m=t.participantId,T=this._participants[m],{compositeUserId:R,externalId:U}=this._conversation,w=R===m;if(!T&&!w){u.log(S.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${m}`);return}let j=w?U:T.externalId,ie=this._streamByStreamId.get(a);if(!ie){u.log(S.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}u.log(S.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,a);let Pe=(p=e.participantStreamDescription)==null?void 0:p.mediaType;if(Pe===ke.STREAM||Pe===ke.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&(w?g.onLocalLive(j,e.participantStreamDescription.streamName,ie):g.onRemoteLive(j,e.participantStreamDescription.streamName,ie));else if(!w){let ne=(d.producerScreenTrack?null:T.secondStream)||ie;g.onRemoteStream(T.externalId,ne)}}else{c.debug(`Waiting for ${s} until stream ${a} for ${i} is switched`);let m=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,m)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(qe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(qe(i)))return i}else{let i={participantId:t,mediaType:ke.CAMERA};if(this._streamIdByStreamDescription.has(qe(i)))return i;let r={participantId:t,mediaType:ke.SCREEN};if(this._streamIdByStreamDescription.has(qe(r)))return r}return c.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?v.includesOneOf(this._conversation.roles,[at.ADMIN,at.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!v.includesOneOf(this._conversation.roles,[at.ADMIN,at.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return o(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return o(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return o(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=tr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return o(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Jr(e));let a=yield this._signaling.getWaitingHall(r,t,i);if(a.error)return Promise.reject(a.message);let s=a.participants||[],p=[],l=[],m=null;return s.length&&(s.forEach(T=>{if(T.externalId){let R=Ee.fromSignaling(T.externalId);p.push(R),this._api.cacheExternalId(T.id.id,R)}else l.push(v.decomposeId(T.id.id).id)}),l.length&&!p.length&&(p=yield this._api.getExternalIdsByOkIds(l)),a.hasMore&&(m=qr(s[s.length-1].id))),{participants:p,pageMarker:m,totalCount:a.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(i){return o(this,arguments,function*({movieId:e,gain:t}){let r={movieId:e};(t||t===0)&&(r.gain=t);let a=yield this._signaling.addMovie(r);if(a.error)throw new Error(a.error);return{movieId:a.movieId,streamType:a.streamType}})}updateMovie(e,t,i,r){return o(this,null,function*(){let a={movieId:e};(t||t===0)&&(a.gain=t),i&&(a.offset=i),typeof r!==void 0&&(a.pause=r);let s=yield this._signaling.updateMovie(a);if(s.error)throw new Error(s.error)})}removeMovie(e){return o(this,null,function*(){let t={movieId:e},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",a=null){return o(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:a,streamMovie:!e},p=yield this._signaling.startStream(s);return p.error?Promise.reject(p.message):p})}stopStream(){return o(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return o(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return o(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return o(this,null,function*(){var r;if(e<d.videoMinWidth||t<d.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<d.videoMinWidth||i.effect.height<d.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");d.videoEffectMaxHeight=i.effect.height,d.videoEffectMaxWidth=i.effect.width}return d.videoMaxWidth=e,d.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return o(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}getParticipants(e){return o(this,null,function*(){let t=e.externalIds.map(s=>({id:s.id,type:this._getClientType()})),i=yield this._signaling.getParticipants(t);if(i.error)throw new Error(i.error);let r=i.participants,a=this._transport.getState();return Promise.all(r.map(s=>o(this,null,function*(){var l;let p=v.composeId(s);return this._createParticipant({id:p,externalId:s.externalId&&fe.fromSignaling(s.externalId,s.deviceIdx||0),mediaSettings:ve(s.mediaSettings),participantState:v.mapParticipantState(s),state:s.state,roles:s.roles||[],status:(l=this._getStatusByTransportState(a))!=null?l:J.WAITING,muteStates:s.muteStates||{},unmuteOptions:s.unmuteOptions||[],observedIds:s.observedIds||[],markers:this._denormalizeMarkers(p,s.markers)})}))).then(v.mapSharedParticipants)})}getParticipantListChunk(e){return o(this,null,function*(){let t=yield this._signaling.getParticipantListChunk(e);if(t.error)throw new Error(t.error);let i=t.chunk,r=i.participants.filter(s=>{let p=v.composeId(s);return!this._participants[p]});return yield this._prepareParticipants(r),yield this._registerParticipants(r),this._participantListChunkToExternalChunk(i)})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t,i;!this._conversation||(c.debug("Local media stream changed",e.mediaSettings),g.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return o(this,null,function*(){var t,i;if(c.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;g.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){c.debug(`Remote media settings changed [${e}]`,t);let{compositeUserId:i,externalId:r}=this._conversation,a=e===i,s=this._participants[e];if(!s&&!a){this._warnParticipantNotInConversation(e);return}a||(s.mediaSettings=t),this._state==="ACTIVE"&&(a?g.onLocalMediaSettings(r,t):g.onRemoteMediaSettings(s.externalId,t,s.markers)),this._specListener&&!a&&this._specListener.onChangeRemoteMediaSettings(e,t)}_changeRemoteParticipantState(e,t){c.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];if(!i){this._warnParticipantNotInConversation(e);return}i.participantState=t||{},this._state==="ACTIVE"&&g.onRemoteParticipantState(i.externalId,i.participantState,i.markers)}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(c.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),g.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case M.ACCEPTED_CALL:return this._onAcceptedCall(e);case M.HUNGUP:return this._onHungup(e);case M.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case M.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case M.CLOSED_CONVERSATION:return this._onClosedConversation(e);case M.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case M.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case M.RATE_CALL_DATA:return this._onNeedRate();case M.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case M.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case M.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case M.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case M.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case M.REGISTERED_PEER:return this._onPeerRegistered(e);case M.SWITCH_MICRO:return this._onMicSwitched(e);case M.CHAT_MESSAGE:return this._onChatMessage(e);case M.CUSTOM_DATA:return this._onCustomData(e);case M.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case M.RECORD_STOPPED:return this._onRecordInfo(null);case M.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case M.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case M.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin,e.markers);case M.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case M.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case M.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case M.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants);case M.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e);case M.MOVIE_SHARE_STARTED:return this._onSharedMovieInfoStarted(e);case M.MOVIE_SHARE_STOPPED:return this._onSharedMovieInfoStopped(e)}}_onSignalingReconnect(e){return o(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?yield this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&(yield this._onPinParticipant(this._conversation.pinnedParticipantId,!0))),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let a of e.conversation.participants){let s=v.composeId(a),p=a.roles||[];if(s===this._conversation.compositeUserId){t=ve(a.mediaSettings),It(this._conversation.roles,p)||this._onRolesChanged(s,p);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:a.id,participant:a,mediaSettings:a.mediaSettings});else{let m=ve(a.mediaSettings);Pr(m,l.mediaSettings)||this._changeRemoteMediaSettings(s,m);let T=v.mapParticipantState(a),R=l.participantState;v.isEqualParticipantState(T,R)||this._changeRemoteParticipantState(s,T),It(p,l.roles)||this._onRolesChanged(l.id,p)}}for(let a of i)r.indexOf(a)<0&&this._removeParticipant(this._participants[a],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||(r=this._registerParticipantInCache(yield this._createParticipant({id:t,mediaSettings:ve(e.mediaSettings)}))),r.state=G.ACCEPTED,r.mediaSettings=ve(e.mediaSettings),this._logWithMediaSettings(S.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===je.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){return o(this,null,function*(){c.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=v.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new O(e.reason,{remote:!0}));return}yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers);let i=this._participants[t];if(!i){this._warnParticipantNotInConversation(t);return}this._transport&&this._transport.close(t),i.state=e.reason===b.REJECTED?G.REJECTED:G.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,b.HUNGUP)})}_onAddedParticipant(e){return o(this,null,function*(){var r,a;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||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&fe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:v.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}))),i.state=G.CALLED,i.mediaSettings=ve((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=v.mapParticipantState(e.participant),i.roles=((a=e.participant)==null?void 0:a.roles)||[],this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),g.onParticipantAdded(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return o(this,null,function*(){var r,a;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||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&fe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:v.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[],markers:this._denormalizeMarkers(t,e.participant.markers)}))),this._conversation&&this._conversation.direction===je.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=G.ACCEPTED,i.mediaSettings=ve(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],J.CONNECTED):this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((a=this._conversation)==null?void 0:a.observer))),g.onParticipantJoined(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new O(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){return o(this,null,function*(){let t=v.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,ve(e.mediaSettings))})}_onParticipantStateChanged(e){return o(this,null,function*(){let t=v.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),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(),g.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ve(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),d.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){c.debug("Got settings update notification",e);let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=wi(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){c.debug("Got video quality update notification",e);let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=wi(this._serverSettings,r),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*(){g.onDeviceSwitched(he.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),g.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),g.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);g.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else g.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!It(this._conversation.roles,t)){c.debug(`Local roles changed: ${t}`),this._conversation.roles=t,g.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!It(i.roles,t)&&(c.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,g.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],a=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),g.onMuteStates(i,r,a,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)&&!a.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(a,e.muteAll,e.unmute,t,s)))})}_processMuteState(){return o(this,arguments,function*(e=[],t=!1,i=!1,r=null,a=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(),m=Object.entries(s);for(let[T,R]of m)if(!(R!==Ke.MUTE&&R!==Ke.MUTE_PERMANENT)&&(this._isCallAdmin()&&R===Ke.MUTE_PERMANENT&&(s[T]=Ke.MUTE),!(!e.includes(T)||i)))switch(T){case he.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(g.onDeviceSwitched(he.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case he.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(g.onDeviceSwitched(he.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case he.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(g.onDeviceSwitched(he.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}g.onMuteStates(s,p,e,t,i,null,a==null?void 0:a.externalId)})}_onPinParticipant(e,t=!1,i){return o(this,null,function*(){if(!this._conversation)return;let r=this._conversation.pinnedParticipantId;if(r&&r!==e)if(this._conversation.compositeUserId===r)g.onLocalPin(!0);else{let a=yield this._getExternalIdByParticipantId(r);a&&g.onPinnedParticipant(a,!0,this._denormalizeMarkers(e,i))}if(this._conversation.compositeUserId===e)g.onLocalPin(t);else{let a=yield this._getExternalIdByParticipantId(e);a&&g.onPinnedParticipant(a,t,this._denormalizeMarkers(e,i))}this._conversation.pinnedParticipantId=t?null:e})}_onOptionsChanged(e){this._conversation&&!er(this._conversation.options,e)&&(this._conversation.options=e,g.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let a;if(i===this._conversation.compositeUserId||i==="")a=this._conversation.networkRating;else if(this._participants[i])a=this._participants[i].networkRating;else continue;if(a!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,g.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),g.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){g.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 a=this._streamIdByStreamDescription.get(r);if(!a||this._streamWaitTimerByStreamDescription.has(r)){c.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(a);if(!s){u.log(S.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}g.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&g.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===_e.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Xi.ADD_PARTICIPANT);g.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&g.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let a=this._participants[i];a&&a.externalId&&t.push({uid:a.externalId,volume:r.real})}g.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){c.debug(`Transport state has changed: ${t}`,e);let i=this._getStatusByTransportState(t);if(!i)return;let r=e.reduce((a,s)=>{if(s in this._participants){let p=this._participants[s];a.push(p),t===N.CONNECTED&&(p.remoteStream||(p.mediaSettings&&this._changeRemoteMediaSettings(s,p.mediaSettings),this._changeRemoteParticipantState(s,p.participantState)),this._updateDisplayLayoutFromCache(s))}else this._warnParticipantNotInConversation(s);return a},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){c.debug(`Local transport state has changed: ${e}`),e===N.CONNECTED&&g.onLocalStatus(J.CONNECTED),e===N.CONNECTING&&g.onLocalStatus(J.CONNECTING),e===N.RECONNECTING&&g.onLocalStatus(J.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(Le.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i),g.onRemoteMixedAudioStream(t);else if(e.startsWith(Le.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))c.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{c.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(c.warn(`Conversation: track added before participant [${e}]`),r=this._registerParticipantInCache(yield this._createParticipant({id:e})),this._setParticipantsStatus([r],J.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===le.audio&&(this._audioOutput.add(i),d.preserveAudioTracks||t.removeTrack(i)),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;g.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 le.audio:this._removeAudioTrack(e,t,i);break;case le.video:case le.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Le.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e===_e.DIRECT&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let a=this._participants[r];e||this._lastStalled[r]?t.push(a):i.push(a)}t.length&&this._setParticipantsStatus(t,J.RECONNECT),i.length&&this._setParticipantsStatus(i,J.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(a=>{if(t[a]=!0,!this._lastStalled[a]){let s=this._participants[a];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[a]}),Object.keys(this._lastStalled).forEach(a=>{let s=this._participants[a];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,J.RECONNECT),r.length&&this._setParticipantsStatus(r,J.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!C.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(c.debug("Toggle join availability",{available:t,chatId:e}),g.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==_e.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((a,s)=>(s.status!==t&&(s.status=t,d.batchParticipantsOnStart?a.push(s.externalId):g.onParticipantStatus(s.externalId,t,i)),a),[]);!r.length||d.batchParticipantsOnStart&&g.onRemoteStatus(r,t,i)}},L=V;L._delayedHangup=!1;var ti=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,ti.prototype),this.participantErrors=t}};var ii;function rn(){return o(this,null,function*(){var n;if(d.apiEnv!=="AUTO")return d.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(n=i==null?void 0:i.Answer[0])==null?void 0:n.data;if(!r)throw new Error("Wrong DNS response");return c.debug("Resolved API endpoint",r),r}catch(e){return c.warn("Failed to resolve API endpoint using DNS, default is used",e),d.apiEndpoint}})}function Xr(){if(!d.apiKey)throw new O(ae.API,{message:"Required argument apiAppKey not passed"})}function Fi(n,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=ea(n,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${ii}/fb.do`,r)}function Zr(i){return o(this,arguments,function*(n,e={},t=!1){ii||(ii=yield rn());let r=ea(n,e,t);return an(r)})}function an(n){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${ii}/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(a){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(n)})})}function ea(n,e={},t=!1){e.method=n,e.format="JSON",e.application_key||(e.application_key=d.apiKey),t||(te.sessionKey?e.session_key=te.sessionKey:te.accessToken&&(e.access_token=te.accessToken));for(let[r,a]of Object.entries(e))typeof a=="object"&&(e[r]=JSON.stringify(a));let i="";for(let[r,a]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(a)}`;return i}var sn=10,on=700,cn=3e3,ri=class extends St{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return o(this,arguments,function*(e,t={},i=!1){let a=s=>o(this,null,function*(){try{return yield Zr(e,t,i)}catch(p){if(!p.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<sn))return yield v.delay(Math.min(s*on,cn)),a(s);throw c.warn(e,"error",p),p}});return a(0)})}_call(r){return o(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(a){c.warn("Api call error",a);let s=ae.API;switch(a.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:a.error_msg,code:a.error_code})}})}userId(e){return o(this,null,function*(){let t=v.decomposeId(e).id;return te.isEmpty()?Ee.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),Ee.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return o(this,null,function*(){te.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return o(this,null,function*(){if(!this._uuid){let t=$e.get("uuid");t||(t=v.uuid(),$e.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:d.appVersion,client_type:"SDK_JS"}};return d.authToken&&(e.session_data.auth_token=d.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),te.sessionKey=t.session_key,te.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&g.onTokenExpired(),new O(ae.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${d.appName}:${d.sdkVersion}`,platform:d.platform,items:e})};Fi("log.externalLog",t)}init(){Xr()}joinConversation(e,t=!1,i){return o(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:d.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return o(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1,protocolVersion:d.protocolVersion};return t&&(r.payload=t),d.domain&&(r.domainId=d.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,a="",s=!1,p=!1){return o(this,null,function*(){let l={conversationId:e,isVideo:r,protocolVersion:d.protocolVersion};if(t&&t.length)switch(i){case He.USER:l.uids=t.join(",");break;case He.GROUP:l.gid=t[0];break;case He.CHAT:l.chatId=t[0];break}return s&&(l.createJoinLink=!0),a&&(l.payload=a),d.domain&&(l.domainId=d.domain),p&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return o(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return o(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return o(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return o(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i){return o(this,null,function*(){let r={joinLink:e,isVideo:t,protocolVersion:d.protocolVersion};return(i==null?void 0:i.length)&&(r.observedIds=i.join(",")),d.anonymToken&&(r.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",r)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=Ee.fromIds(e),i=[],r={methods:[]},a=[],s=Object.keys(this._externalUidsCache),p=Object.values(this._externalUidsCache);for(let m of t){let T=Ee.toString(m),R=p.indexOf(T);R>-1?i.push(Number(s[R])):(a.push(T),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:m.id,anonym:m.type===_t.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((m,T)=>{if(m.ok){let R=Number(m.ok.ok_id);this._externalUidsCache[R]=a[T],i.push(R)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let a of e)this._externalUidsCache.hasOwnProperty(a)?t.push(Ee.fromString(this._externalUidsCache[a])):i.push(a);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let a of i)r.hasOwnProperty(a)&&t.push(Ee.fromString(r[a]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=Ee.toString(e),a=i.indexOf(r);return a>-1?v.composeUserId(t[a],ee.USER):null}cacheExternalId(e,t){let i=v.decomposeId(e).id;this._externalUidsCache[i]=Ee.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),Fi("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,a]of Object.entries(i.external_ids))t[r]=Ee.fromIdToString(a,_t.USER);if(i.anonym_ids)for(let[r,a]of Object.entries(i.anonym_ids))t[r]=Ee.fromIdToString(a,_t.ANONYM);return t}catch(i){return t}})}};var ta=(D=>(D.RECOVER="recover",D.ACCEPT_CALL="accept-call",D.ADD_PARTICIPANT="add-participant",D.REMOVE_PARTICIPANT="remove-participant",D.HANGUP="hangup",D.TRANSMIT_DATA="transmit-data",D.ACCEPT_PRODUCER="accept-producer",D.ALLOCATE_CONSUMER="allocate-consumer",D.CHANGE_MEDIA_SETTINGS="change-media-settings",D.CHANGE_PARTICIPANT_STATE="change-participant-state",D.CHANGE_STREAM_PRIORITIES="change-streams-priorities",D.UPDATE_DISPLAY_LAYOUT="update-display-layout",D.REPORT_PERF_STAT="report-perf-stat",D.RECORD_START="record-start",D.RECORD_STOP="record-stop",D.RECORD_SET_ROLE="record-set-role",D.RECORD_GET_STATUS="record-get-status",D.SWITCH_MICRO="switch-micro",D.SWITCH_TOPOLOGY="switch-topology",D.REQUEST_REALLOC="request-realloc",D.CHAT_MESSAGE="chat-message",D.CHAT_HISTORY="chat-history",D.CUSTOM_DATA="custom-data",D.GRANT_ROLES="grant-roles",D.MUTE_PARTICIPANT="mute-participant",D.PIN_PARTICIPANT="pin-participant",D.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",D.CHANGE_OPTIONS="change-options",D.GET_WAITING_HALL="get-waiting-hall",D.GET_PARTICIPANT_LIST_CHUNK="get-participant-list-chunk",D.GET_PARTICIPANTS="get-participants",D.PROMOTE_PARTICIPANT="promote-participant",D.REQUEST_TEST_MODE="request-test-mode",D.ADD_MOVIE="add-movie",D.UPDATE_MOVIE="update-movie",D.REMOVE_MOVIE="remove-movie",D))(ta||{}),F=ta;var ia="open",ra=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0,()=>d.movieShare,()=>d.useParticipantListChunk],dn=10,we=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="+we._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<ra.length;t++)ra[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(S.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 a=v.decomposeParticipantId(t.participantId),s=v.decomposeId(a.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),a.deviceIdx&&(t.deviceIdx=a.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return o(this,arguments,function*(e,t={},i=0){let a=s=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===ia&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){u.log(S.SOCKET_ACTION,"not_opened"),c.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(u.log(S.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=(T,R=!1)=>{!i||R?p(T):(c.debug("Resending a signaling message",e,m.sequence),i--,a(m))},m={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};a(m)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===F.UPDATE_DISPLAY_LAYOUT||e===F.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===F.UPDATE_DISPLAY_LAYOUT||e===F.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(F.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(F.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e,t){return o(this,null,function*(){return this._send(F.REQUEST_TEST_MODE,{consumer:e,producer:t})})}sendSdp(e,t){return o(this,null,function*(){return this._send(F.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(F.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(F.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},dn)})}changeParticipantState(e){return o(this,null,function*(){return this._send(F.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(F.ADD_PARTICIPANT,rt({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(F.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(F.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(F.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(F.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(F.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return o(this,null,function*(){return this._send(F.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(F.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(F.REMOVE_MOVIE,e)})}startStream(e){return o(this,null,function*(){return this._send(F.RECORD_START,e)})}stopStream(){return o(this,null,function*(){return this._send(F.RECORD_STOP)})}recordSetRole(e,t){return o(this,null,function*(){return this._send(F.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return o(this,null,function*(){return this._send(F.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(F.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(F.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(F.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(F.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(F.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(F.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(F.GRANT_ROLES,r)})}muteParticipant(e,t,i){return o(this,null,function*(){return this._sendRaw(F.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(F.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(F.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(F.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(F.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(F.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}getParticipantListChunk(e){return o(this,null,function*(){return this._send(F.GET_PARTICIPANT_LIST_CHUNK,e)})}getParticipants(e){return o(this,null,function*(){return this._send(F.GET_PARTICIPANTS,{externalIds:e})})}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ge.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),t=i(t),c.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor();function i(r){if(!d.useParticipantListChunk)return r;r+=`&partIdx=${d.participantListChunkInitIndex}`;let s=d.participantListChunkInitCount;return s!==null&&(r+=`&partCount=${s}`),r}}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){c.debug("Socket opened"),u.log(S.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(S.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(Te.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Te.NOTIFICATION,{type:"notification",notification:M.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(Te.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(u.log(S.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(u.log(S.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(Te.NOTIFICATION,{notification:M.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(ae.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(u.log(S.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(Te.FAILED,e)}_onError(e){u.log(S.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){u.log(S.SOCKET_ACTION,"closed"),c.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<we.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(we.RECONNECT_MAX_DELAY,we.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),u.log(S.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ge.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(S.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),we.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),a=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==ia){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}we._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,a),we.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(a))}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,a),we.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(a))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new O(ae.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},we.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(Ge.RETRY)},we.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Ve=we;Ve.RECONNECT_DELAY=d.signalingReconnectDelay,Ve.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,Ve.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,Ve.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,Ve.WAIT_RESPONSE_DELAY=d.waitResponseDelay,Ve.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var aa=(t=>(t.KING="KING",t.PAWN="PAWN",t))(aa||{}),pn=aa;var gt,de,xt=null,om={getCameras:C.getCameras,getMicrophones:C.getMicrophones,getOutput:C.getOutput,hasCamera:C.hasCamera,hasMicrophone:C.hasMicrophone,getSavedCamera:C.getSavedCamera,getSavedMicrophone:C.getSavedMicrophone,getSavedOutput:C.getSavedOutput,hasCameraPermission:C.hasCameraPermission,hasMicrophonePermission:C.hasMicrophonePermission,hasPermissions:C.hasPermissions,getUserMedia:C.getUserMedia,getUserVideo:C.getUserVideo,getUserAudio:C.getUserAudio,saveDeviceId:C.saveDeviceId,isBrowserSupported:C.isBrowserSupported,isScreenCapturingSupported:C.isScreenCapturingSupported,os:C.os,isMobile:C.isMobile,browserName:C.browserName,browserVersion:C.browserVersion,baseChromeVersion:C.baseChromeVersion,getAudioContext:C.getAudioContext};function ln(n){de=n}function un(n){gt=n}function cm(n){xt=n}function dm(n){d.videoEffects=n}function pm(n){return o(this,null,function*(){if(d.set(n),C.browserName()==="Sferum"&&(d.platform=`SFERUM:${C.browserVersion()}`),de||ln(new ri),gt||un(()=>new Ve),d.debug&&(na.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${d.sdkVersion}`,n),yield C.init(),!C.isBrowserSupported())throw new O(ae.UNSUPPORTED);de.init()})}function lm(a){return o(this,arguments,function*(n,e=[he.AUDIO],t="",i=!1,r=!1){let s=[],p=[];if(Array.isArray(n)?s=n.length?n:[]:n&&(s=[n]),s.length&&(p=yield de.getOkIdsByExternalIds(s),!p.length))throw new O(b.CALLEE_IS_OFFLINE);return mn(p,He.USER,e,t,i,r)})}function mn(s){return o(this,arguments,function*(n,e=He.USER,t,i="",r=!1,a=!1){if(L.current())throw c.error("There is already active call"),new O(b.FAILED);return new L(de,gt(),xt).onStart(n,e,t,i,r,a)})}function um(n){return o(this,null,function*(){return hn(n)})}function hn(i){return o(this,arguments,function*(n,e=ee.USER,t){if(n===L.id())throw new Error("Push has already been processed");return new L(de,gt(),xt).onPush(n,e,t)})}function mm(n){return o(this,null,function*(){return n&&(d.authToken=n),de.authorize()})}function hm(){return o(this,arguments,function*(n=[he.AUDIO]){return Lt().accept(n)})}function _m(){return o(this,null,function*(){let n=L.current();if(n)return n.decline()})}function gm(t){return o(this,arguments,function*(n,e=[he.AUDIO]){return _n(n,e)})}function _n(n,e,t){return o(this,null,function*(){if(L.current())throw c.error("There is already active call"),new O(b.FAILED);return new L(de,gt(),xt).onJoin({conversationId:n,mediaOptions:e,chatId:t})})}function fm(r){return o(this,arguments,function*(n,e=[he.AUDIO],t,i){if(L.current())throw c.error("There is already active call"),new O(b.FAILED);return t&&(d.anonymToken=t),new L(de,gt(),xt).onJoin({joinLink:n,mediaOptions:e,observedIds:i})})}function Sm(){return o(this,null,function*(){let n=L.current();if(n)return n.hangup();L.hangupAfterInit()})}function vm(n,e){return o(this,null,function*(){let t=yield de.getOkIdsByExternalIds([n]);if(!t.length)throw new Error("User not found");return gn(t[0],e)})}function gn(n,e){return o(this,null,function*(){let t=L.current();t&&(yield t.addParticipant(v.composeUserId(n,ee.USER),e))})}function Em(n,e=!1){return o(this,null,function*(){let t=yield de.getOkIdsByExternalIds([n]);return fn(t[0],e)})}function fn(n,e=!1){return o(this,null,function*(){let t=L.current();t&&(yield t.removeParticipant(v.composeUserId(n,ee.USER),e))})}function Im(n,e){return o(this,null,function*(){let t=yield C.saveDeviceId(n,e),i=L.current();return t&&i?i.changeDevice(n):Promise.reject()})}function Tm(n){return o(this,null,function*(){let e=L.current();return e?e.toggleScreenCapturing(n):Promise.reject()})}function Cm(n,e=!1){return o(this,null,function*(){let t=L.current();t&&(yield t.setVideoStream(n,e))})}function Pm(n){return o(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalVideo(n))})}function ym(n){return o(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalAudio(n))})}function Rm(n,e,t){return o(this,null,function*(){let i=L.current();if(i)return i.setLocalResolution(n,e,t)})}function bm(n){return o(this,null,function*(){let e=L.current();e&&(yield e.changePriorities(n))})}function Mm(n){return o(this,null,function*(){let e=L.current();e&&(yield e.changeParticipantState(n))})}function Dm(n){return o(this,null,function*(){let e=L.current();e&&(yield e.updateDisplayLayout(n))})}function Am(n,e,t=!1){return o(this,null,function*(){let i=yield de.getOkIdsByExternalIds([n]);return Sn(i[0],e,t)})}function Sn(n,e,t=!1){return o(this,null,function*(){let i=L.current();i&&(yield i.grantRoles(v.composeUserId(n,ee.USER),e,t))})}function km(){return o(this,arguments,function*(n=null,e,t=[]){let i=null;return n&&(i=(yield de.getOkIdsByExternalIds([n]))[0]),vn(i,e,t,fe.getDeviceIdx(n))})}function vn(){return o(this,arguments,function*(n=null,e,t=[],i=0){let r=L.current();if(r){let a=n?v.composeParticipantId(n,ee.USER,i):null;yield r.muteParticipant(a,e,t)}})}function Om(n,e=!1){return o(this,null,function*(){let t=yield de.getOkIdsByExternalIds([n]);return En(t[0],e,fe.getDeviceIdx(n))})}function En(n,e=!1,t=0){return o(this,null,function*(){let i=L.current();i&&(yield i.pinParticipant(v.composeParticipantId(n,ee.USER,t),e))})}function wm(n){return o(this,null,function*(){let e=L.current();e&&(yield e.updateMediaModifiers(n))})}function xm(n){return o(this,null,function*(){let e=L.current();e&&(yield e.changeOptions(n))})}function Lm(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield de.getOkIdsByExternalIds([e]))[0]),In(n,t)})}function In(n,e=null){return o(this,null,function*(){let t=L.current();if(t){let i=e?v.composeUserId(e,ee.USER):null;yield t.chatMessage(n,i)}})}function Nm(n=10){return o(this,null,function*(){let e=L.current();if(e)return e.chatHistory(n)})}function Um(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield de.getOkIdsByExternalIds([e]))[0]),Tn(n,t,fe.getDeviceIdx(e))})}function Tn(n,e=null,t=0){return o(this,null,function*(){let i=L.current();if(i){let r=e?v.composeParticipantId(e,ee.USER,t):null;yield i.customData(n,r)}})}function Bm(n="",e=!1){return o(this,null,function*(){return(yield de.createConversation(v.uuid(),n,e)).join_link})}function Vm(){return o(this,null,function*(){let n=L.current();return n?n.createJoinLink():Promise.reject()})}function Fm(){return o(this,null,function*(){let n=L.current();return n?n.removeJoinLink():Promise.reject()})}function Hm(n,e){return o(this,null,function*(){return de.getAnonymTokenByLink(n,e)})}function Gm(n){let e=L.current();e&&e.setVolume(n)}function Wm(n){d.forceRelayPolicy=n}function jm(n=!1,e=null,t=null,i="DIRECT_LINK",r=null){return o(this,null,function*(){let a=L.current();return a?a.startStream(n,e,t,i,r):Promise.reject()})}function Km(){return o(this,null,function*(){let n=L.current();return n?n.stopStream():Promise.reject()})}function $m(n,e){return o(this,null,function*(){let t=L.current();if(t){let i=yield de.getOkIdsByExternalIds([n]),r=fe.getDeviceIdx(n);return t.recordSetRole(v.composeParticipantId(i[0],ee.USER,r),e)}return Promise.reject()})}function qm(){return o(this,null,function*(){let n=L.current();return n?n.getStreamInfo():Promise.reject()})}function Jm(n){return o(this,null,function*(){let e=L.current();return e?e.addMovie(n):Promise.reject()})}function Ym(n,e,t,i){return o(this,null,function*(){let r=L.current();return r?r.updateMovie(n,e,t,i):Promise.reject()})}function zm(n){return o(this,null,function*(){let e=L.current();return e?e.removeMovie(n):Promise.reject()})}function Qm(n){d.statisticsInterval=n;let e=L.current();if(e)return e.updateStatisticsInterval()}function Xm(n){na.disableLog(!n),c.toggle(n)}function Zm(n,...e){!d.debugLog||c.send(n,"[external]",...e)}function eh(n){return o(this,null,function*(){let e=L.current();if(e)return e.videoEffect(n)})}function th(n){return o(this,null,function*(){let e=L.current();e&&(yield e.setAudioStream(n))})}function ih(n=null,e,t=!1){return o(this,null,function*(){return Lt().getWaitingHall(n,e,t)})}function rh(n,e=!1){return o(this,null,function*(){let t=Lt(),i=yield de.getOkIdsByExternalIds([n]);return t.promoteParticipant(v.composeUserId(i[0],ee.USER),e)})}function ah(n){return o(this,null,function*(){return Lt().getParticipantListChunk(n)})}function nh(n){return o(this,null,function*(){return Lt().getParticipants(n)})}function Lt(){let n=L.current();if(!n)throw new Error("Conversation not found");return n}function sh(n){return o(this,null,function*(){yield de.removeHistoryRecords(n)})}export{ri as Api,St as BaseApi,vt as BaseLogger,Et as BaseSignaling,je as CallDirection,He as CallType,oi as ChatRoomEventType,ci as ConversationOption,jr as DebugMessageType,_t as ExternalIdType,kr as FacingMode,ae as FatalError,O as HangupReason,b as HangupType,he as MediaOption,le as MediaTrackKind,ke as MediaType,Ke as MuteState,G as ParticipantState,J as ParticipantStatus,pn as RecordRole,Ve as Signaling,F as SignalingCommandType,Ge as SignalingConnectionType,M as SignalingNotification,at as UserRole,ee as UserType,v as Utils,hm as acceptCall,Jm as addMovie,vm as addParticipant,gn as addParticipantInternal,mm as authorize,om as browser,mn as callInternal,lm as callTo,Tm as captureScreen,xm as changeConversationOptions,Im as changeDevice,Mm as changeParticipantState,bm as changePriorities,eh as changeVideoEffect,Nm as chatHistory,Lm as chatMessage,In as chatMessageInternal,Vm as createJoinLink,Um as customData,Tn as customDataInternal,Xm as debug,Zm as debugMessage,_m as declineCall,Wm as forceRelayPolicy,Hm as getAnonymTokenByLink,ah as getParticipantListChunk,nh as getParticipants,qm as getStreamInfo,ih as getWaitingHall,Am as grantRoles,Sn as grantRolesInternal,Sm as hangup,pm as init,gm as joinCall,fm as joinCallByLink,_n as joinCallInternal,km as muteParticipant,vn as muteParticipantInternal,Om as pinParticipant,En as pinParticipantInternal,um as processPush,hn as processPushInternal,rh as promoteParticipant,$m as recordSetRole,sh as removeHistoryRecords,Fm as removeJoinLink,zm as removeMovie,Em as removeParticipant,fn as removeParticipantInternal,ln as setApi,th as setAudioStream,Rm as setLocalResolution,cm as setLogger,wm as setMediaModifiers,un as setSignalingFactory,Qm as setStatisticsInterval,dm as setVideoEffects,Cm as setVideoStream,Gm as setVolume,Bm as startConversation,jm as startStream,Km as stopStream,ym as toggleLocalAudio,Pm as toggleLocalVideo,Dm as updateDisplayLayout,Ym as updateMovie};