@vkontakte/calls-sdk 2.4.4-dev.c28b095.0 → 2.5.2-dev.75f890a.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CallsSDK.d.ts +2 -1
- package/abstract/BaseApi.d.ts +1 -1
- package/calls-sdk.cjs.js +16 -9
- package/calls-sdk.esm.js +16 -9
- package/classes/Conversation.d.ts +1 -1
- package/classes/Logger.d.ts +3 -0
- package/classes/codec/IDecoder.d.ts +2 -2
- package/classes/codec/LibVPxDecoder.d.ts +2 -2
- package/classes/codec/WebCodecsDecoder.d.ts +2 -2
- package/classes/screenshare/ScreenCaptureReceiver.d.ts +6 -1
- package/classes/transport/PerfStatReporter.d.ts +16 -0
- package/classes/transport/ServerTransport.d.ts +1 -0
- package/classes/transport/Statistics.d.ts +1 -0
- package/classes/transport/Transport.d.ts +1 -0
- package/enums/HangupType.d.ts +1 -0
- package/package.json +3 -1
- package/static/Params.d.ts +9 -7
- package/types/MediaSettings.d.ts +1 -0
package/calls-sdk.esm.js
CHANGED
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/calls-sdk v2.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/callssdk/2-
|
|
2
|
+
* @vkontakte/calls-sdk v2.5.2-dev.75f890a.0
|
|
3
|
+
* Mon, 24 Jan 2022 11:47:27 GMT
|
|
4
|
+
* https://st.mycdn.me/static/callssdk/2-5-2/doc/
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
var zr=Object.defineProperty;var ki=Object.getOwnPropertySymbols;var Qr=Object.prototype.hasOwnProperty,Xr=Object.prototype.propertyIsEnumerable;var wi=Math.pow,Ni=(a,e,t)=>e in a?zr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,xi=(a,e)=>{for(var t in e||(e={}))Qr.call(e,t)&&Ni(a,t,e[t]);if(ki)for(var t of ki(e))Xr.call(e,t)&&Ni(a,t,e[t]);return a};var s=(a,e,t)=>new Promise((i,r)=>{var n=l=>{try{p(t.next(l))}catch(m){r(m)}},c=l=>{try{p(t.throw(l))}catch(m){r(m)}},p=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,c);p((t=t.apply(a,e)).next())});import Jr from"webrtc-adapter";var dt=class{createJoinLink(e){return s(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return s(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return s(this,null,function*(){return""})}log(e){}prepareUserIds(e){return s(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return s(this,null,function*(){})}cleanup(){}getTokenForAnonym(e,t){return s(this,null,function*(){return""})}call(i){return s(this,arguments,function*(e,t={}){return null})}};var pt=class{log(e,t,i=!1){}destroy(){}};var J=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var lt=class extends J{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var Li=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(Li||{}),Ue=Li;var Ui=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(Ui||{}),xe=Ui;var Bi=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(Bi||{}),Jt=Bi;var Vi=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(Vi||{}),Fi=Vi;var Hi=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(Hi||{}),Yt=Hi;function Gi(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function Wi(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 ji=(F=>(F.CAMERA_PERMISSION="camera",F.MIC_PERMISSION="mic",F.CAMERA_ACCESS="cameralock",F.MIC_ACCESS="miclock",F.MIC_NOT_FOUND="nomic",F.SCREEN_PERMISSION="screenpermission",F.SCREEN_ACCESS="screenlock",F.CONNECTION="connection",F.NETWORK="network",F.UNKNOWN="unknown",F.UNSUPPORTED="unsupported",F.SIGNALING_FAILED="signalingfailed",F.API="api",F.AUTH="auth",F))(ji||{}),ie=ji;var Ki=(H=>(H.CANCELED="CANCELED",H.REJECTED="REJECTED",H.REMOVED="REMOVED",H.HUNGUP="HUNGUP",H.MISSED="MISSED",H.BUSY="BUSY",H.FAILED="FAILED",H.NETWORK_ERROR="NETWORK_ERROR",H.KILLED="KILLED",H.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",H.NOT_FRIENDS="NOT_FRIENDS",H.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",H.UNKNOWN_ERROR="UNKNOWN_ERROR",H.UNSUPPORTED="UNSUPPORTED",H.OLD_VERSION="OLD_VERSION",H.SERVICE_DISABLED="SERVICE_DISABLED",H.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",H.SOCKET_CLOSED="SOCKET_CLOSED",H.ENDED="ENDED",H))(Ki||{}),R=Ki;var $i=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))($i||{}),ce=$i;var qi=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(qi||{}),Be=qi;var Ji=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(Ji||{}),W=Ji;var Yi=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(Yi||{}),Le=Yi;var zi=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(zi||{}),me=zi;var Qi=(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))(Qi||{}),O=Qi;var Xi=(I=>(I.ERROR="callError",I.DEVICES="callDevices",I.CALL_SPEC_ERROR="callSpecError",I.ICE_CONNECTION_STATE="callIceConnectionState",I.ICE_CONNECTION_TYPE="callIceConnectionType",I.ICE_RESTART="callIceRestart",I.PUSH="callPush",I.OUTGOING_CALL="callStart",I.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",I.JOIN_CONVERSATION="callJoinConversation",I.ACCEPTED_OUTGOING="callAcceptedOutgoing",I.ACCEPT_INCOMING="callAcceptIncoming",I.DECLINE_INCOMING="callDeclineIncoming",I.ACCEPT_CONCURRENT="callAcceptConcurrent",I.HANGUP="callHangup",I.MEDIA_STATUS="callMediaStatus",I.DEVICE_CHANGED="callDeviceChanged",I.SOCKET_ACTION="callSocketAction",I.ADD_PARTICIPANT="callAddParticipant",I.REMOVE_PARTICIPANT="callRemoveParticipant",I.POOR_CONNECTION="callPoorConnection",I.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",I.RELAY_POLICY="callForceRelay",I.PAT_ALLOCATED="patAllocate",I.PAT_DEALLOCATED="patDeallocate",I.PAT_ERROR="patError",I.PAT_WAITING_TIME_ERROR="patWaitingTimeError",I.PAT_OUTDATED_RESPONSE="patOutdatedResponse",I))(Xi||{}),h=Xi;var Zi=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(Zi||{}),be=Zi;var er=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(er||{}),tr=er;function ir(a){switch(a){case 1:return"no-available-tracks";default:return"unknown-error"}}var rr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(rr||{}),ze=rr;function ut(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var ar=(t=>(t.USER="USER",t.GROUP="GROUP",t))(ar||{}),X=ar;var zt=class{constructor(){this._items=[]}get length(){return this._items.length}push(e){this._items.push(e)}shift(){return this._items.shift()||null}bisect(){let e=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(e)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(e,t)=>t instanceof Error?String(t):t):""}};var nr=2*1024*1024,Zr=512*1024,mt=100*1024,ea=5,Qt="_okcls_logs_session_",ta=3e4,sr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=nr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(Qt)!==0)continue;let i=e.getItem(t);if(!i){dr(t);continue}let r=cr(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(mt)}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(Qt,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(dr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>nr||this.length>ea-1||this.size+e>this.available);)this.deleteOldestItem()}};function or(){return`${Qt}${Date.now()}`}function cr(a){return new Blob([a]).size}function dr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function Xt(){let a=He.toString();if(!_e.available||!a)return;let e=cr(a);_e.cleanup(e);try{window.localStorage.setItem(Pt,a)}catch(t){if(console.warn("Failed to write log to storage",t),_e.storageSize=_e.size+e,_e.cleanup(mt+e),_e.available>=mt+e){Xt();return}if(e>mt){He.bisect(),Xt();return}_e.storageSize=0;return}e>Zr&&(_e.add(Pt,e),Pt=or(),He.clear(),_e.cleanup(mt))}function Zt(){!_e.available||!He.length||Xt()}function ia(a=!1){let e=[];try{let r=window.localStorage;for(let c of _e.items){let p=r.getItem(c.key);e.push(p)}let n=He.toString();n&&e.push(n)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(a)return t;let i=`logs_${Date.now()}.json`;return ra(t,i),i}function ra(a,e){let t=document.createElement("a"),i=new Blob([a],{type:"text/json"});t.href=URL.createObjectURL(i),t.download=e,t.click()}function pr(a,e){!_e.available||(He.push({t:Date.now(),l:a,d:e}),ti||(ti=window.setTimeout(()=>{ti=null,Zt()},ta)))}function ei(){_e||(_e=new sr,He=new zt,Pt=or(),window.addEventListener("beforeunload",Zt))}var _e,He,Pt,ti=null;window.__VKCallsSDKLogs__=(a=!1)=>(_e||ei(),Zt(),ia(a));import lr from"@vkontakte/libvpx";var he=(c=>(c.INIT="init",c.READY="ready",c.FRAME="frame",c.ERROR="error",c.DEBUG="debug",c.LOG_ERROR="log_error",c))(he||{});var u=class extends pt{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:{},uid:this._api.getUserId()};typeof t!="undefined"&&(r.custom.param=t),this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch(),this._externalLogger&&this._externalLogger.log(e,t,i)}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){u._instance||(u._instance=new u(e,t))}static log(e,t,i=!1){u._instance&&u._instance.log(e,t,i)}static destroy(){u._instance&&u._instance.destroy(),u._instance=null}};var De=class{constructor(){this._worker=null}_createWorker(c,p){return s(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((l,m)=>{let y=i.join(","),D=new Blob([e,`exports.default(${y});`],{type:"application/javascript; charset=utf-8"}),j=window.URL.createObjectURL(D);this._worker=new Worker(j),this._worker.onmessage=te=>{switch(te.data.type){case he.READY:l();break;case he.ERROR:m(te.data.error);break;case he.FRAME:t(te.data);break;case he.DEBUG:o.debug(te.data.message);break;case he.LOG_ERROR:u.log(h.ERROR,te.data.message);break}},this._sendToWorker(he.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 Qe=class extends De{init(e){return s(this,null,function*(){o.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var y=Object.defineProperty;var E=a=>y(a,"__esModule",{value:!0});var M=(a,p)=>{E(a);for(var e in p)y(a,e,{get:p[e],enumerable:!0})};var D={};M(D,{default:()=>V});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var V=(a,p)=>{let e=null,n=null,g=!0;function b(){return a({locateFile:p}).then(r=>n=r)}function s(r,m,l,R,x){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(x),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let d=e.getImageBuffer();if(!d){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let c=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(d.byteLength);if(i.set(d),R){let o=new ImageData(i,c,f);createImageBitmap(o,0,0,c,f).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:i.buffer,width:c,height:f},[i.buffer])}b().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return D;})();\n',t=>{if(t.error)o.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i)}else e(t.data)},[lr,lr.getUrl])})}decodeFrame(e,t,i,r){let n="ImageBitmap"in window;this._sendToWorker(he.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:n,debug:o.enabled()},[t.buffer])}destroy(){this._removeWorker(),o.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var Ge=class extends De{init(e){return s(this,null,function*(){o.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var i=Object.defineProperty;var f=e=>i(e,"__esModule",{value:!0});var E=(e,d)=>{f(e);for(var a in d)i(e,a,{get:d[a],enumerable:!0})};var g={};E(g,{default:()=>V});var s=(a=>(a.VP9="vp09.00.50.08",a.VP8="vp8",a))(s||{}),o=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(o||{});var V=()=>{let e=null,d=!0;function a(){self.postMessage({type:o.READY})}function l(r,p,t,m=!1){(!e||d!==t)&&(d=t,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${t?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${t?"VP9":"VP8"}`}),e=new VideoDecoder({output:c=>{("createImageBitmap"in c?c.createImageBitmap():createImageBitmap(c)).then(n=>{self.postMessage({type:o.FRAME,data:n}),n.close()}).finally(()=>c.close())},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:t?s.VP9:s.VP8}));let u=new EncodedVideoChunk({type:m?"key":"delta",timestamp:r,data:p});e.decode(u)}self.onmessage=r=>{switch(r.data.type){case o.INIT:a();break;case o.FRAME:l(r.data.timestamp,r.data.data,r.data.isVP9,r.data.keyFrame);break}}};return g;})();\n',t=>{t.error?o.warn("WebCodecsDecoder",t.error):e(t.data)})})}decodeFrame(e,t,i,r=!1){this._sendToWorker(he.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),o.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window&&"ImageBitmap"in window&&"createImageBitmap"in window}};var ii="_okcls_",Xe=(()=>{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 na(a){let e=Xe?Xe.getItem(ii+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function sa(a,e){try{Xe&&Xe.setItem(ii+a,JSON.stringify(e))}catch(t){}}function oa(a){Xe&&Xe.removeItem(ii+a)}var ri;(i=>{function a(r){return na(r)||null}i.get=a;function e(r,n){sa(r,n)}i.set=e;function t(r){oa(r)}i.remove=t})(ri||(ri={}));var Ve=ri;import ht from"big-integer";function ur(a,e){if(a.isAudioEnabled!==e.isAudioEnabled||a.isVideoEnabled!==e.isVideoEnabled||a.isScreenSharingEnabled!==e.isScreenSharingEnabled||a.videoStreams.length!==e.videoStreams.length)return!1;for(let t of a.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function ge(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}var mr=a=>a.stop(),hr=a=>a.getTracks().forEach(mr),ai=a=>a.getVideoTracks().forEach(mr),gr=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(R).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 fe=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(fe||{}),le=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(le||{}),ni=class extends J{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=ge();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return s(this,arguments,function*(e=[ce.AUDIO]){if(this._stream)return;let t=e.includes(ce.VIDEO),i=e.includes(ce.AUDIO);if(!T.isBrowserSupported())throw new k(ie.UNSUPPORTED);try{this._stream=yield T.getUserMedia(t,i),this._mediaSettings.isVideoEnabled=t&&this._stream.getVideoTracks().filter(r=>r.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=i&&this._stream.getAudioTracks().filter(r=>r.enabled).length>0||!1}catch(r){throw new k(r)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t=!1){let i=this.getStream(),r=this._getSendAudioTrack(),n=this.getSendVideoTrack(t);if(!i||!r&&!n)throw new Error("No local stream found");r&&e.addTrack(r,i),n&&e.addTrack(n,i)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return s(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return s(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=S.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);navigator.mediaDevices.addEventListener("devicechange",()=>s(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),c=n&&n.groupId,p=this._stream.getVideoTracks()[0],l=p&&p.enabled&&p.getSettings(),m=l&&l.groupId;if(!c&&!m)return;let y=yield navigator.mediaDevices.enumerateDevices();!e&&c&&(e=!y.find(D=>D.groupId===c)),!t&&m&&(t=!y.find(D=>D.groupId===m)),i()}))}_changeVideoInput(e=null){return s(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield T.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{d.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),n=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),u.log(h.DEVICE_CHANGED,t),o.log("Video stream changed"),yield this._replaceLocalTrack(n),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(h.ERROR,"change_video"),o.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=gr(e)),t=this._trackVideoStreamBackup.clone(),ai(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),ai(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return s(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return s(this,null,function*(){try{if(e=e||(yield T.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),u.log(h.DEVICE_CHANGED,"audio"),o.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(h.ERROR,"change_audio"),o.error("Microphone change failed",t),t}})}_changeScreen(e){return s(this,null,function*(){try{if(e=e||(yield T.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=d.consumerScreenTrack?t:yield this._videoEffect(null,t);u.log(h.DEVICE_CHANGED,"screen"),o.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,d.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=d.consumerScreenDataChannel?T.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw u.log(h.ERROR,"screen"),o.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return s(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,n;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(n=this._stream)==null||n.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return s(this,null,function*(){if(!d.videoEffects)return t;try{return u.log(h.DEVICE_CHANGED,`effect_${e}`),d.videoEffects.setEffect(e,t)}catch(i){return o.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){d.videoEffects&&(this._effect=null,d.videoEffects.destroy()),this._stream&&(hr(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return s(this,null,function*(){return e?this._changeScreen():d.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return s(this,null,function*(){if(!this._stream)return;d.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield T.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=T.getBlackMediaTrack(d.videoMinWidth,d.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return s(this,null,function*(){if(!this._stream)return;let t;e?t=(yield T.getUserAudio()).getAudioTracks()[0]:t=T.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return s(this,null,function*(){if(!d.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return s(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks()[0];if(!e)throw new Error("Local audio track not found");if(!!e.enabled)return e.applyConstraints({noiseSuppression:d.noiseSuppression})})}videoEffect(e){return s(this,null,function*(){if(!d.videoEffects)throw new Error("Video Effects library is not set");if(!d.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var si;(Oi=>{function a(v,C,b,I,A=!1){let Te=/[\r\n]+/,Y=`\r
|
|
8
|
-
`;if(!
|
|
9
|
-
`);for(let Y of b)if(Y.startsWith("a=fingerprint")){let N=Y.split(" ");if(N.length===2){C=N[1];break}}if(!C)return ht.minusOne;let I=C.split(":"),A=ht.zero;for(let Y=Math.min(7,I.length-1);Y>=0;Y--){let N=ht(I[Y],16);A=A.shiftLeft(8).or(N)}return((Y,N)=>{let z=N.value;if(typeof z=="bigint")return ht(BigInt.asIntN(Y,z));let P=ht.one.shiftLeft(Y),K=N.and(P.subtract(1));return K.greaterOrEquals(P.subtract(K))?K.subtract(P):K})(64,A)}Oi.sdpFingerprint=j;function te(v){return s(this,null,function*(){return new Promise(C=>window.setTimeout(C,v))})}Oi.delay=te;function F(v,C,b){let I=[];return v.getSenders().forEach(A=>ue(C,A,A.track,b,I)),I}Oi.applySettings=F;function ue(v,C,b,I,A){if(v&&b&&b.kind===le.video){let Te=b.getSettings();if(Te){let Y=v.maxBitrateK?v.maxBitrateK*1024:null,N=Te.width,z=Te.height,P=N&&z&&v.maxDimension?Math.max(1,Math.max(N,z)/v.maxDimension):null,K=v.maxFramerate?v.maxFramerate:null,se=v.degradationPreference?v.degradationPreference:"balanced",M=I[b.id];if(M&&M.bitrate===Y&&M.scaleResolutionDownBy===P&&M.maxFramerate===K&&M.degradationPreference===se){A[b.id]=M;return}A[b.id]={bitrate:Y,scaleResolutionDownBy:P,maxFramerate:K,degradationPreference:se};let Ne=C.getParameters();Ne.encodings||(Ne.encodings=[{}]),Ne.encodings.forEach(q=>{Y?q.maxBitrate=Y:delete q.maxBitrate,P?q.scaleResolutionDownBy=P:delete q.scaleResolutionDownBy,K?q.maxFramerate=K:delete q.maxFramerate}),Ne.degradationPreference=se,C.setParameters(Ne)}}}Oi.applyVideoTrackSettings=ue;function Me(v,C){Array.isArray(C)||(C=[C]);for(let b of C)if(v.includes(b))return!0;return!1}Oi.includesOneOf=Me;function de(v){var C;return Object.entries(((C=v.participantState)==null?void 0:C.state)||{}).reduce((b,[I,A])=>(v.participantState&&(b[I]={ts:v.participantState.stateUpdateTs[I],state:A}),b),{})}Oi.mapParticipantState=de;function Ye(v){return Object.entries(v).reduce((C,[b,{state:I}])=>(C[b]=I,C),{})}Oi.mapLegacyParticipantState=Ye;function H(v){return v.map(C=>{let b={uid:C.externalId,mediaSettings:C.mediaSettings,status:C.status,muteStates:C.muteStates,unmuteOptions:C.unmuteOptions};return d.participantStateMapped&&(b.participantState=C.participantState),b})}Oi.mapSharedParticipants=H;function ye(v,C){let b=Object.keys(v),I=Object.keys(C);if(b.length!==I.length)return!1;for(let A of b)if(!I.hasOwnProperty(A)||v[A].state!==C[A].state||v[A].ts!==C[A].ts)return!1;return!0}Oi.isEqualParticipantState=ye;function Re(v,C){let b=Object.keys(v),I=Object.keys(C);if(b.length!==I.length)return!1;for(let A of b)if(!C.hasOwnProperty(A)||v[A]!==C[A])return!1;return!0}Oi.isObjectsEquals=Re;function ot(v,C){if(v.length!==C.length)return!1;for(let b of v)if(C.indexOf(b)<0)return!1;return!0}Oi.isArraysEquals=ot;function Di(v){return!Object.keys(v).length}Oi.isEmptyObject=Di})(si||(si={}));var S=si;var We=null,oi=null,Mt=[],At=[],ci=[],gt=null,_t=null,di=null,pi=!1,li=!1,Dt,Ze,Ot,_r=!1,fr=!1,ui=null,mi="",kt=[],hi=null,Sr=navigator.appVersion,ca=navigator.appName,Se=navigator.userAgent,vr=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(vr||{}),ft=class{constructor(e,t=!1,i=d.videoMaxWidth,r=d.videoMaxHeight){let n=!1;if(e){n={noiseSuppression:d.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let p;_t&&(p=_t.deviceId),typeof e=="string"&&(p=e),p&&(n.deviceId={exact:p})}let c=!1;if(t){c={width:{min:d.videoMinWidth,max:i,ideal:i},height:{min:d.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:d.videoAspectRatio},frameRate:{ideal:d.videoFrameRate}};let p;gt&&(p=gt.deviceId),typeof t=="string"&&(p=t),p&&(c.deviceId={exact:p}),d.videoFacingMode&&(c.facingMode={exact:d.videoFacingMode})}this.audio=n,this.video=c,this.needVideo=!!c}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},Er=class extends ft{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=d.screenFrameRate}};function da(){return s(this,null,function*(){We=null,yield wt()})}function pa(){We=null,wt().then(()=>_.onDeviceChange())}function wt(){return s(this,null,function*(){return We||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!oi&&navigator.mediaDevices.addEventListener&&(oi=S.throttle(pa,1e3),navigator.mediaDevices.addEventListener("devicechange",oi)),We=navigator.mediaDevices.enumerateDevices().then(a=>{Mt=a.filter(r=>r.kind==="videoinput"?(r.label&&(pi=!0),!0):!1),At=a.filter(r=>r.kind==="audioinput"?(r.label?li=!0:je.isMobile()&&je.browserName()==="Firefox"&&(li=pi),!0):!1),ci=a.filter(r=>r.kind==="audiooutput");let e=Ve.get("videoinput"),t=Ve.get("audioinput"),i=Ve.get("audiooutput");return gt=Mt.find(r=>r.deviceId===e)||null,_t=At.find(r=>r.deviceId===t)||null,di=ci.find(r=>r.deviceId===i)||null,We=Promise.resolve(a),a}).catch(()=>(We=null,[]))))})}function la(){return s(this,null,function*(){return je.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(_r=!0),/^a=mid:0$/m.test(t.sdp)&&(fr=!0),a()}).catch(a)}):Promise.resolve()})}function Nt(a,e){return s(this,null,function*(){o.debug("Try to get media",a.getNative());let t=je.hasPermissions(a.isVideo());!t&&!e&&_.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield da()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?ie.CAMERA_PERMISSION:ie.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?ie.CAMERA_ACCESS:ie.MIC_ACCESS;break}if(a.canSimplify())return Nt(a.simplify(),e);let r=e||ie.UNKNOWN;throw _.onPermissionsError(r),r}})}function ua(a){return s(this,null,function*(){o.debug("Try to get screen",a.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(a.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(o.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw ie.SCREEN_PERMISSION;default:throw ie.SCREEN_ACCESS}}})}function gi(){return kt.length||(kt=(()=>{let a,e=!1,t=0,i=Se.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return a=/\brv[ :]+(\d+)/g.exec(Se),["IE",a&&a[1]||"Unknown",e,t];if(i[1]==="Safari"){if(a=Se.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(a=Se.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,a[1]];if(a=Se.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t];if(a=Se.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t];if(a=Se.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),a=Se.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t];if(a=Se.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t];if(a=Se.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t];if(a=Se.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t]}return a=Se.match(/version\/(\d+)/i),[i[2]?i[1]:ca,a&&a[1]||i[2]||Sr,e,t]})()),kt}var je;(Y=>{function a(){return s(this,null,function*(){return yield la(),wt()})}Y.init=a;function e(){return Mt}Y.getCameras=e;function t(){return At}Y.getMicrophones=t;function i(){return ci}Y.getOutput=i;function r(){return Mt.length>0}Y.hasCamera=r;function n(){return At.length>0}Y.hasMicrophone=n;function c(){return gt}Y.getSavedCamera=c;function p(){return _t}Y.getSavedMicrophone=p;function l(){return di}Y.getSavedOutput=l;function m(){return pi}Y.hasCameraPermission=m;function y(){return li}Y.hasMicrophonePermission=y;function D(N=!1){return y()?r()&&N?m():!0:!1}Y.hasPermissions=D;function j(N=!1,z=!0){return s(this,null,function*(){let P=n()&&z,K=r()&&N,se;if(!P&&!K)se=new MediaStream;else try{se=yield Nt(new ft(P,K))}catch(M){se=new MediaStream}return se.getVideoTracks().length||se.addTrack(Ye()),se.getAudioTracks().length||se.addTrack(de()),se})}Y.getUserMedia=j;function te(){return s(this,null,function*(){return ua(new Er(window.screen.width,window.screen.height))})}Y.getScreenMedia=te;function F(N,z=!1){return s(this,null,function*(){let P=z?d.videoEffectMaxWidth:d.videoMaxWidth,K=z?d.videoEffectMaxHeight:d.videoMaxHeight;return Nt(new ft(!1,N||!0,P,K))})}Y.getUserVideo=F;function ue(N){return s(this,null,function*(){return Nt(new ft(N||!0,!1))})}Y.getUserAudio=ue;function Me(N,z){return s(this,null,function*(){let K=(yield wt()).find(se=>se.kind===N&&se.deviceId===z);return K?(N==="videoinput"?gt=K:N==="audioinput"?_t=K:N==="audiooutput"&&(di=K),Ve.set(N,z),K):null})}Y.saveDeviceId=Me;function de(){if(!Ot||Ot.readyState==="ended"){let N=Te(),z=N.createMediaStreamDestination(),P=N.createGain();P.gain.value=1e-5,P.connect(z),P.connect(N.destination);let K=N.createOscillator();K.type="sine",K.frequency.value=0,K.connect(P),K.start(),Ot=z.stream.getAudioTracks()[0]}return Object.assign(Ot.clone(),{enabled:!1})}Y.getSilentMediaTrack=de;function Ye(N=d.videoMinWidth,z=d.videoMinHeight){return Ze||(Ze=document.createElement("canvas"),Ze.getContext("2d")),Ze.width=N,Ze.height=z,(!Dt||Dt.readyState==="ended")&&(Dt=Ze.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(Dt.clone(),{enabled:!1})}Y.getBlackMediaTrack=Ye;function H(){if(b()==="Edge"&&I()<70)return!1;try{let N=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&N.RTCPeerConnection&&N.RTCIceCandidate&&N.RTCSessionDescription&&N.HTMLCanvasElement&&N.HTMLCanvasElement.prototype.captureStream&&N.RTCRtpSender&&N.RTCRtpSender.prototype.replaceTrack&&N.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(N){return!1}}Y.isBrowserSupported=H;function ye(){return!!navigator.mediaDevices.getDisplayMedia}Y.isScreenCapturingSupported=ye;function Re(){return _r}Y.canVP8=Re;function ot(){return fr}Y.isUnifiedPlan=ot;function Di(){return Y.browserName()==="Opera"&&Y.os()==="Windows"}Y.isBrokenH264=Di;function Oi(){return!(Y.baseChromeVersion()&&Y.isMobile())}Y.canPreferH264=Oi;function v(){return mi||(mi=(()=>{let N={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let z in N)if(N.hasOwnProperty(z)&&N[z].test(Se))return z;return"Unknown"})()),mi}Y.os=v;function C(){return ui===null&&(ui=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Sr)),ui}Y.isMobile=C;function b(){return gi()[0]}Y.browserName=b;function I(){return gi()[1]}Y.browserVersion=I;function A(){return gi()[3]}Y.baseChromeVersion=A;function Te(){return hi||(hi=new(window.AudioContext||window.webkitAudioContext)),hi}Y.getAudioContext=Te})(je||(je={}));var T=je;import{BitStream as ma}from"bit-buffer";var ha=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&&(o.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%ha!==e.sequence){o.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,c)=>n+c.data.byteLength,0),i=new Uint8Array(t),r=0;for(let n of e)i.set(new Uint8Array(n.data),r),r+=n.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new ma(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),c=i.readBits(1)<<1|r;return c===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,c>=2&&i.index++,i.readBits(3)!==7?(i.index++,(c===1||c===3)&&(i.index+=3)):(c===1||c===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var St=class extends Ke{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;o.debug(`StreamBuilder started for participant [${e}]`),this._useImageBitmap="ImageBitmap"in window,Ge.isBrowserSupported()?this._decoder=new Ge:this._decoder=new Qe,this._decoder.init(i=>this._drawImage(i)).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}_drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._removeStream(),o.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(T.browserName()==="Safari"&&T.browserVersion()>=15)}};var xt=1,ga=1,Tr=0,Cr=11,Ir=1,yr=2,Rr=4,br=8;function Pr(a,e,t,i,r,n,c){let p=0;e&&(p|=Ir),t&&(p|=yr),i&&(p|=Rr),c||(p|=br);let l=new ArrayBuffer(Cr),m=new DataView(l);if(m.setUint8(0,xt),m.setUint16(1,r),m.setUint32(3,a),m.setUint8(7,n?1:0),m.setUint16(8,Tr),m.setUint8(10,p),!c)return l;let y=new Uint8Array(l.byteLength+c.byteLength);return y.set(new Uint8Array(l),0),y.set(new Uint8Array(c),l.byteLength),y.buffer}function Mr(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,c=e.getUint16(8),p=e.getUint8(10),l=!!(p&Ir),m=!!(p&yr),y=!!(p&Rr),D=!!(p&br);if(t!==xt)throw new Error(`Unexpected protocol version. Got ${t}, expected ${xt}`);return{timestamp:r,start:l,end:m,keyframe:y,sequence:i,isVP9:n,ssrc:c,eos:D,data:a.slice(Cr)}}function Ar(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==xt||e.getUint8(1)!==ga||e.getUint16(2)!==Tr)}import*as g from"simple-ebml-builder";var _a=wi(2,15)-1,_i=1,fa=5,Sa=5;var Lt=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),o.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=Lt._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return g.build(e[0])}else return new Uint8Array;let t=e.reduce((n,c)=>n+c.countSize(),0),i=new Uint8Array(t),r=0;for(let n of e){let c=g.build(n);i.set(c,r),r+=c.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var n;let e=(n=this._sourceBuffer)==null?void 0:n.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-fa);r-i>Sa&&(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}},Pe=class extends Ke{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;o.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return g.element(g.ID.EBML,[g.element(g.ID.EBMLVersion,g.number(1)),g.element(g.ID.EBMLReadVersion,g.number(1)),g.element(g.ID.EBMLMaxIDLength,g.number(4)),g.element(g.ID.EBMLMaxSizeLength,g.number(8)),g.element(g.ID.DocType,g.string("webm")),g.element(g.ID.DocTypeVersion,g.number(2)),g.element(g.ID.DocTypeReadVersion,g.number(2))])}static _genSegmentHeader(e,t,i){let r=g.element(g.ID.Info,[g.element(g.ID.TimecodeScale,g.number(1e6)),g.element(g.ID.MuxingApp,g.string("vk-webm-builder")),g.element(g.ID.WritingApp,g.string("vk-webm-builder"))]),n=[g.element(g.ID.PixelWidth,g.number(e)),g.element(g.ID.PixelHeight,g.number(t))],c=g.element(g.ID.Tracks,g.element(g.ID.TrackEntry,[g.element(g.ID.TrackNumber,g.number(_i)),g.element(g.ID.TrackUID,g.number(_i)),g.element(g.ID.TrackType,g.number(1)),g.element(g.ID.FlagLacing,g.number(0)),g.element(g.ID.DefaultDuration,g.number(1e9)),g.element(g.ID.CodecID,g.string(`V_${i.toUpperCase()}`)),g.element(g.ID.Video,n)]));return g.unknownSizeElement(g.ID.Segment,[r,c])}static _genClusterHeader(e){return g.unknownSizeElement(g.ID.Cluster,[g.element(g.ID.Timecode,g.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new Lt(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){o.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=()=>o.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,o.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,o.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let c=Pe._genWebmHeader();this._mediaBuffer.append(c);let p=Pe._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(p),this._mediaBuffer.cleanup()}let r=Math.round(i-this._clusterStartTime);if(r>_a&&(this._clusterStartTime=i,r=0),r===0){o.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let c=Pe._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(c)}let n=g.element(g.ID.SimpleBlock,[g.vintEncodedNumber(_i),g.bytes(Pe._intToU16BE(r)),g.number((e.keyframe?1:0)<<7),g.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),o.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 et=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};o.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=n=>this._onDataChannelMessage(n.data)}_onDataChannelMessage(e){var n,c;let t=Mr(e),i=(c=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:c.participantId;if(!i){o.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];if(!r){let p=l=>this._onStream(i,l);d.screenShareWebmBuilder&&Pe.isBrowserSupported()?r=new Pe(i,p):r=new St(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,o.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(Ge.isBrowserSupported()||Qe.isBrowserSupported())&&(St.isBrowserSupported()||Pe.isBrowserSupported())}};import Dr from"@vkontakte/libvpx";var va=1e3,vt=class extends De{constructor(e,t){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return s(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=p=>t(),r.onerror=()=>i(new Error("Video element error"));let n=r.play(),c=()=>i(new Error("Autoplay is disabled"));n?n.catch(c):c()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return s(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return s(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;o.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var u=Object.defineProperty;var b=o=>u(o,"__esModule",{value:!0});var 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})},[
|
|
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(he.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),o.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var Ea=16*1024,Ta=11,Or=Ea-Ta,Ca=65536,fi=0,it=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;o.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,n)=>{if(!this._destroyed){if(!r){o.warn("requestFrame failed, keyFrame: "+this._needKeyframe,n),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(c=>{o.warn("sendFrame failed",c),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};tt.isBrowserSupported()?this._encoder=new tt(e,i):this._encoder=new vt(e,i),this._datachannel.onmessage=r=>{Ar(r.data)&&(o.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>o.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,n){let c=Pr(e,t,i,r,fi,this._encoder.isVP9(),n);return fi=(fi+1)%Ca,c}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return s(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let n=e.data.slice(t,t+Or),c=e.data.byteLength<=t+n.byteLength,p=this._wrapHeader(e.timestamp,!t,c,e.type==="key",n);this._datachannel.onbufferedamountlow=c?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(p)}catch(l){o.warn("Error send data to DataChannel",l),r();return}c||window.setTimeout(()=>this._sendChunk(e,t+Or,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),o.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return tt.isBrowserSupported()||vt.isBrowserSupported()}};var Z=class{static get sessionKey(){return Z._sessionKey}static set sessionKey(e){Z._sessionKey=e}static get sessionSecretKey(){return Z._sessionSecretKey}static set sessionSecretKey(e){Z._sessionSecretKey=e}static get accessToken(){return Z._accessToken}static set accessToken(e){Z._accessToken=e}static isEmpty(){return!Z._sessionKey||!Z._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")&&(Z.accessToken=e.apiAuth.accessToken,Z.sessionKey=e.apiAuth.sessionKey,Z.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.4.4-dev.c28b095.0"}static get debug(){return!1}static get protocolVersion(){return 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 apiAppId(){return 42}static get apiKey(){return f._params.apiKey}static get apiEnv(){switch(f._params.apiEnv){case"TEST":return{api:"https://apitest.ok.ru/api/",connect:"https://test.ok.ru/"};case"VIDEOTEST":return{api:"https://videotestapi.ok.ru/api/",connect:"https://test.ok.ru/"};case"DEV":return{api:"https://1.api.an-eremeev.devdc.odkl.ru/api/",connect:"https://1.web.an-eremeev.devdc.odkl.ru/"};default:return{api:"https://api.ok.ru/",connect:"https://connect.ok.ru/"}}}static get authToken(){return 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 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 producerNotificationDataChannel(){return f._params.producerNotificationDataChannel&&et.isBrowserSupported()}static get producerCommandDataChannel(){return f._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return f._params.consumerScreenDataChannel&&it.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 videoTracksCount(){return f.producerNotificationDataChannel?f._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return f._params.breakVideoPayloadTypes}static get filteredMessages(){return f._params.filteredMessages}static get batchParticipantsOnStart(){return f._params.batchParticipantsOnStart}static get participantStateMapped(){return f._params.participantStateMapped}},d=f;d._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"PROD",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!1,producerScreenTrack:!1,videoTracksCount:0,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!1};var $=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))($||{});function B(a,...e){let t=d.get(a);t&&setTimeout(t,0,...e)}function Oe(a){return Object.assign({},a)}function rt(a){return a.slice()}var Si;(oe=>{function a(E,x){B("onLocalStream",E,Oe(x))}oe.onLocalStream=a;function e(E,x){B("onScreenStream",E,Oe(x))}oe.onScreenStream=e;function t(E,x){B("onLocalStreamUpdate",Oe(E),x)}oe.onLocalStreamUpdate=t;function i(E){B("onLocalStatus",E)}oe.onLocalStatus=i;function r(E,x){B("onRemoteStream",E,x)}oe.onRemoteStream=r;function n(E,x,ne){B("onRemoteLive",E,x,ne)}oe.onRemoteLive=n;function c(E,x){B("onRemoteScreenStream",E,x)}oe.onRemoteScreenStream=c;function p(E,x,ne,ct){B("onConversation",E,Oe(x),Oe(ne),ct)}oe.onConversation=p;function l(E,x){B("onRemoteMediaSettings",E,Oe(x))}oe.onRemoteMediaSettings=l;function m(E,x){B("onRemoteParticipantState",E,Oe(x))}oe.onRemoteParticipantState=m;function y(E,x,ne=null){B("onRemoteStatus",E,x,ne)}oe.onRemoteStatus=y;function D(E,x,ne=null){B("onParticipantStatus",E,x,ne)}oe.onParticipantStatus=D;function j(){B("onPermissionsRequested")}oe.onPermissionsRequested=j;function te(E){B("onPermissionsError",E)}oe.onPermissionsError=te;function F(E){B("onRemoteRemoved",E)}oe.onRemoteRemoved=F;function ue(E,x,ne){B("onCallState",E,x,Oe(ne))}oe.onCallState=ue;function Me(E,x){B("onDeviceSwitched",E,x)}oe.onDeviceSwitched=Me;function de(E,x,ne,ct=!1,$t=!1,qt=null,Yr=null){B("onMuteStates",Oe(E),rt(x),rt(ne),ct,$t,qt,Yr)}oe.onMuteStates=de;function Ye(E,x){B("onRolesChanged",E,rt(x))}oe.onRolesChanged=Ye;function H(E){B("onLocalRolesChanged",rt(E))}oe.onLocalRolesChanged=H;function ye(E,x){B("onPinnedParticipant",E,x)}oe.onPinnedParticipant=ye;function Re(E){B("onLocalPin",E)}oe.onLocalPin=Re;function ot(E){B("onOptionsChanged",rt(E))}oe.onOptionsChanged=ot;function Di(){B("onCallAccepted")}oe.onCallAccepted=Di;function Oi(){B("onRateNeeded")}oe.onRateNeeded=Oi;function v(E){B("onSpeakerChanged",E)}oe.onSpeakerChanged=v;function C(E){B("onVolumesDetected",rt(E))}oe.onVolumesDetected=C;function b(E,x){B("onLocalVolume",E,x)}oe.onLocalVolume=b;function I(E,x){B("onJoinStatus",E,x)}oe.onJoinStatus=I;function A(E,x){B("onHangup",E,x)}oe.onHangup=A;function Te(E){B("onMultipartyChatCreated",Oe(E))}oe.onMultipartyChatCreated=Te;function Y(){B("onDeviceChange")}oe.onDeviceChange=Y;function N(E){B("onFingerprintChange",E)}oe.onFingerprintChange=N;function z(){B("onTokenExpired")}oe.onTokenExpired=z;function P(E,x,ne=!1){B("onChatMessage",E,x,ne)}oe.onChatMessage=P;function K(E,x,ne=!1){B("onCustomData",E,x,ne)}oe.onCustomData=K;function se(E,x,ne,ct,$t,qt){B("onRecordStarted",E,x,ne,ct,$t,qt)}oe.onRecordStarted=se;function M(){B("onRecordStopped")}oe.onRecordStopped=M;function Ne(E){B("onLocalNetworkStatusChanged",E)}oe.onLocalNetworkStatusChanged=Ne;function q(E){B("onNetworkStatusChanged",E)}oe.onNetworkStatusChanged=q;function Ae(E,...x){B("onDebugMessage",E,...x)}oe.onDebugMessage=Ae;function pe(E,x){let ne=Object.assign({},E,{memory:x});B("onStatistics",ne)}oe.onStatistics=pe;function ae(){B("onAutoplayError")}oe.onAutoplayError=ae;function Q(E,x,ne){B("onChatRoomUpdated",E,x,ne)}oe.onChatRoomUpdated=Q})(Si||(Si={}));var _=Si;var kr=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(kr||{}),vi;(H=>{let a="📞",e=(ye,...Re)=>{_.onDebugMessage(ye,...Re)},t=!1,i=(ye,Re)=>(...ot)=>{ye(...ot),pr(Re,ot)},r=console.debug.bind(console,a),n=console.log.bind(console,a),c=console.warn.bind(console,a),p=console.error.bind(console,a),l=e.bind(null,"DEBUG"),m=e.bind(null,"LOG"),y=e.bind(null,"WARN"),D=e.bind(null,"ERROR");H.debug=l,H.log=m,H.warn=y,H.error=D;function Me(){return t}H.enabled=Me;function de(ye){t=ye,d.debugLog&&ei(),ye?(H.debug=d.debugLog?i(r,"DEBUG"):r,H.log=d.debugLog?i(n,"LOG"):n,H.warn=d.debugLog?i(c,"WARN"):c,H.error=d.debugLog?i(p,"ERROR"):p):(H.debug=d.debugLog?i(l,"DEBUG"):l,H.log=d.debugLog?i(m,"LOG"):m,H.warn=d.debugLog?i(y,"WARN"):y,H.error=d.debugLog?i(D,"ERROR"):D)}H.toggle=de;function Ye(ye,...Re){switch(ye){case"DEBUG":H.debug(...Re);break;case"LOG":H.log(...Re);break;case"WARN":H.warn(...Re);break;case"ERROR":H.error(...Re);break}}H.send=Ye})(vi||(vi={}));var o=vi;var at=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(at||{}),ee;(p=>{function a(l){return l.length?typeof l[0]=="object"?l:l.map(m=>e(m)):[]}p.fromIds=a;function e(l,m="USER"){return{id:l,type:m}}p.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}p.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}p.toString=i;function r(l,m="USER"){return i(e(l,m))}p.fromIdToString=r;function n(l){try{return JSON.parse(l)}catch(m){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}p.fromString=n;function c(l,m){return l.id===m.id&&l.type===m.type}p.compare=c})(ee||(ee={}));var ve=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(ve||{}),Ei=":",wr="s",Nr="m";function $e(a){return a.participantId+(a.mediaType?Ei+wr+a.mediaType:"")+(a.streamName?Ei+Nr+a.streamName:"")}function Et(a){let e=a.split(Ei),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i={participantId:t,mediaType:null};for(let r of e)switch(r.charAt(0)){case wr:i.mediaType=Ia(r.slice(1));break;case Nr:i.streamName=r.slice(1);break;default:throw new Error("Unexpected parameter type "+r.charAt(0)+" in stream description "+a)}return i}function Ia(a){for(let e of Object.keys(ve))if(e===a)return ve[e];return null}function Ti(a,e){return a===null||e===null?a===null&&e===null:!(a.maxDimension!==e.maxDimension||a.maxBitrateK!==e.maxBitrateK||a.maxFramerate!==e.maxFramerate||a.degradationPreference!==e.degradationPreference)}function Ut(a,e){return!(!Ti(a.camera,e.camera)||!Ti(a.screenSharing,e.screenSharing))}function Ci(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function xr(a){return{camera:Object.assign({},a.camera),screenSharing:Object.assign({},a.screenSharing)}}function Lr(a){try{return btoa(JSON.stringify(a))}catch(e){o.warn("WaitingParticipant: failed convert to string",a,e)}return null}function Ur(a){try{return JSON.parse(atob(a))}catch(e){o.warn("WaitingParticipant: failed convert from string",a,e)}return null}var Tt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,u.log(h.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,u.log(h.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(o.log("Failed to fix RV"),u.log(h.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),u.log(h.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,o.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===le.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Bt=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var c;if(!((c=this._output)==null?void 0:c.audioTrack))return;let e=T.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{o.warn("Error on play audio"),_.onAutoplayError()},r=p=>{t.srcObject=new MediaStream([p]),t.load();let l=t.play();l?l.catch(i):i()},n=()=>{var l;o.debug("Recover audio playback");let p=(l=this._output)==null?void 0:l.audioTrack;p?r(p):o.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 s(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=T.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw u.log(h.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var ya=90,Ra=3,Vt=class extends J{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),_.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>ya?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Ra)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var ba=44100,Ct=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=T.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=ba/this._fftBins.length,t=Math.ceil(d.voiceParams.minFreq/e),i=Math.floor(d.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((n,c)=>n+c,0)/e.length/255,r=this._lastSmoothedLevel*d.voiceParams.smoothing+i*(1-d.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var Ft=class extends J{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&_.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,d.voiceParams.interval)};this._interval=window.setTimeout(t,d.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,fe.SOURCE_CHANGED,r=>{r.kind===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 Ct("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var Pa=1e3;function ke(a,e,t=0){return e in a&&a[e]?a[e]:t}function Br(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function Fe(a,e){return t=>t[a]===e}function Ma(a){return(e,t)=>e[a]-t[a]}function Ht(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function Aa(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Da(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Ii(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=Da(t[1])?Ii(t[1]):t[1],e),{})}function Oa(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function ka(a){return s(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...a.getReceivers().map(t=>t.getStats())),e.push(...a.getSenders().map(t=>t.getStats()))):e.push(a.getStats()),Promise.all(e).then(Oa).then(Aa)})}function wa(a){let e=a.filter(Fe("type","candidate-pair")).sort(Ma("priority")).find(Br(Fe("nominated",!0),Fe("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=a.find(Fe("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=a.find(Fe("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),Ii(t)}function Na(a,e){let t=Ht("id",a),i=a.filter(Br(Fe("type","inbound-rtp"),Fe("type","outbound-rtp")));T.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,c)=>{if(!n[c.ssrc])n[c.ssrc]=c;else{let p=Object.assign({},n[c.ssrc],c),l=n[c.ssrc].isRemote?c:n[c.ssrc];p.id=l.id,p.type=l.type,delete p.isRemote,delete p.remoteId,n[p.ssrc]=p}return n},{})));let r={};if(T.browserName()==="Safari"){let n=a.filter(Fe("type","track"));r=Ht("trackIdentifier",n)}return i.map(n=>{let c=Number(n.ssrc),p=n.mediaType||n.kind,l=n.trackId,m=n.type,y=n.codecId;if(T.browserName()==="Safari"){let j=/^.+_([\d]+)$/.exec(n.id);if(j&&(c=parseInt(j[1],10)),p=n.id.indexOf("Audio")>0?"audio":"video",e[c]){let te=p+"-"+e[c];r[te]&&(l=r[te].id)}}if(!m||!c||!p)return null;let D={ssrc:c,type:m,kind:p,bytesReceived:ke(n,"bytesReceived"),bytesSent:ke(n,"bytesSent"),jitter:ke(n,"jitter"),packetsLost:ke(n,"packetsLost"),packetsReceived:ke(n,"packetsReceived"),packetsSent:ke(n,"packetsSent"),fractionLost:ke(n,"fractionLost"),pliCount:ke(n,"pliCount"),firCount:ke(n,"firCount"),nackCount:ke(n,"nackCount"),userId:e[c]};if(y&&t[y]){let j=t[y];D.clockRate=j.clockRate,D.mimeType=j.mimeType}if(l&&t[l]){let j=t[l];D.frameHeight=j.frameHeight,D.frameWidth=j.frameWidth,D.framesDecoded=j.framesDecoded,D.framesReceived=j.framesReceived,D.framesDropped=j.framesDropped}return Ii(D)}).filter(n=>!!n)}function xa(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=Ht("ssrc",a.rtps),i=Ht("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let c=t[n],p=i[n];if(!(!c||!p)){if(c.bytesReceived&&c.bytesReceived>p.bytesReceived&&(c.bandwidth=Math.round((c.bytesReceived-p.bytesReceived)/r)),c.bytesSent&&c.bytesSent>p.bytesSent&&(c.bandwidth=Math.round((c.bytesSent-p.bytesSent)/r)),c.packetsReceived)if(c.packetsReceived>p.packetsReceived||c.packetsLost>p.packetsLost){let l=c.packetsLost-p.packetsLost,m=c.packetsReceived-p.packetsReceived;c.packetLoss=parseFloat((100*l/(l+m)).toFixed(2))}else c.packetLoss=0;c.framesDropped&&p.framesDropped&&c.framesDropped>p.framesDropped&&(c.framesDroppedDelta=parseFloat(((c.framesDropped-p.framesDropped)/r).toFixed(0)))}}),a}function It(i,r){return s(this,arguments,function*(a,e,t={}){let n=yield ka(a),c={timestamp:Date.now(),transport:wa(n),rtps:Na(n,t)};return e?xa(c,e):(yield S.delay(Pa),It(a,c,t))})}var Gt=.8,qe=class extends J{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=U.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=n,this.subscribe(this._signaling,me.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,fe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,fe.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:d.iceServers,iceTransportPolicy:d.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(c){u.log(h.ERROR,"addTrack-direct"),o.error("Unable to add media source tracks",c,{participantId:this._participantId}),this._failedOnCreate=c;return}this._createOffer(!1).catch(c=>{this._state===U.IDLE?this._failedOnCreate=c:this.close(c)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==U.IDLE&&e!==U.CLOSED&&e!==U.FAILED&&this._startStatInterval()}open(e=null){return s(this,null,function*(){if(this._isOpen){o.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(o.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(i){u.log(h.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(U.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(L.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Ut(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(L.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(o.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(U.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(U.CLOSED)),this._triggerEvent(L.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(L.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case 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=S.getPeerIdString(e.peerId);S.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return s(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){o.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw u.log(h.ERROR,"addIceCandidate-direct"),o.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else o.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return s(this,null,function*(){if(!this._remoteCandidates[e]){o.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return s(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){o.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw u.log(h.ERROR,"setRemoteDescription-direct"),o.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){o.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(L.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(L.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return s(this,null,function*(){e.candidate&&this._signaling.ready&&(o.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(o.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>s(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(o.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===U.IDLE||e===U.OPENED?this._setState(U.CONNECTING):this._setState(U.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),u.log(h.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(U.CONNECTED),this._stopReconnection(),S.getPeerConnectionHostInfo(this._pc).then(e=>{e&&u.log(h.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(U.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(o.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},d.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(o.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(Ee.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(u.log(h.ICE_RESTART),o.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):o.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,o.error("Ice restart failed",{participantId:this._participantId}),u.log(h.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return s(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return o.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw o.error("Unable to create offer",i,{participantId:this._participantId}),u.log(h.ERROR,"createOffer-direct"),i}).then(i=>s(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=qe._patchDescription(i),o.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw o.error("Unable to set local description",i,{participantId:this._participantId}),u.log(h.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return s(this,null,function*(){return o.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw o.error("Unable to create answer",e,{participantId:this._participantId}),u.log(h.ERROR,"createAnswer-direct"),e}).then(e=>s(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=qe._patchDescription(e),o.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw o.error("Unable to set local description",e,{participantId:this._participantId}),u.log(h.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!T.baseChromeVersion();return e.sdp=S.patchSDP(e.sdp,d.preferH264&&T.canPreferH264(),T.isBrokenH264(),d.preferVP9,t&&d.audioNack),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{o.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),u.log(h.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}It(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:Ee.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:Ee.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(L.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,d.statisticsInterval)})};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=de=>de.rtt<=this._networkLimits.goodNet.rtt&&de.loss<=this._networkLimits.goodNet.loss,i=de=>de.rtt>=this._networkLimits.badNet.rtt||de.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((de,Ye)=>Math.max(de,Ye.packetLoss||0),0),c={rtt:this._lastNetworkStat.rtt*(1-Gt)+r*Gt,loss:this._lastNetworkStat.loss*(1-Gt)+n*Gt},p=i(c),l=t(c),m=i(this._remoteNetworkStat),y=t(this._remoteNetworkStat),D=i(this._lastNetworkStat),j=t(this._lastNetworkStat),ue=p||m?.2:l&&y?1:0,Me=Date.now();if((D!==p||j!==l||Me-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},c)},null).catch(de=>{o.warn("Unable to send [bad-net]",de)})),ue){let de={};de[this._participantId]=de[""]=ue,this._triggerEvent(L.NETWORK_STATUS,de)}this._lastNetworkStat.rtt=c.rtt,this._lastNetworkStat.loss=c.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=S.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(_.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=S.applySettings(this._pc,e,this._prevConsumerSettings))}};var Vr=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Vr||{}),yt=Vr;import{decode as nt}from"messagepack";var yi=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var n,c;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let p=nt(r);return Object.entries(p).forEach(([F,ue])=>{let Me=Et(F);this.streamDescriptionByCompactId.set(ue,Me)}),null;case 2:case 4:let l=nt(r),m=[];for(let F of l){let ue=this.getStreamDescription(F);ue&&m.push(ue.participantId)}return i===2?{type:"notification",notification:O.AUDIO_ACTIVITY,activeParticipants:m}:{type:"notification",notification:O.STALLED_ACTIVITY,stalledParticipants:m};case 3:let y=nt(r);return{type:"notification",notification:O.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(y))==null?void 0:n.participantId};case 5:let D=nt(r);return{type:"notification",notification:O.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:D[0],maxDimension:D[1]}};case 6:let j=nt(r),te={};for(let[F,ue]of Object.entries(j)){let Me=(c=this.getStreamDescription(Number(F)))==null?void 0:c.participantId;Me&&(te[Me]=ue/100)}return{type:"notification",notification:O.NETWORK_STATUS,statuses:te};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return o.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=nt(e),i=[];for(let[r,n]of Object.entries(t)){let c=n[0],p=n[1],l=n[2],m;if(c!==null){if(m=this.getStreamDescription(c),!m){o.error(`could not uncompress participant ID ${c}`);continue}}else m=null;if(l===null){o.error("unexpected null sequenceNumber",r,n);continue}let y=be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,D=p?p>>>0:null;i.push({participantStreamDescription:m,streamId:y,rtpTimestamp:D,sequenceNumber:l})}return{type:"notification",notification:O.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Fr="videochat-epi",Rt=class extends J{constructor(e,t){super();this._previousTimestamp=0;this._signaling=t,this.subscribe(e,L.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Fr)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return s(this,null,function*(){if(!d.perfStatReportEnabled||!e.inbound||!e.inbound.rtps)return;let t=e.inbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.framesDecoded+=n.framesDecoded||0,r.framesReceived+=n.framesReceived||0),r),{framesDecoded:0,framesReceived:0}),i=Date.now();if(!(this._previousTimestamp+5e3>i)){if(t.framesDecoded)try{let r=yield this._signaling.reportPerfStat(t);localStorage.setItem(Fr,r.estimatedPerformanceIndex)}catch(r){}this._previousTimestamp=i}})}};var La=90,Ua=4294967295,Ce=class extends J{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._reconnectionPrevented=!1;this._state=U.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,me.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,fe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,fe.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,fe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Rt(this,e),this._serverSettings=i,o.debug("ServerTransport: Created")}getState(){return this._state||U.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==U.IDLE&&e!==U.CLOSED&&e!==U.FAILED&&this._startStatInterval()}open(){if(this._isOpen){o.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(o.error("ServerTransport: Closed",e),this._setState(U.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(U.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Ut(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,Ce._closeDataChannel(this._producerNotification),Ce._closeDataChannel(this._producerCommand),Ce._closeDataChannel(this._producerScreen),Ce._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(L.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){o.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{o.debug(`[${t}] data channel opened`),r.onerror=n=>{o.error(`[${t}] data channel error`,n)},i(r)}}_openConnection(e=!1){o.debug("ServerTransport: Open single connection");let t={};T.baseChromeVersion()&&(t.sdpSemantics=Ce._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=S.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Ce._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,yt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new yi,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,yt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,yt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){o.error("ServerTransport: Unable to add media source tracks",i),u.log(h.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,yt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(U.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==U.OPENED&&(this._setState(U.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(L.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(L.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(L.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(L.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
|
|
12
|
-
`).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${be.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 it(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 et(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(L.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(L.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!d.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==le.video)return;let r=!this._disabledSenders.has(i),n=e.maxDimension!==0;if(r&&!n){o.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(T.getBlackMediaTrack()).catch(p=>{o.error("Could not disable video upload",p)});return}let c=this._mediaSource.getSendVideoTrack();if(!r&&n&&c){o.log("Enabling video upload"),this._disabledSenders.delete(i);let p=i.track;p.enabled=c.enabled,i.replaceTrack(c).then(()=>p.stop()).catch(l=>{o.error("Could not enable video upload",l)})}S.applyVideoTrackSettings(e,i,c!=null?c:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(L.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,d.statisticsInterval)};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return s(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield It(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(L.REMOTE_DATA_STATS,{inbound:{topology:Ee.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:Ee.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(c=>c.type==="inbound-rtp"&&c.kind==="audio"&&this._ssrcMap[c.ssrc]==="mix");if(!t)return;let i=be.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let c=t.bytesReceived-r.bytesReceived;c>=0&&c<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(L.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Rt.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:Ce._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return s(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,o.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(o.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw o.error("[single] unable to set remote offer",i),u.log(h.ERROR,"setRemoteDescription-single"),i}).then(()=>s(this,null,function*(){if(o.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw o.error("[single] unable to create answer",i),u.log(h.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=S.patchSDP(i.sdp,!1,T.isBrokenH264(),!1),i)).then(i=>s(this,null,function*(){if(o.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw o.error("[single] unable to set local answer",i),u.log(h.ERROR,"setLocalDescription-single"),i}).then(i=>s(this,null,function*(){o.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),o.debug("[single] remote offer has been processed")})).catch(i=>{o.warn("[single] unable to send local answer",i),u.log(h.ERROR,"acceptProducer")}).then(()=>s(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){o.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return s(this,null,function*(){if(!!this._isOpen)switch(e.notification){case 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 s(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),d.breakVideoPayloadTypes&&(o.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){o.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent(L.REMOTE_TRACK_REMOVED,i.id,i,n.track)}),i.getTracks().find(n=>n.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(L.REMOTE_TRACK_ADDED,i.id,i,t.track)):o.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){o.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(o.debug("[single] connection state changed",{state:e.connectionState},t),u.log(h.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===U.IDLE||i===U.OPENED?this._setState(U.CONNECTING):e.iceConnectionState==="checking"&&this._setState(U.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(U.RECONNECTING);break;case"connected":this._setState(U.CONNECTED),S.getPeerConnectionHostInfo(e).then(r=>{r&&u.log(h.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(d.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{o.error("ServerTransport: Unable to replace track",r),u.log(h.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=T.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(T.browserName(),T.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return u.log(h.PAT_WAITING_TIME_ERROR,"noConnection"),o.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return u.log(h.PAT_WAITING_TIME_ERROR,"noReceiver"),o.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return o.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let c=r[0].rtpTimestamp;if(!Number.isInteger(c))return u.log(h.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),o.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${c}`),0;let p=t-c&Ua,l=Math.ceil(p/La);return Math.min(100,Math.max(0,l))}};var L=(F=>(F.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",F.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",F.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",F.REMOTE_ALL_STALL="REMOTE_ALL_STALL",F.REMOTE_DATA_STATS="REMOTE_DATA_STATS",F.STATE_CHANGED="STATE_CHANGED",F.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",F.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",F.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",F.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",F.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",F.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",F.NETWORK_STATUS="NETWORK_STATUS",F.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",F))(L||{}),U=(p=>(p.IDLE="IDLE",p.OPENED="OPENED",p.CONNECTING="CONNECTING",p.RECONNECTING="RECONNECTING",p.CONNECTED="CONNECTED",p.CLOSED="CLOSED",p.FAILED="FAILED",p))(U||{}),Ee=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(Ee||{}),Ri=class extends J{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,me.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){o.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){o.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){o.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),o.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&o.warn(`The participant [${e}] transport has already deallocated`),this._topology==="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(o.log(`Topology changed ${this._topology} -> ${e.topology}`),u.log(h.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],n=i.length&&r.length?S.composeId(i[0],r[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){o.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&o.warn("Topology changed to DIRECT, but the allocated participants count more then one");let c=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let p=n===c;this._directTransport=this._createDirectTransport(c,p)}this._opened.indexOf(c)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new qe(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),this._dtListeners&&this._dtListeners.length>0&&o.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("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 Ce(this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!1),this._stListeners&&this._stListeners.length>0&&o.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("ACTIVE_PARTICIPANTS_NO_SIGNAL",this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;d.noiseSuppression!==e&&(d.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent("ACTIVE_PARTICIPANTS_NO_SIGNAL")}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(u.log(h.PAT_WAITING_TIME_ERROR,"wrongTopology"),o.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(u.log(h.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Je=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(Je||{}),bi=class extends J{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,L.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,L.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,L.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,L.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===le.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Ct(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,d.voiceParams.interval)};this._interval=window.setTimeout(n,d.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===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===be.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var Pi=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(Pi||{}),Mi=class extends J{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,Je.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,L.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,L.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,L.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>d.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*d.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent("SPEAKER_CHANGED",e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var Wt=class extends J{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,L.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,Je.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===U.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),d.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),d.specListenerParams.volumeTimeout))),t===U.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),u.log(h.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==U.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),u.log(h.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),u.log(h.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Ba=1e3,Va=1e4;var V=class extends J{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=W.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._signalingServerSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;u.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),u.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new Bt,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Ba))}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="",n=!1,c=!1){return s(this,null,function*(){if(V._activationMutex)throw u.log(h.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new k(R.FAILED);V._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let p=this._mediaSource.getMediaSettings();t===xe.CHAT||e.length>1?this._logWithMediaSettings(h.OUTGOING_MULTIPARTY_CALL,p):this._logWithMediaSettings(h.OUTGOING_CALL,p);let l=yield this._startConversation(e,t,Ue.OUTGOING,i,r,n,c);if(!this._conversation)throw new k(R.UNKNOWN_ERROR);if(this._participantState=W.ACCEPTED,this._signaling.changeMediaSettings(p),yield this._registerParticipants(l.conversation.participants),this._processConnectionData(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),V._delayedHangup)throw new k(R.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let m=Object.values(this._participants),y;return d.batchParticipantsOnStart&&(y=S.mapSharedParticipants(m)),_.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),_.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,y),_.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),V._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(m,$.WAITING),this._conversation}catch(p){throw this._close(p,"Unable to start conversation"),p}finally{V._activationMutex=!1}})}onJoin(e){return s(this,null,function*(){if(V._activationMutex)throw u.log(h.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new k(R.FAILED);V._activationMutex=!0,this._state="PROCESSING";try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(h.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new k(R.UNKNOWN_ERROR);return _.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(o.log("In waiting hall"),V._current=this,V._activationMutex=!1,this._signaling.readyToSend(),_.onLocalStatus($.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw V._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return s(this,null,function*(){o.debug("Join conversation part 2"),V._activationMutex=!0;try{if(this._participantState=W.ACCEPTED,!this._conversation||!this._mediaSource)throw new k(R.UNKNOWN_ERROR);if(this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),V._delayedHangup)throw new k(R.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=S.mapSharedParticipants(t)),_.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),_.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),V._current=this,d.batchParticipantsOnStart||this._setParticipantsStatus(t,$.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 s(this,arguments,function*(e,t=X.USER,i){if(V._activationMutex)throw o.warn("Conversation: there is already running activation"),new k(R.REJECTED);V._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new k(R.UNKNOWN_ERROR);if(!n.conversation.participants.find(p=>{var l;return p.state===W.CALLED&&p.id===((l=this._conversation)==null?void 0:l.userId)}))throw o.log("Push rejected (there is an active call)"),u.log(h.PUSH,"rejected"),new k(R.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),u.log(h.PUSH,"accepted"),V._current=this,V._delayedHangup)throw new k(R.CANCELED);V._activationMutex=!1}catch(n){throw V._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Yt.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>S.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return s(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new k(R.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(h.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),_.onCallAccepted(),this._state="ACTIVE",this._participantState=W.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return s(this,null,function*(){if(this._state!=="IDLE")throw u.log(h.ERROR,"acceptIncoming"),o.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new k(R.UNKNOWN_ERROR);this._state="PROCESSING",o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(h.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=W.ACCEPTED;let i=Object.values(this._participants),r;d.batchParticipantsOnStart&&(r=S.mapSharedParticipants(i)),_.onCallAccepted(),_.onLocalStream(this._mediaSource.getStream(),t),_.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),_.onLocalStatus($.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(Be.MUTE)||n.includes(Be.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),d.batchParticipantsOnStart||this._setParticipantsStatus(i,$.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return s(this,null,function*(){var e;if(this._state!=="IDLE")throw u.log(h.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",o.debug("Decline incoming call"),this._logWithMediaSettings(h.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=W.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(R.REJECTED)),this._close(new k(R.REJECTED))})}hangup(){return s(this,null,function*(){o.debug("Hangup");let e=this._state==="ACTIVE"?R.HUNGUP:R.CANCELED;u.log(h.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new k(e))):_.onHangup(new k(R.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return s(this,null,function*(){if(!this._signaling.ready){this._close(new k(R.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=R.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(e,n,r)})}removeParticipant(e,t=!1){return s(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){if(!this._transport)return;let i=[];for(let r of e)(r.state===W.CALLED||r.state===W.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===W.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&o.error(t,e),o.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(R.FAILED):u.log(h.ERROR,e.hangup),V._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([R.CANCELED,R.NOT_FRIENDS,R.CALLEE_IS_OFFLINE,R.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===R.REJECTED&&!e.remote){_.onHangup(e,i),this.destroy();return}if(e.hangup===R.HUNGUP&&(!e.remote||this._participantState===W.CALLED)){_.onHangup(e,i),this.destroy();return}if(e.hangup===R.MISSED&&!e.remote){_.onHangup(e,i),this.destroy();return}if(e.hangup===R.SOCKET_CLOSED&&V._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===R.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=W.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),u.destroy(),this._conversation=null,V._current=null,V._delayedHangup=!1,_.onHangup(e||new k(R.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;o.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),u.destroy(),this._conversation=null,V._current=null,V._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return s(this,null,function*(){let t=yield this._api.getConversationParams(e);o.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let c=r.urls.filter((p,l,m)=>m.indexOf(p)===l);c.forEach(p=>c.push(`${p}?transport=tcp`)),i.push({urls:c,username:r.username,credential:r.credential})}d.iceServers=i,d.wssBase=t.endpoint,d.wssToken=t.token,t.client_type&&(d.clientType=t.client_type)})}_startConversation(e,t,i,r,n="",c=!1,p=!1){return s(this,null,function*(){let l=S.uuid();o.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let m=r.includes(ce.VIDEO),y=yield this._api.startConversation(l,e,t,m,n,c,p);o.debug("Api.startConversation",y),yield this._getConversationParams(y.id);let D=yield this._connectSignaling(Le.START,y);return yield this._setConversation(y,D,i),D})}_joinConversation(e){return s(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n}=e;o.debug("Conversation: join",{conversationId:t,joinLink:n});let c=i.includes(ce.VIDEO),p;if(t)p=yield this._api.joinConversation(t,c,r);else if(n)p=yield this._api.joinConversationByLink(n,c);else throw new k(R.UNKNOWN_ERROR);o.debug("Api.joinConversation",p),yield this._getConversationParams(p.id);let l=yield this._connectSignaling(Le.JOIN,p);return yield this._setConversation(p,l,Ue.JOINING),l})}_prepareConversation(r){return s(this,arguments,function*(e,t=X.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i}),yield this._getConversationParams(e);let n=this._api.getUserId();if(!n)throw new k(R.UNKNOWN_ERROR);let c={id:e,peerId:i,endpoint:`${d.wssBase}?userId=${n}&entityType=${t}&conversationId=${e}&token=${d.wssToken}`,is_concurrent:!1,p2p_forbidden:!1},p=yield this._connectSignaling(Le.ACCEPT,c);return V._current&&(V._current._participantState===W.ACCEPTED||V._current._participantState===W.CALLED)?(o.log("Push rejected (busy)"),u.log(h.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(R.BUSY),Promise.reject({hangup:R.BUSY})):(V._current&&(V._current.destroy(),V._current=null),yield this._setConversation(c,p,Ue.INCOMING,t),p)})}_createParticipant(e){return s(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:ge(),participantState:{},state:W.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);return e.externalId?this._api.cacheExternalId(t.id,e.externalId):t.externalId=yield this._getUserId(t.id),t})}_getUserId(e){return s(this,null,function*(){try{return yield this._api.userId(e)}catch(t){throw this._close(new k(R.NETWORK_ERROR),t),t}})}_setConversation(n,c,p){return s(this,arguments,function*(e,t,i,r=X.USER){let l=t.conversation.participants.map(j=>j.id);yield this._api.prepareUserIds(l);let m=this._api.getUserId();if(!m){let j=(t.conversation.participants||[]).find(te=>S.comparePeerId(te.peerId,t.peerId));if(!j)throw new k(R.UNKNOWN_ERROR);m=Number(j.id),j.idType&&(r=j.idType),this._api.setUserId(m)}let y=S.composeId(m,r),D=yield this._getUserId(y);this._conversation={userId:m,compositeUserId:y,externalId:D,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||Ee.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),u.log(h.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new k(R.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||Ee.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 ni;return this.subscribe(e,fe.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,fe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new Tt(e),e}_connectSignaling(e,t){return s(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,me.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,me.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,me.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return s(this,null,function*(){if(!!this._conversation)for(let t of e){let i=S.composeParticipantId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),_.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===W.HUNGUP||t.state===W.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],R.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&ee.fromSignaling(t.externalId),mediaSettings:ge(t.mediaSettings),participantState:S.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?$.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),_.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){S.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Jt.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Ri(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new Vt,this.subscribe(this._transport,L.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,L.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,L.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,L.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,L.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,L.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,L.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,L.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,L.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,L.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,L.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,L.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Ue.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===W.ACCEPTED||t.state===W.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new bi(this._transport),this.subscribe(this._volumesDetector,Je.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Mi(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,Pi.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Ft(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Wt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=T.getCameras().length,t=T.getMicrophones().length;o.debug("Cameras: "+e+(T.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(T.hasMicrophonePermission()?"✔":"✖")),u.log(h.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){u.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===W.CALLED||e.state===W.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===R.HUNGUP?this._setParticipantsStatus([e],$.HANGUP):this._setParticipantsStatus([e],$.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:ve.CAMERA,stopStream:!0}]),delete this._participants[e.id],_.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){o.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return s(this,null,function*(){o.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===W.ACCEPTED||r.state===W.CALLED)){o.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&ee.fromSignaling(t.externalId),mediaSettings:ge(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],$.WAITING),i?(r.state=W.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=W.CALLED,this._transport.allocate(r.id,!0),u.log(h.ADD_PARTICIPANT))})}_onRemoveParticipant(e){o.debug(`Remove participant [${e}]`);let t=this._participants[e];if(!t){o.warn(`Participant [${e}] isn't in conversation`);return}this._transport&&this._transport.close(t.id),u.log(h.REMOVE_PARTICIPANT)}changeDevice(e){return s(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new Tt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ie.UNKNOWN)})}toggleScreenCapturing(e){return s(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ie.UNKNOWN)})}setVideoStream(e,t=!1){return s(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return s(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return s(this,null,function*(){if(this._mediaSource)return u.log(h.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return s(this,null,function*(){if(this._mediaSource)return u.log(h.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return s(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let n=typeof r.uid=="object"?r.uid:ee.fromId(r.uid),c=ee.toString(n);i[c]=r.priority}for(let r of Object.values(this._participants)){let n=ee.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return s(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}updateDisplayLayout(e){return s(this,null,function*(){if(e.length<1||!this._signaling.ready)return;o.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:ee.fromId(r.uid),c=ee.toString(n),p=this._api.getCachedOkIdByExternalId(n);if(!p){o.log(`Unknown participant external ID ${c}`);continue}let l=$e({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){o.error("Cannot accommodate all streaming requests: tracks available "+d.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]=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)&&(o.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Et(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===ve.STREAM||i.mediaType===ve.SCREEN)?_.onRemoteLive(r.externalId,i.streamName,null):_.onRemoteStream(r.externalId,null),u.log(h.PAT_DEALLOCATED)):o.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return s(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,n]of Object.entries(t.errorCodeByParticipantId||{})){let c=Et(r),p=this._participants[c.participantId];if(p){let l;typeof n!="number"?(o.warn(`Unexpected error code ${n} received for participant ${c.participantId}`),l=tr.UNKNOWN_ERROR):l=ir(n),i.push({externalId:p.externalId,errorReason:l})}}if(i&&i.length)throw new jt("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]+Va>Date.now())break;let c=r[0];this._stopStreaming(c),e[c]=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),e.keyFrame&&(t!==""&&(t+=":"),t+="kf"),t}_onParticipantSourcesUpdate(e){if(this._conversation){o.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return s(this,null,function*(){o.log("Promoted in waiting hall",!e.demote),e.demote?(o.log("Kicked from waiting hall"),this._close(new k(R.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return s(this,arguments,function*(e,t=0,i=[]){o.log(`Chat room updated: ${e}`);let n=[],c=[];i.length&&(i.forEach(p=>{if(p.externalId){let l=ee.fromSignaling(p.externalId);n.push(l),this._api.cacheExternalId(p.id.id,l)}else c.push(S.decomposeId(p.id.id).id)}),c.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(c))),_.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var p,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===ve.SCREEN)return;let i=$e(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){o.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),u.log(h.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,c=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(c<=0){this._streamWaitTimerByStreamDescription.delete(i);let m=t.participantId,y=this._participants[m];if(!y){u.log(h.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${m}`);return}let D=this._streamByStreamId.get(n);if(!D){u.log(h.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}u.log(h.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let j=(p=e.participantStreamDescription)==null?void 0:p.mediaType;if(j===ve.STREAM||j===ve.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&_.onRemoteLive(y.externalId,e.participantStreamDescription.streamName,D);else{let te=(d.producerScreenTrack?null:y.secondStream)||D;_.onRemoteStream(y.externalId,te)}}else{o.debug(`Waiting for ${c} until stream ${n} for ${i} is switched`);let m=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),c);this._streamWaitTimerByStreamDescription.set(i,m)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has($e(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has($e(i)))return i}else{let i={participantId:t,mediaType:ve.CAMERA};if(this._streamIdByStreamDescription.has($e(i)))return i;let r={participantId:t,mediaType:ve.SCREEN};if(this._streamIdByStreamDescription.has($e(r)))return r}return o.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?S.includesOneOf(this._conversation.roles,[ze.ADMIN,ze.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!S.includesOneOf(this._conversation.roles,[ze.ADMIN,ze.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return s(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return s(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return s(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return s(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return s(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Wi(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return s(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Ur(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let c=n.participants||[],p=[],l=[],m=null;return c.length&&(c.forEach(y=>{if(y.externalId){let D=ee.fromSignaling(y.externalId);p.push(D),this._api.cacheExternalId(y.id.id,D)}else l.push(S.decomposeId(y.id.id).id)}),l.length&&!p.length&&(p=yield this._api.getExternalIdsByOkIds(l)),n.hasMore&&(m=Lr(c[c.length-1].id))),{participants:p,pageMarker:m,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return s(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return s(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return s(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return s(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return s(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return s(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return s(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return s(this,null,function*(){var p;let n={movieId:e,participantId:(p=this._conversation)==null?void 0:p.compositeUserId};(t||t===0)&&(n.gain=t),i&&(n.offset=i),typeof r!==void 0&&(n.pause=r);let c=yield this._signaling.updateMovie(n);if(c.error)throw new Error(c.error)})}removeMovie(e){return s(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",n=null){return s(this,null,function*(){let c={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},p=yield this._signaling.startStream(c);return p.error?Promise.reject(p.message):p})}stopStream(){return s(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return s(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return s(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return s(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 s(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return s(this,null,function*(){var t;!this._conversation||(o.debug("Local media stream changed",e.mediaSettings),_.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return s(this,null,function*(){var t;if(o.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;_.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){o.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&_.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){o.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&(d.participantStateMapped?_.onRemoteParticipantState(i.externalId,i.participantState):_.onRemoteParticipantState(i.externalId,S.mapLegacyParticipantState(i.participantState))))}_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 s(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let c=S.composeParticipantId(n),p=n.roles||[];if(c===this._conversation.compositeUserId){t=ge(n.mediaSettings),ut(this._conversation.roles,p)||this._onRolesChanged(c,p);continue}r.push(c);let l=this._participants[c];if(!l)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let m=ge(n.mediaSettings);ur(m,l.mediaSettings)||this._changeRemoteMediaSettings(c,m);let y=S.mapParticipantState(n),D=l.participantState;S.isEqualParticipantState(y,D)||this._changeRemoteParticipantState(c,y),ut(p,l.roles)||this._onRolesChanged(l.id,p)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],R.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){o.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return s(this,null,function*(){let t=S.composeMessageId(e),i=S.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new k(R.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:ge(e.mediaSettings)}),r=this._participants[t]),r.state=W.ACCEPTED,r.mediaSettings=ge(e.mediaSettings),this._logWithMediaSettings(h.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Ue.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){o.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=S.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new k(e.reason));return}let i=this._participants[t];if(!i){o.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===R.REJECTED?W.REJECTED:W.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,R.HUNGUP)}_onAddedParticipant(e){return s(this,null,function*(){var r,n;o.debug(`Participant added [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state!==W.HUNGUP&&i.state!==W.REJECTED){o.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&ee.fromSignaling(e.participant.externalId),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=W.CALLED,i.mediaSettings=ge((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=S.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],$.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onJoinedParticipant(e){return s(this,null,function*(){var r;o.debug(`Participant joined [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state===W.ACCEPTED){o.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&ee.fromSignaling(e.participant.externalId),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Ue.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=W.ACCEPTED,i.mediaSettings=ge(e.mediaSettings),i.participantState=S.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],$.CONNECTED):this._setParticipantsStatus([i],$.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id])),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new k(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=S.composeMessageId(e);this._changeRemoteMediaSettings(t,ge(e.mediaSettings))}_onParticipantStateChanged(e){let t=S.composeMessageId(e);this._changeRemoteParticipantState(t,S.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),_.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return s(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ge(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),d.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Ci(this._serverSettings,t),this._signalingServerSettings=xr(this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){let t=this._serverSettings.camera,i=this._signalingServerSettings.camera;if(!t||!i)return;let r=Math.min(Math.round(e.quality.maxBitrate/1024),i.maxBitrateK),n=Math.min(e.quality.maxDimension,i.maxDimension),c={camera:Object.assign({},t,{maxBitrateK:r,maxDimension:n}),screenSharing:null};this._serverSettings=Ci(this._serverSettings,c),o.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=S.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return s(this,null,function*(){_.onDeviceSwitched(ce.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return s(this,null,function*(){let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),_.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return s(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),_.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return s(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getUserId(e.initiator);_.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else _.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!ut(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,_.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!ut(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,_.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return s(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],c=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){o.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let p=this._participants[e.participantId];p&&(o.debug(`Mute states for participant [${e.participantId}] changed`,i),_.onMuteStates(i,r,n,e.muteAll,e.unmute,p.externalId,c==null?void 0:c.externalId));return}S.isObjectsEquals(this._conversation.muteStates,i)&&S.isArraysEquals(this._conversation.unmuteOptions,r)&&!n.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(n,e.muteAll,e.unmute,t,c)))})}_processMuteState(){return s(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==W.ACCEPTED)return;let c=Object.assign({},this._conversation.muteStates),p=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),m=Object.entries(c);for(let[y,D]of m)if(!(D!==Be.MUTE&&D!==Be.MUTE_PERMANENT)&&(this._isCallAdmin()&&D===Be.MUTE_PERMANENT&&(c[y]=Be.MUTE),!(!e.includes(y)||i)))switch(y){case ce.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(_.onDeviceSwitched(ce.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case ce.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(_.onDeviceSwitched(ce.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case ce.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(_.onDeviceSwitched(ce.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}_.onMuteStates(c,p,e,t,i,null,n==null?void 0:n.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?_.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&_.onLocalPin(!0)),this._participants[e]?_.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&_.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!Gi(this._conversation.options,e)&&(this._conversation.options=e,_.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let n;if(i===this._conversation.compositeUserId||i==="")n=this._conversation.networkRating;else if(this._participants[i])n=this._participants[i].networkRating;else continue;if(n!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,_.onLocalNetworkStatusChanged(r);else{let c=this._participants[i];c.networkRating=r,t.push({uid:c.externalId,rating:r})}}if(t.length===0)return;o.log("Received network status update: ",e),_.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){_.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,d.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){o.error("Received remote stream notification for a participant that has no track associated with it",r);return}let n=this._streamIdByStreamDescription.get(r);if(!n||this._streamWaitTimerByStreamDescription.has(r)){o.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let c=this._streamByStreamId.get(n);if(!c){u.log(h.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}_.onRemoteStream(i.externalId,i.secondStream||c)}else{let r=t||i.remoteStream;r&&_.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===Ee.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Fi.ADD_PARTICIPANT);_.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&_.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})}_.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(_.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return s(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===U.CONNECTED?i=$.CONNECTED:t===U.CONNECTING||t===U.OPENED?i=$.CONNECTING:t===U.RECONNECTING&&(i=$.RECONNECT),!i)return;let r=e.reduce((n,c)=>{if(c in this._participants){let p=this._participants[c];n.push(p),t===U.CONNECTED&&(p.remoteStream||(p.mediaSettings&&this._changeRemoteMediaSettings(c,p.mediaSettings),this._changeRemoteParticipantState(c,p.participantState)),this._updateDisplayLayoutFromCache(c))}else o.warn(`Participant [${c}] isn't in conversation`);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return s(this,null,function*(){o.debug(`Local transport state has changed: ${e}`),e===U.CONNECTED&&_.onLocalStatus($.CONNECTED),e===U.CONNECTING&&_.onLocalStatus($.CONNECTING),e===U.RECONNECTING&&_.onLocalStatus($.RECONNECT),e===U.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(R.FAILED)),this._close(new k(R.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return s(this,null,function*(){if(e.endsWith(be.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))o.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{o.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(o.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],$.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(_.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),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;_.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),d.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(o.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case 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!==be.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onRemoteActivityNoSignal(){this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)}_onTopologyChanged(e){this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let n=this._participants[r];e||this._lastStalled[r]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,$.RECONNECT),i.length&&this._setParticipantsStatus(i,$.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let c=this._participants[n];c&&!this._remoteAllStalled&&i.push(c)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let c=this._participants[n];c&&!this._remoteAllStalled&&r.push(c)}),i.length&&this._setParticipantsStatus(i,$.RECONNECT),r.length&&this._setParticipantsStatus(r,$.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!T.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),_.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return s(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==Ee.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,c)=>(c.status!==t&&(c.status=t,d.batchParticipantsOnStart?n.push(c.externalId):_.onParticipantStatus(c.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&_.onRemoteStatus(r,t,i)}},w=V;w._delayedHangup=!1;var jt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,jt.prototype),this.participantErrors=t}};function Hr(){if(!d.apiAppId||!d.apiKey)throw new k(ie.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function Ai(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Wr(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${d.apiEnv.api}fb.do`,r)}function Gr(i){return s(this,arguments,function*(a,e={},t=!1){let r=Wr(a,e,t);return Fa(r)})}function Fa(a){return s(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${d.apiEnv.api}fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(n){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(a)})})}function Wr(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=d.apiKey),t||(Z.sessionKey?e.session_key=Z.sessionKey:Z.accessToken&&(e.access_token=Z.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 Ga=10,Wa=700,ja=3e3,Kt=class extends dt{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return s(this,arguments,function*(e,t={},i=!1){let n=c=>s(this,null,function*(){try{return yield Gr(e,t,i)}catch(p){if(!p.hasOwnProperty("error_msg")&&(c++,o.debug(`${e} network error, attempt ${c}...`),c<Ga))return yield S.delay(Math.min(c*Wa,ja)),n(c);throw o.warn(e,"error",p),p}});return n(0)})}_call(r){return s(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){o.warn("Api call error",n);let c=ie.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:c=R.SERVICE_DISABLED;break;case 1102:c=R.CALLEE_IS_OFFLINE;break;case 1103:c=R.NOT_FRIENDS;break;case 1104:case 1106:c=R.EXTERNAL_API_ERROR;break}throw new k(c,{message:n.error_msg,code:n.error_code})}})}userId(e){return s(this,null,function*(){let t=S.decomposeId(e).id;return Z.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 s(this,null,function*(){Z.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return s(this,null,function*(){if(!this._uuid){let t=Ve.get("uuid");t||(t=S.uuid(),Ve.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:d.appVersion,client_type:"SDK_JS"}};return d.authToken&&(e.session_data.auth_token=d.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),Z.sessionKey=t.session_key,Z.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&_.onTokenExpired(),new k(ie.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${d.appName}:${d.sdkVersion}`,platform:d.platform,items:e})};Ai("log.externalLog",t)}init(){Hr()}joinConversation(e,t=!1,i){return s(this,null,function*(){let r={conversationId:e,isVideo:t};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return s(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1};return t&&(r.payload=t),d.domain&&(r.domainId=d.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,n="",c=!1,p=!1){return s(this,null,function*(){let l={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case xe.USER:l.uids=t.join(",");break;case xe.GROUP:l.gid=t[0];break;case xe.CHAT:l.chatId=t[0];break}return c&&(l.createJoinLink=!0),n&&(l.payload=n),d.domain&&(l.domainId=d.domain),p&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return s(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return s(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return s(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return s(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1){return s(this,null,function*(){let i={joinLink:e,isVideo:t};return d.anonymToken&&(i.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return s(this,null,function*(){let t=ee.fromIds(e),i=[],r={methods:[]},n=[],c=Object.keys(this._externalUidsCache),p=Object.values(this._externalUidsCache);for(let m of t){let y=ee.toString(m),D=p.indexOf(y);D>-1?i.push(Number(c[D])):(n.push(y),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:m.id,anonym:m.type===at.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((m,y)=>{if(m.ok){let D=Number(m.ok.ok_id);this._externalUidsCache[D]=n[y],i.push(D)}}),i})}getExternalIdsByOkIds(e){return s(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(ee.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(ee.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=ee.toString(e),n=i.indexOf(r);return n>-1?S.composeId(t[n],X.USER):null}cacheExternalId(e,t){let i=S.decomposeId(e).id;this._externalUidsCache[i]=ee.toString(t)}getConversationParams(e){return s(this,null,function*(){let t={};return d.anonymToken&&(t.anonymToken=d.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:R.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),Ai("vchat.hangupConversation",t)}removeHistoryRecords(e){return s(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return s(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,n]of Object.entries(i.external_ids))t[r]=ee.fromIdToString(n,at.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=ee.fromIdToString(n,at.ANONYM);return t}catch(i){return t}})}getTokenForAnonym(e,t){return s(this,null,function*(){let i={id:e};return t&&(i.application_key=t),(yield this._callUnsafe("auth.getTokenForAnonym",i,!0)).token})}call(i){return s(this,arguments,function*(e,t={}){return this._call(e,t)})}};var jr=(P=>(P.RECOVER="recover",P.ACCEPT_CALL="accept-call",P.ADD_PARTICIPANT="add-participant",P.REMOVE_PARTICIPANT="remove-participant",P.HANGUP="hangup",P.TRANSMIT_DATA="transmit-data",P.ACCEPT_PRODUCER="accept-producer",P.ALLOCATE_CONSUMER="allocate-consumer",P.CHANGE_MEDIA_SETTINGS="change-media-settings",P.CHANGE_PARTICIPANT_STATE="change-participant-state",P.CHANGE_STREAM_PRIORITIES="change-streams-priorities",P.UPDATE_DISPLAY_LAYOUT="update-display-layout",P.REPORT_PERF_STAT="report-perf-stat",P.RECORD_START="record-start",P.RECORD_STOP="record-stop",P.RECORD_SET_ROLE="record-set-role",P.RECORD_GET_STATUS="record-get-status",P.SWITCH_MICRO="switch-micro",P.SWITCH_TOPOLOGY="switch-topology",P.REQUEST_REALLOC="request-realloc",P.CHAT_MESSAGE="chat-message",P.CHAT_HISTORY="chat-history",P.CUSTOM_DATA="custom-data",P.GRANT_ROLES="grant-roles",P.MUTE_PARTICIPANT="mute-participant",P.PIN_PARTICIPANT="pin-participant",P.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",P.CHANGE_OPTIONS="change-options",P.GET_WAITING_HALL="get-waiting-hall",P.PROMOTE_PARTICIPANT="promote-participant",P.REQUEST_TEST_MODE="request-test-mode",P.ADD_MOVIE="add-movie",P.UPDATE_MOVIE="update-movie",P.REMOVE_MOVIE="remove-movie",P))(jr||{}),G=jr;var Kr="open",$r=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0],Ka=10,Ie=class extends lt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+d.platform+"&appVersion="+d.appVersion+"&version="+d.protocolVersion+"&device="+d.device+"&capabilities="+Ie._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<$r.length;t++)$r[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return s(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){u.log(h.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return s(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=S.decomposeId(t.participantId);t=Object.assign({},t,{participantId:n.id,participantType:n.type})}return this._sendRaw(e,t,i)})}_sendRaw(r){return s(this,arguments,function*(e,t={},i=0){let n=c=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(c),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===Kr&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){u.log(h.SOCKET_ACTION,"not_opened"),o.warn("Socket not opened"),c.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(u.log(h.SOCKET_ACTION,"invalid_state"),o.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(c),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((c,p)=>{let l=(y,D=!1)=>{!i||D?p(y):(o.debug("Resending a signaling message",e,m.sequence),i--,n(m))},m={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:c,reject:l};n(m)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return s(this,null,function*(){return this._send(G.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return s(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return s(this,null,function*(){return this._send(G.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return s(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return s(this,null,function*(){return this._send(G.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return s(this,null,function*(){return this._send(G.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},Ka)})}changeParticipantState(e){return s(this,null,function*(){return this._send(G.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return s(this,null,function*(){return this._send(G.ADD_PARTICIPANT,xi({participantId:e},t))})}removeParticipant(e,t=!1){return s(this,null,function*(){return this._send(G.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return s(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(G.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return s(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(G.ACCEPT_PRODUCER,i)})}changePriorities(e){return s(this,null,function*(){return this._send(G.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return s(this,null,function*(){return this._send(G.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return s(this,null,function*(){return this._send(G.ADD_MOVIE,e)})}updateMovie(e){return s(this,null,function*(){return this._send(G.UPDATE_MOVIE,e)})}removeMovie(e){return s(this,null,function*(){return this._send(G.REMOVE_MOVIE,e)})}startStream(e){return s(this,null,function*(){return this._send(G.RECORD_START,e)})}stopStream(){return s(this,null,function*(){return this._send(G.RECORD_STOP)})}recordSetRole(e,t){return s(this,null,function*(){return this._send(G.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return s(this,null,function*(){return this._send(G.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return s(this,null,function*(){return this._send(G.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return s(this,null,function*(){return this._send(G.REQUEST_REALLOC)})}reportPerfStat(e){return s(this,null,function*(){return this._send(G.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return s(this,null,function*(){return this._send(G.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return s(this,null,function*(){return this._send(G.CHAT_HISTORY,{count:e})})}customData(e,t){return s(this,null,function*(){return this._send(G.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return s(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(G.GRANT_ROLES,r)})}muteParticipant(e,t,i){return s(this,null,function*(){return this._sendRaw(G.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return s(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(G.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return s(this,null,function*(){return this._send(G.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return s(this,null,function*(){return this._send(G.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return s(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(G.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return s(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(G.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Le.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),o.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){o.debug("Socket opened"),u.log(h.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){u.log(h.SOCKET_ACTION,"parse_error"),o.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(o.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(me.RECONNECT,e),e.conversation.topology&&this._triggerEvent(me.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(me.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(u.log(h.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(u.log(h.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new k(R.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(me.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(ie.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(u.log(h.SOCKET_ACTION,"unknown_message"),o.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(me.FAILED,e)}_onError(e){u.log(h.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){u.log(h.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Ie.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(Ie.RECONNECT_MAX_DELAY,Ie.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),u.log(h.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(h.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Ie.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)!==Kr){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}Ie._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Ie.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),Ie.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(ie.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Ie.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{o.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Le.RETRY)},Ie.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},we=Ie;we.RECONNECT_DELAY=d.signalingReconnectDelay,we.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,we.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,we.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,we.WAIT_RESPONSE_DELAY=d.waitResponseDelay,we.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var qr=(t=>(t.KING="KING",t.PAWN="PAWN",t))(qr||{}),$a=qr;var st,re,bt=null,pu={getCameras:T.getCameras,getMicrophones:T.getMicrophones,getOutput:T.getOutput,hasCamera:T.hasCamera,hasMicrophone:T.hasMicrophone,getSavedCamera:T.getSavedCamera,getSavedMicrophone:T.getSavedMicrophone,getSavedOutput:T.getSavedOutput,hasCameraPermission:T.hasCameraPermission,hasMicrophonePermission:T.hasMicrophonePermission,hasPermissions:T.hasPermissions,getUserMedia:T.getUserMedia,getUserVideo:T.getUserVideo,getUserAudio:T.getUserAudio,saveDeviceId:T.saveDeviceId,isBrowserSupported:T.isBrowserSupported,isScreenCapturingSupported:T.isScreenCapturingSupported,os:T.os,isMobile:T.isMobile,browserName:T.browserName,browserVersion:T.browserVersion,baseChromeVersion:T.baseChromeVersion,getAudioContext:T.getAudioContext};function qa(a){re=a}function Ja(a){st=a}function lu(a){bt=a}function uu(a){d.videoEffects=a}function mu(a){return s(this,null,function*(){if(d.set(a),T.browserName()==="Sferum"&&(d.platform=`SFERUM:${T.browserVersion()}`),re||qa(new Kt),st||Ja(()=>new we),d.debug&&(Jr.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${d.sdkVersion}`,a),yield T.init(),!T.isBrowserSupported())throw new k(ie.UNSUPPORTED);re.init()})}function hu(n){return s(this,arguments,function*(a,e=[ce.AUDIO],t="",i=!1,r=!1){let c=[],p=[];if(Array.isArray(a)?c=a.length?a:[]:a&&(c=[a]),c.length&&(p=yield re.getOkIdsByExternalIds(c),!p.length))throw new k(R.CALLEE_IS_OFFLINE);return Ya(p,xe.USER,e,t,i,r)})}function Ya(c){return s(this,arguments,function*(a,e=xe.USER,t,i="",r=!1,n=!1){if(w.current())throw o.error("There is already active call"),new k(R.FAILED);return new w(re,st(),bt).onStart(a,e,t,i,r,n)})}function gu(a){return s(this,null,function*(){return za(a)})}function za(i){return s(this,arguments,function*(a,e=X.USER,t){if(a===w.id())throw new Error("Push has already been processed");return new w(re,st(),bt).onPush(a,e,t)})}function _u(a,e){return s(this,null,function*(){return re.getTokenForAnonym(a,e)})}function fu(t){return s(this,arguments,function*(a,e={}){return re.call(a,e)})}function Su(a){return s(this,null,function*(){return a&&(d.authToken=a),re.authorize()})}function vu(){return s(this,arguments,function*(a=[ce.AUDIO]){let e=w.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function Eu(){return s(this,null,function*(){let a=w.current();if(a)return a.decline()})}function Tu(t){return s(this,arguments,function*(a,e=[ce.AUDIO]){return Qa(a,e)})}function Qa(a,e,t){return s(this,null,function*(){if(w.current())throw o.error("There is already active call"),new k(R.FAILED);return new w(re,st(),bt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function Cu(i){return s(this,arguments,function*(a,e=[ce.AUDIO],t){if(w.current())throw o.error("There is already active call"),new k(R.FAILED);return t&&(d.anonymToken=t),new w(re,st(),bt).onJoin({joinLink:a,mediaOptions:e})})}function Iu(){return s(this,null,function*(){let a=w.current();if(a)return a.hangup();w.hangupAfterInit()})}function yu(a,e){return s(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return Xa(t[0],e)})}function Xa(a,e){return s(this,null,function*(){let t=w.current();t&&(yield t.addParticipant(S.composeId(a,X.USER),e))})}function Ru(a,e=!1){return s(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);return Za(t[0],e)})}function Za(a,e=!1){return s(this,null,function*(){let t=w.current();t&&(yield t.removeParticipant(S.composeId(a,X.USER),e))})}function bu(a,e){return s(this,null,function*(){let t=yield T.saveDeviceId(a,e),i=w.current();return t&&i?i.changeDevice(a):Promise.reject()})}function Pu(a){return s(this,null,function*(){let e=w.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function Mu(a,e=!1){return s(this,null,function*(){let t=w.current();t&&(yield t.setVideoStream(a,e))})}function Au(a){return s(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalVideo(a))})}function Du(a){return s(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalAudio(a))})}function Ou(a,e,t){return s(this,null,function*(){let i=w.current();if(i)return i.setLocalResolution(a,e,t)})}function ku(a){return s(this,null,function*(){let e=w.current();e&&(yield e.changePriorities(a))})}function wu(a){return s(this,null,function*(){let e=w.current();e&&(yield e.changeParticipantState(a))})}function Nu(a){return s(this,null,function*(){let e=w.current();e&&(yield e.updateDisplayLayout(a))})}function xu(a,e,t=!1){return s(this,null,function*(){let i=yield re.getOkIdsByExternalIds([a]);return en(i[0],e,t)})}function en(a,e,t=!1){return s(this,null,function*(){let i=w.current();i&&(yield i.grantRoles(S.composeId(a,X.USER),e,t))})}function Lu(){return s(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield re.getOkIdsByExternalIds([a]))[0]),tn(i,e,t)})}function tn(){return s(this,arguments,function*(a=null,e,t=[]){let i=w.current();if(i){let r=a?S.composeId(a,X.USER):null;yield i.muteParticipant(r,e,t)}})}function Uu(a,e=!1){return s(this,null,function*(){let t=yield re.getOkIdsByExternalIds([a]);return rn(t[0],e)})}function rn(a,e=!1){return s(this,null,function*(){let t=w.current();t&&(yield t.pinParticipant(S.composeId(a,X.USER),e))})}function Bu(a){return s(this,null,function*(){let e=w.current();e&&(yield e.updateMediaModifiers(a))})}function Vu(a){return s(this,null,function*(){let e=w.current();e&&(yield e.changeOptions(a))})}function Fu(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield re.getOkIdsByExternalIds([e]))[0]),an(a,t)})}function an(a,e=null){return s(this,null,function*(){let t=w.current();if(t){let i=e?S.composeId(e,X.USER):null;yield t.chatMessage(a,i)}})}function Hu(a=10){return s(this,null,function*(){let e=w.current();if(e)return e.chatHistory(a)})}function Gu(a,e=null){return s(this,null,function*(){let t=null;return e&&(t=(yield re.getOkIdsByExternalIds([e]))[0]),nn(a,t)})}function nn(a,e=null){return s(this,null,function*(){let t=w.current();if(t){let i=e?S.composeId(e,X.USER):null;yield t.customData(a,i)}})}function Wu(a="",e=!1){return s(this,null,function*(){return(yield re.createConversation(S.uuid(),a,e)).join_link})}function ju(){return s(this,null,function*(){let a=w.current();return a?a.createJoinLink():Promise.reject()})}function Ku(){return s(this,null,function*(){let a=w.current();return a?a.removeJoinLink():Promise.reject()})}function $u(a,e){return s(this,null,function*(){return re.getAnonymTokenByLink(a,e)})}function qu(a){let e=w.current();e&&e.setVolume(a)}function Ju(a){d.forceRelayPolicy=a}function Yu(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return s(this,null,function*(){let n=w.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function zu(){return s(this,null,function*(){let a=w.current();return a?a.stopStream():Promise.reject()})}function Qu(a,e){return s(this,null,function*(){let t=w.current();if(t){let i=yield re.getOkIdsByExternalIds([a]);return t.recordSetRole(S.composeId(i[0],X.USER),e)}return Promise.reject()})}function Xu(){return s(this,null,function*(){let a=w.current();return a?a.getStreamInfo():Promise.reject()})}function Zu(a){return s(this,null,function*(){let e=w.current();return e?e.addMovie(a):Promise.reject()})}function em(a,e,t,i){return s(this,null,function*(){let r=w.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function tm(a){return s(this,null,function*(){let e=w.current();return e?e.removeMovie(a):Promise.reject()})}function im(a){d.statisticsInterval=a;let e=w.current();if(e)return e.updateStatisticsInterval()}function rm(a){Jr.disableLog(!a),o.toggle(a)}function am(a,...e){!d.debugLog||o.send(a,"[external]",...e)}function nm(a){return s(this,null,function*(){let e=w.current();if(e)return e.videoEffect(a)})}function sm(a){return s(this,null,function*(){let e=w.current();e&&(yield e.setAudioStream(a))})}function om(a=null,e,t=!1){return s(this,null,function*(){let i=w.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(a,e,t)})}function cm(a,e=!1){return s(this,null,function*(){let t=w.current();if(!t)throw new Error("Conversation not found");let i=yield re.getOkIdsByExternalIds([a]);return t.promoteParticipant(S.composeId(i[0],X.USER),e)})}function dm(a){return s(this,null,function*(){yield re.removeHistoryRecords(a)})}export{Kt as Api,dt as BaseApi,pt as BaseLogger,lt as BaseSignaling,Ue as CallDirection,xe as CallType,Jt as ChatRoomEventType,Yt as ConversationOption,kr as DebugMessageType,at as ExternalIdType,vr as FacingMode,ie as FatalError,k as HangupReason,R as HangupType,ce as MediaOption,le as MediaTrackKind,ve as MediaType,Be as MuteState,W as ParticipantState,$ as ParticipantStatus,$a as RecordRole,we as Signaling,G as SignalingCommandType,Le as SignalingConnectionType,O as SignalingNotification,ze as UserRole,X as UserType,S as Utils,vu as acceptCall,Zu as addMovie,yu as addParticipant,Xa as addParticipantInternal,fu as apiCall,Su as authorize,pu as browser,Ya as callInternal,hu as callTo,Pu as captureScreen,Vu as changeConversationOptions,bu as changeDevice,wu as changeParticipantState,ku as changePriorities,nm as changeVideoEffect,Hu as chatHistory,Fu as chatMessage,an as chatMessageInternal,ju as createJoinLink,Gu as customData,nn as customDataInternal,rm as debug,am as debugMessage,Eu as declineCall,Ju as forceRelayPolicy,$u as getAnonymTokenByLink,Xu as getStreamInfo,_u as getTokenForAnonym,om as getWaitingHall,xu as grantRoles,en as grantRolesInternal,Iu as hangup,mu as init,Tu as joinCall,Cu as joinCallByLink,Qa as joinCallInternal,Lu as muteParticipant,tn as muteParticipantInternal,Uu as pinParticipant,rn as pinParticipantInternal,gu as processPush,za as processPushInternal,cm as promoteParticipant,Qu as recordSetRole,dm as removeHistoryRecords,Ku as removeJoinLink,tm as removeMovie,Ru as removeParticipant,Za as removeParticipantInternal,qa as setApi,sm as setAudioStream,Ou as setLocalResolution,lu as setLogger,Bu as setMediaModifiers,Ja as setSignalingFactory,im as setStatisticsInterval,uu as setVideoEffects,Mu as setVideoStream,qu as setVolume,Wu as startConversation,Yu as startStream,zu as stopStream,Du as toggleLocalAudio,Au as toggleLocalVideo,Nu as updateDisplayLayout,em as updateMovie};
|
|
7
|
+
var $n=Object.create;var Bt=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Jn=Object.getOwnPropertyNames,or=Object.getOwnPropertySymbols,Yn=Object.getPrototypeOf,cr=Object.prototype.hasOwnProperty,zn=Object.prototype.propertyIsEnumerable;var dr=Math.pow,pr=(n,e,t)=>e in n?Bt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,lr=(n,e)=>{for(var t in e||(e={}))cr.call(e,t)&&pr(n,t,e[t]);if(or)for(var t of or(e))zn.call(e,t)&&pr(n,t,e[t]);return n};var Qn=n=>Bt(n,"__esModule",{value:!0});var pi=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Xn=(n,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jn(e))!cr.call(n,i)&&i!=="default"&&Bt(n,i,{get:()=>e[i],enumerable:!(t=qn(e,i))||t.enumerable});return n},ur=n=>Xn(Qn(Bt(n!=null?$n(Yn(n)):{},"default",n&&n.__esModule&&"default"in n?{get:()=>n.default,enumerable:!0}:{value:n,enumerable:!0})),n);var o=(n,e,t)=>new Promise((i,r)=>{var a=p=>{try{d(t.next(p))}catch(u){r(u)}},s=p=>{try{d(t.throw(p))}catch(u){r(u)}},d=p=>p.done?i(p.value):Promise.resolve(p.value).then(a,s);d((t=t.apply(n,e)).next())});var Kr=pi(Vt=>{"use strict";Vt.byteLength=sa;Vt.toByteArray=ca;Vt.fromByteArray=la;var Ne=[],Me=[],aa=typeof Uint8Array!="undefined"?Uint8Array:Array,vi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ze=0,Wr=vi.length;ze<Wr;++ze)Ne[ze]=vi[ze],Me[vi.charCodeAt(ze)]=ze;var ze,Wr;Me["-".charCodeAt(0)]=62;Me["_".charCodeAt(0)]=63;function jr(n){var e=n.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=n.indexOf("=");t===-1&&(t=e);var i=t===e?0:4-t%4;return[t,i]}function sa(n){var e=jr(n),t=e[0],i=e[1];return(t+i)*3/4-i}function oa(n,e,t){return(e+t)*3/4-t}function ca(n){var e,t=jr(n),i=t[0],r=t[1],a=new aa(oa(n,i,r)),s=0,d=r>0?i-4:i,p;for(p=0;p<d;p+=4)e=Me[n.charCodeAt(p)]<<18|Me[n.charCodeAt(p+1)]<<12|Me[n.charCodeAt(p+2)]<<6|Me[n.charCodeAt(p+3)],a[s++]=e>>16&255,a[s++]=e>>8&255,a[s++]=e&255;return r===2&&(e=Me[n.charCodeAt(p)]<<2|Me[n.charCodeAt(p+1)]>>4,a[s++]=e&255),r===1&&(e=Me[n.charCodeAt(p)]<<10|Me[n.charCodeAt(p+1)]<<4|Me[n.charCodeAt(p+2)]>>2,a[s++]=e>>8&255,a[s++]=e&255),a}function da(n){return Ne[n>>18&63]+Ne[n>>12&63]+Ne[n>>6&63]+Ne[n&63]}function pa(n,e,t){for(var i,r=[],a=e;a<t;a+=3)i=(n[a]<<16&16711680)+(n[a+1]<<8&65280)+(n[a+2]&255),r.push(da(i));return r.join("")}function la(n){for(var e,t=n.length,i=t%3,r=[],a=16383,s=0,d=t-i;s<d;s+=a)r.push(pa(n,s,s+a>d?d:s+a));return i===1?(e=n[t-1],r.push(Ne[e>>2]+Ne[e<<4&63]+"==")):i===2&&(e=(n[t-2]<<8)+n[t-1],r.push(Ne[e>>10]+Ne[e>>4&63]+Ne[e<<2&63]+"=")),r.join("")}});var $r=pi(Ei=>{Ei.read=function(n,e,t,i,r){var a,s,d=r*8-i-1,p=(1<<d)-1,u=p>>1,_=-7,f=t?r-1:0,W=t?-1:1,K=n[e+f];for(f+=W,a=K&(1<<-_)-1,K>>=-_,_+=d;_>0;a=a*256+n[e+f],f+=W,_-=8);for(s=a&(1<<-_)-1,a>>=-_,_+=i;_>0;s=s*256+n[e+f],f+=W,_-=8);if(a===0)a=1-u;else{if(a===p)return s?NaN:(K?-1:1)*(1/0);s=s+Math.pow(2,i),a=a-u}return(K?-1:1)*s*Math.pow(2,a-i)};Ei.write=function(n,e,t,i,r,a){var s,d,p,u=a*8-r-1,_=(1<<u)-1,f=_>>1,W=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,K=i?0:a-1,O=i?1:-1,J=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(d=isNaN(e)?1:0,s=_):(s=Math.floor(Math.log(e)/Math.LN2),e*(p=Math.pow(2,-s))<1&&(s--,p*=2),s+f>=1?e+=W/p:e+=W*Math.pow(2,1-f),e*p>=2&&(s++,p/=2),s+f>=_?(d=0,s=_):s+f>=1?(d=(e*p-1)*Math.pow(2,r),s=s+f):(d=e*Math.pow(2,f-1)*Math.pow(2,r),s=0));r>=8;n[t+K]=d&255,K+=O,d/=256,r-=8);for(s=s<<r|d,u+=r;u>0;n[t+K]=s&255,K+=O,s/=256,u-=8);n[t+K-O]|=J*128}});var Mi=pi(dt=>{"use strict";var Ti=Kr(),ct=$r(),qr=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;dt.Buffer=h;dt.SlowBuffer=fa;dt.INSPECT_MAX_BYTES=50;var Ht=2147483647;dt.kMaxLength=Ht;h.TYPED_ARRAY_SUPPORT=ua();!h.TYPED_ARRAY_SUPPORT&&typeof console!="undefined"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function ua(){try{var n=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(n,e),n.foo()===42}catch(t){return!1}}Object.defineProperty(h.prototype,"parent",{enumerable:!0,get:function(){if(!!h.isBuffer(this))return this.buffer}});Object.defineProperty(h.prototype,"offset",{enumerable:!0,get:function(){if(!!h.isBuffer(this))return this.byteOffset}});function Ge(n){if(n>Ht)throw new RangeError('The value "'+n+'" is invalid for option "size"');var e=new Uint8Array(n);return Object.setPrototypeOf(e,h.prototype),e}function h(n,e,t){if(typeof n=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Ci(n)}return Jr(n,e,t)}h.poolSize=8192;function Jr(n,e,t){if(typeof n=="string")return ma(n,e);if(ArrayBuffer.isView(n))return _a(n);if(n==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n);if(Le(n,ArrayBuffer)||n&&Le(n.buffer,ArrayBuffer)||typeof SharedArrayBuffer!="undefined"&&(Le(n,SharedArrayBuffer)||n&&Le(n.buffer,SharedArrayBuffer)))return yi(n,e,t);if(typeof n=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var i=n.valueOf&&n.valueOf();if(i!=null&&i!==n)return h.from(i,e,t);var r=ga(n);if(r)return r;if(typeof Symbol!="undefined"&&Symbol.toPrimitive!=null&&typeof n[Symbol.toPrimitive]=="function")return h.from(n[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n)}h.from=function(n,e,t){return Jr(n,e,t)};Object.setPrototypeOf(h.prototype,Uint8Array.prototype);Object.setPrototypeOf(h,Uint8Array);function Yr(n){if(typeof n!="number")throw new TypeError('"size" argument must be of type number');if(n<0)throw new RangeError('The value "'+n+'" is invalid for option "size"')}function ha(n,e,t){return Yr(n),n<=0?Ge(n):e!==void 0?typeof t=="string"?Ge(n).fill(e,t):Ge(n).fill(e):Ge(n)}h.alloc=function(n,e,t){return ha(n,e,t)};function Ci(n){return Yr(n),Ge(n<0?0:Ri(n)|0)}h.allocUnsafe=function(n){return Ci(n)};h.allocUnsafeSlow=function(n){return Ci(n)};function ma(n,e){if((typeof e!="string"||e==="")&&(e="utf8"),!h.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var t=zr(n,e)|0,i=Ge(t),r=i.write(n,e);return r!==t&&(i=i.slice(0,r)),i}function Ii(n){for(var e=n.length<0?0:Ri(n.length)|0,t=Ge(e),i=0;i<e;i+=1)t[i]=n[i]&255;return t}function _a(n){if(Le(n,Uint8Array)){var e=new Uint8Array(n);return yi(e.buffer,e.byteOffset,e.byteLength)}return Ii(n)}function yi(n,e,t){if(e<0||n.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(n.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');var i;return e===void 0&&t===void 0?i=new Uint8Array(n):t===void 0?i=new Uint8Array(n,e):i=new Uint8Array(n,e,t),Object.setPrototypeOf(i,h.prototype),i}function ga(n){if(h.isBuffer(n)){var e=Ri(n.length)|0,t=Ge(e);return t.length===0||n.copy(t,0,0,e),t}if(n.length!==void 0)return typeof n.length!="number"||Pi(n.length)?Ge(0):Ii(n);if(n.type==="Buffer"&&Array.isArray(n.data))return Ii(n.data)}function Ri(n){if(n>=Ht)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Ht.toString(16)+" bytes");return n|0}function fa(n){return+n!=n&&(n=0),h.alloc(+n)}h.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==h.prototype};h.compare=function(e,t){if(Le(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),Le(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),!h.isBuffer(e)||!h.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var i=e.length,r=t.length,a=0,s=Math.min(i,r);a<s;++a)if(e[a]!==t[a]){i=e[a],r=t[a];break}return i<r?-1:r<i?1:0};h.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};h.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return h.alloc(0);var i;if(t===void 0)for(t=0,i=0;i<e.length;++i)t+=e[i].length;var r=h.allocUnsafe(t),a=0;for(i=0;i<e.length;++i){var s=e[i];if(Le(s,Uint8Array))a+s.length>r.length?h.from(s).copy(r,a):Uint8Array.prototype.set.call(r,s,a);else if(h.isBuffer(s))s.copy(r,a);else throw new TypeError('"list" argument must be an Array of Buffers');a+=s.length}return r};function zr(n,e){if(h.isBuffer(n))return n.length;if(ArrayBuffer.isView(n)||Le(n,ArrayBuffer))return n.byteLength;if(typeof n!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof n);var t=n.length,i=arguments.length>2&&arguments[2]===!0;if(!i&&t===0)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return bi(n).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return an(n).length;default:if(r)return i?-1:bi(n).length;e=(""+e).toLowerCase(),r=!0}}h.byteLength=zr;function Sa(n,e,t){var i=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(n||(n="utf8");;)switch(n){case"hex":return Ma(this,e,t);case"utf8":case"utf-8":return Zr(this,e,t);case"ascii":return ba(this,e,t);case"latin1":case"binary":return Pa(this,e,t);case"base64":return ya(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Aa(this,e,t);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(n+"").toLowerCase(),i=!0}}h.prototype._isBuffer=!0;function Qe(n,e,t){var i=n[e];n[e]=n[t],n[t]=i}h.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)Qe(this,t,t+1);return this};h.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)Qe(this,t,t+3),Qe(this,t+1,t+2);return this};h.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)Qe(this,t,t+7),Qe(this,t+1,t+6),Qe(this,t+2,t+5),Qe(this,t+3,t+4);return this};h.prototype.toString=function(){var e=this.length;return e===0?"":arguments.length===0?Zr(this,0,e):Sa.apply(this,arguments)};h.prototype.toLocaleString=h.prototype.toString;h.prototype.equals=function(e){if(!h.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:h.compare(this,e)===0};h.prototype.inspect=function(){var e="",t=dt.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"};qr&&(h.prototype[qr]=h.prototype.inspect);h.prototype.compare=function(e,t,i,r,a){if(Le(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),!h.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),i===void 0&&(i=e?e.length:0),r===void 0&&(r=0),a===void 0&&(a=this.length),t<0||i>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=i)return 0;if(r>=a)return-1;if(t>=i)return 1;if(t>>>=0,i>>>=0,r>>>=0,a>>>=0,this===e)return 0;for(var s=a-r,d=i-t,p=Math.min(s,d),u=this.slice(r,a),_=e.slice(t,i),f=0;f<p;++f)if(u[f]!==_[f]){s=u[f],d=_[f];break}return s<d?-1:d<s?1:0};function Qr(n,e,t,i,r){if(n.length===0)return-1;if(typeof t=="string"?(i=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,Pi(t)&&(t=r?0:n.length-1),t<0&&(t=n.length+t),t>=n.length){if(r)return-1;t=n.length-1}else if(t<0)if(r)t=0;else return-1;if(typeof e=="string"&&(e=h.from(e,i)),h.isBuffer(e))return e.length===0?-1:Xr(n,e,t,i,r);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?r?Uint8Array.prototype.indexOf.call(n,e,t):Uint8Array.prototype.lastIndexOf.call(n,e,t):Xr(n,[e],t,i,r);throw new TypeError("val must be string, number or Buffer")}function Xr(n,e,t,i,r){var a=1,s=n.length,d=e.length;if(i!==void 0&&(i=String(i).toLowerCase(),i==="ucs2"||i==="ucs-2"||i==="utf16le"||i==="utf-16le")){if(n.length<2||e.length<2)return-1;a=2,s/=2,d/=2,t/=2}function p(K,O){return a===1?K[O]:K.readUInt16BE(O*a)}var u;if(r){var _=-1;for(u=t;u<s;u++)if(p(n,u)===p(e,_===-1?0:u-_)){if(_===-1&&(_=u),u-_+1===d)return _*a}else _!==-1&&(u-=u-_),_=-1}else for(t+d>s&&(t=s-d),u=t;u>=0;u--){for(var f=!0,W=0;W<d;W++)if(p(n,u+W)!==p(e,W)){f=!1;break}if(f)return u}return-1}h.prototype.includes=function(e,t,i){return this.indexOf(e,t,i)!==-1};h.prototype.indexOf=function(e,t,i){return Qr(this,e,t,i,!0)};h.prototype.lastIndexOf=function(e,t,i){return Qr(this,e,t,i,!1)};function va(n,e,t,i){t=Number(t)||0;var r=n.length-t;i?(i=Number(i),i>r&&(i=r)):i=r;var a=e.length;i>a/2&&(i=a/2);for(var s=0;s<i;++s){var d=parseInt(e.substr(s*2,2),16);if(Pi(d))return s;n[t+s]=d}return s}function Ea(n,e,t,i){return Gt(bi(e,n.length-t),n,t,i)}function Ta(n,e,t,i){return Gt(Oa(e),n,t,i)}function Ca(n,e,t,i){return Gt(an(e),n,t,i)}function Ia(n,e,t,i){return Gt(ka(e,n.length-t),n,t,i)}h.prototype.write=function(e,t,i,r){if(t===void 0)r="utf8",i=this.length,t=0;else if(i===void 0&&typeof t=="string")r=t,i=this.length,t=0;else if(isFinite(t))t=t>>>0,isFinite(i)?(i=i>>>0,r===void 0&&(r="utf8")):(r=i,i=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var a=this.length-t;if((i===void 0||i>a)&&(i=a),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return va(this,e,t,i);case"utf8":case"utf-8":return Ea(this,e,t,i);case"ascii":case"latin1":case"binary":return Ta(this,e,t,i);case"base64":return Ca(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ia(this,e,t,i);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}};h.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ya(n,e,t){return e===0&&t===n.length?Ti.fromByteArray(n):Ti.fromByteArray(n.slice(e,t))}function Zr(n,e,t){t=Math.min(n.length,t);for(var i=[],r=e;r<t;){var a=n[r],s=null,d=a>239?4:a>223?3:a>191?2:1;if(r+d<=t){var p,u,_,f;switch(d){case 1:a<128&&(s=a);break;case 2:p=n[r+1],(p&192)==128&&(f=(a&31)<<6|p&63,f>127&&(s=f));break;case 3:p=n[r+1],u=n[r+2],(p&192)==128&&(u&192)==128&&(f=(a&15)<<12|(p&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:p=n[r+1],u=n[r+2],_=n[r+3],(p&192)==128&&(u&192)==128&&(_&192)==128&&(f=(a&15)<<18|(p&63)<<12|(u&63)<<6|_&63,f>65535&&f<1114112&&(s=f))}}s===null?(s=65533,d=1):s>65535&&(s-=65536,i.push(s>>>10&1023|55296),s=56320|s&1023),i.push(s),r+=d}return Ra(i)}var en=4096;function Ra(n){var e=n.length;if(e<=en)return String.fromCharCode.apply(String,n);for(var t="",i=0;i<e;)t+=String.fromCharCode.apply(String,n.slice(i,i+=en));return t}function ba(n,e,t){var i="";t=Math.min(n.length,t);for(var r=e;r<t;++r)i+=String.fromCharCode(n[r]&127);return i}function Pa(n,e,t){var i="";t=Math.min(n.length,t);for(var r=e;r<t;++r)i+=String.fromCharCode(n[r]);return i}function Ma(n,e,t){var i=n.length;(!e||e<0)&&(e=0),(!t||t<0||t>i)&&(t=i);for(var r="",a=e;a<t;++a)r+=xa[n[a]];return r}function Aa(n,e,t){for(var i=n.slice(e,t),r="",a=0;a<i.length-1;a+=2)r+=String.fromCharCode(i[a]+i[a+1]*256);return r}h.prototype.slice=function(e,t){var i=this.length;e=~~e,t=t===void 0?i:~~t,e<0?(e+=i,e<0&&(e=0)):e>i&&(e=i),t<0?(t+=i,t<0&&(t=0)):t>i&&(t=i),t<e&&(t=e);var r=this.subarray(e,t);return Object.setPrototypeOf(r,h.prototype),r};function _e(n,e,t){if(n%1!=0||n<0)throw new RangeError("offset is not uint");if(n+e>t)throw new RangeError("Trying to access beyond buffer length")}h.prototype.readUintLE=h.prototype.readUIntLE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r};h.prototype.readUintBE=h.prototype.readUIntBE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r};h.prototype.readUint8=h.prototype.readUInt8=function(e,t){return e=e>>>0,t||_e(e,1,this.length),this[e]};h.prototype.readUint16LE=h.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||_e(e,2,this.length),this[e]|this[e+1]<<8};h.prototype.readUint16BE=h.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||_e(e,2,this.length),this[e]<<8|this[e+1]};h.prototype.readUint32LE=h.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};h.prototype.readUint32BE=h.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};h.prototype.readIntLE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return a*=128,r>=a&&(r-=Math.pow(2,8*t)),r};h.prototype.readIntBE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=t,a=1,s=this[e+--r];r>0&&(a*=256);)s+=this[e+--r]*a;return a*=128,s>=a&&(s-=Math.pow(2,8*t)),s};h.prototype.readInt8=function(e,t){return e=e>>>0,t||_e(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};h.prototype.readInt16LE=function(e,t){e=e>>>0,t||_e(e,2,this.length);var i=this[e]|this[e+1]<<8;return i&32768?i|4294901760:i};h.prototype.readInt16BE=function(e,t){e=e>>>0,t||_e(e,2,this.length);var i=this[e+1]|this[e]<<8;return i&32768?i|4294901760:i};h.prototype.readInt32LE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};h.prototype.readInt32BE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};h.prototype.readFloatLE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),ct.read(this,e,!0,23,4)};h.prototype.readFloatBE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),ct.read(this,e,!1,23,4)};h.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||_e(e,8,this.length),ct.read(this,e,!0,52,8)};h.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||_e(e,8,this.length),ct.read(this,e,!1,52,8)};function Te(n,e,t,i,r,a){if(!h.isBuffer(n))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>r||e<a)throw new RangeError('"value" argument is out of bounds');if(t+i>n.length)throw new RangeError("Index out of range")}h.prototype.writeUintLE=h.prototype.writeUIntLE=function(e,t,i,r){if(e=+e,t=t>>>0,i=i>>>0,!r){var a=Math.pow(2,8*i)-1;Te(this,e,t,i,a,0)}var s=1,d=0;for(this[t]=e&255;++d<i&&(s*=256);)this[t+d]=e/s&255;return t+i};h.prototype.writeUintBE=h.prototype.writeUIntBE=function(e,t,i,r){if(e=+e,t=t>>>0,i=i>>>0,!r){var a=Math.pow(2,8*i)-1;Te(this,e,t,i,a,0)}var s=i-1,d=1;for(this[t+s]=e&255;--s>=0&&(d*=256);)this[t+s]=e/d&255;return t+i};h.prototype.writeUint8=h.prototype.writeUInt8=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,1,255,0),this[t]=e&255,t+1};h.prototype.writeUint16LE=h.prototype.writeUInt16LE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2};h.prototype.writeUint16BE=h.prototype.writeUInt16BE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2};h.prototype.writeUint32LE=h.prototype.writeUInt32LE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4};h.prototype.writeUint32BE=h.prototype.writeUInt32BE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};h.prototype.writeIntLE=function(e,t,i,r){if(e=+e,t=t>>>0,!r){var a=Math.pow(2,8*i-1);Te(this,e,t,i,a-1,-a)}var s=0,d=1,p=0;for(this[t]=e&255;++s<i&&(d*=256);)e<0&&p===0&&this[t+s-1]!==0&&(p=1),this[t+s]=(e/d>>0)-p&255;return t+i};h.prototype.writeIntBE=function(e,t,i,r){if(e=+e,t=t>>>0,!r){var a=Math.pow(2,8*i-1);Te(this,e,t,i,a-1,-a)}var s=i-1,d=1,p=0;for(this[t+s]=e&255;--s>=0&&(d*=256);)e<0&&p===0&&this[t+s+1]!==0&&(p=1),this[t+s]=(e/d>>0)-p&255;return t+i};h.prototype.writeInt8=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1};h.prototype.writeInt16LE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2};h.prototype.writeInt16BE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2};h.prototype.writeInt32LE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4};h.prototype.writeInt32BE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function tn(n,e,t,i,r,a){if(t+i>n.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function rn(n,e,t,i,r){return e=+e,t=t>>>0,r||tn(n,e,t,4,34028234663852886e22,-34028234663852886e22),ct.write(n,e,t,i,23,4),t+4}h.prototype.writeFloatLE=function(e,t,i){return rn(this,e,t,!0,i)};h.prototype.writeFloatBE=function(e,t,i){return rn(this,e,t,!1,i)};function nn(n,e,t,i,r){return e=+e,t=t>>>0,r||tn(n,e,t,8,17976931348623157e292,-17976931348623157e292),ct.write(n,e,t,i,52,8),t+8}h.prototype.writeDoubleLE=function(e,t,i){return nn(this,e,t,!0,i)};h.prototype.writeDoubleBE=function(e,t,i){return nn(this,e,t,!1,i)};h.prototype.copy=function(e,t,i,r){if(!h.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<i&&(r=i),r===i||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-i&&(r=e.length-t+i);var a=r-i;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(t,i,r):Uint8Array.prototype.set.call(e,this.subarray(i,r),t),a};h.prototype.fill=function(e,t,i,r){if(typeof e=="string"){if(typeof t=="string"?(r=t,t=0,i=this.length):typeof i=="string"&&(r=i,i=this.length),r!==void 0&&typeof r!="string")throw new TypeError("encoding must be a string");if(typeof r=="string"&&!h.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(e.length===1){var a=e.charCodeAt(0);(r==="utf8"&&a<128||r==="latin1")&&(e=a)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(t<0||this.length<t||this.length<i)throw new RangeError("Out of range index");if(i<=t)return this;t=t>>>0,i=i===void 0?this.length:i>>>0,e||(e=0);var s;if(typeof e=="number")for(s=t;s<i;++s)this[s]=e;else{var d=h.isBuffer(e)?e:h.from(e,r),p=d.length;if(p===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<i-t;++s)this[s+t]=d[s%p]}return this};var Da=/[^+/0-9A-Za-z-_]/g;function wa(n){if(n=n.split("=")[0],n=n.trim().replace(Da,""),n.length<2)return"";for(;n.length%4!=0;)n=n+"=";return n}function bi(n,e){e=e||1/0;for(var t,i=n.length,r=null,a=[],s=0;s<i;++s){if(t=n.charCodeAt(s),t>55295&&t<57344){if(!r){if(t>56319){(e-=3)>-1&&a.push(239,191,189);continue}else if(s+1===i){(e-=3)>-1&&a.push(239,191,189);continue}r=t;continue}if(t<56320){(e-=3)>-1&&a.push(239,191,189),r=t;continue}t=(r-55296<<10|t-56320)+65536}else r&&(e-=3)>-1&&a.push(239,191,189);if(r=null,t<128){if((e-=1)<0)break;a.push(t)}else if(t<2048){if((e-=2)<0)break;a.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;a.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;a.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return a}function Oa(n){for(var e=[],t=0;t<n.length;++t)e.push(n.charCodeAt(t)&255);return e}function ka(n,e){for(var t,i,r,a=[],s=0;s<n.length&&!((e-=2)<0);++s)t=n.charCodeAt(s),i=t>>8,r=t%256,a.push(r),a.push(i);return a}function an(n){return Ti.toByteArray(wa(n))}function Gt(n,e,t,i){for(var r=0;r<i&&!(r+t>=e.length||r>=n.length);++r)e[r+t]=n[r];return r}function Le(n,e){return n instanceof e||n!=null&&n.constructor!=null&&n.constructor.name!=null&&n.constructor.name===e.name}function Pi(n){return n!==n}var xa=function(){for(var n="0123456789abcdef",e=new Array(256),t=0;t<16;++t)for(var i=t*16,r=0;r<16;++r)e[i+r]=n[t]+n[r];return e}()});import jn from"webrtc-adapter";var Et=class{createJoinLink(e){return o(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return o(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return o(this,null,function*(){return""})}log(e){}prepareUserIds(e){return o(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return o(this,null,function*(){})}cleanup(){}getTokenForAnonym(e,t){return o(this,null,function*(){return""})}call(i){return o(this,arguments,function*(e,t={}){return null})}};var Tt=class{log(e,t,i=!1){}destroy(){}};var Q=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var Ct=class extends Q{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var hr=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(hr||{}),je=hr;var mr=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(mr||{}),Ve=mr;var _r=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(_r||{}),li=_r;var gr=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(gr||{}),fr=gr;var Sr=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(Sr||{}),ui=Sr;function vr(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}function Er(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 Tr=(O=>(O.CAMERA_PERMISSION="camera",O.MIC_PERMISSION="mic",O.CAMERA_ACCESS="cameralock",O.MIC_ACCESS="miclock",O.MIC_NOT_FOUND="nomic",O.SCREEN_PERMISSION="screenpermission",O.SCREEN_ACCESS="screenlock",O.CONNECTION="connection",O.NETWORK="network",O.UNKNOWN="unknown",O.UNSUPPORTED="unsupported",O.SIGNALING_FAILED="signalingfailed",O.API="api",O.AUTH="auth",O))(Tr||{}),ne=Tr;var Cr=($=>($.CANCELED="CANCELED",$.REJECTED="REJECTED",$.REMOVED="REMOVED",$.HUNGUP="HUNGUP",$.MISSED="MISSED",$.BUSY="BUSY",$.FAILED="FAILED",$.NETWORK_ERROR="NETWORK_ERROR",$.KILLED="KILLED",$.BANNED="BANNED",$.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",$.NOT_FRIENDS="NOT_FRIENDS",$.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",$.UNKNOWN_ERROR="UNKNOWN_ERROR",$.UNSUPPORTED="UNSUPPORTED",$.OLD_VERSION="OLD_VERSION",$.SERVICE_DISABLED="SERVICE_DISABLED",$.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",$.SOCKET_CLOSED="SOCKET_CLOSED",$.ENDED="ENDED",$))(Cr||{}),P=Cr;var Ir=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(Ir||{}),he=Ir;var yr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(yr||{}),Ke=yr;var Rr=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(Rr||{}),j=Rr;var br=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(br||{}),He=br;var Pr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(Pr||{}),fe=Pr;var Mr=(D=>(D.TRANSMITTED_DATA="transmitted-data",D.ACCEPTED_CALL="accepted-call",D.HUNGUP="hungup",D.PARTICIPANT_ADDED="participant-added",D.PARTICIPANT_JOINED="participant-joined",D.CLOSED_CONVERSATION="closed-conversation",D.MEDIA_SETTINGS_CHANGED="media-settings-changed",D.PARTICIPANT_STATE_CHANGED="participant-state-changed",D.RATE_CALL_DATA="rate-call-data",D.FEATURE_SET_CHANGED="feature-set-changed",D.TOPOLOGY_CHANGED="topology-changed",D.PRODUCER_UPDATED="producer-updated",D.CONSUMER_ANSWERED="consumer-answered",D.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",D.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",D.SETTINGS_UPDATE="settings-update",D.VIDEO_QUALITY_UPDATE="video-quality-update",D.REGISTERED_PEER="registered-peer",D.SWITCH_MICRO="switch-micro",D.RECORD_STARTED="record-started",D.RECORD_STOPPED="record-stopped",D.REALLOC_CON="realloc-con",D.AUDIO_ACTIVITY="audio-activity",D.SPEAKER_CHANGED="speaker-changed",D.STALLED_ACTIVITY="stalled-activity",D.CHAT_MESSAGE="chat-message",D.CUSTOM_DATA="custom-data",D.ROLES_CHANGED="roles-changed",D.MUTE_PARTICIPANT="mute-participant",D.PIN_PARTICIPANT="pin-participant",D.OPTIONS_CHANGED="options-changed",D.NETWORK_STATUS="network-status",D.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",D.PROMOTE_PARTICIPANT="promote-participant",D.CHAT_ROOM_UPDATED="chat-room-updated",D.PROMOTION_APPROVED="promotion-approved",D.JOIN_LINK_CHANGED="join-link-changed",D))(Mr||{}),k=Mr;var Ar=(b=>(b.ERROR="callError",b.DEVICES="callDevices",b.CALL_SPEC_ERROR="callSpecError",b.ICE_CONNECTION_STATE="callIceConnectionState",b.ICE_CONNECTION_TYPE="callIceConnectionType",b.ICE_RESTART="callIceRestart",b.PUSH="callPush",b.OUTGOING_CALL="callStart",b.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",b.JOIN_CONVERSATION="callJoinConversation",b.ACCEPTED_OUTGOING="callAcceptedOutgoing",b.ACCEPT_INCOMING="callAcceptIncoming",b.DECLINE_INCOMING="callDeclineIncoming",b.ACCEPT_CONCURRENT="callAcceptConcurrent",b.HANGUP="callHangup",b.MEDIA_STATUS="callMediaStatus",b.DEVICE_CHANGED="callDeviceChanged",b.SOCKET_ACTION="callSocketAction",b.ADD_PARTICIPANT="callAddParticipant",b.REMOVE_PARTICIPANT="callRemoveParticipant",b.POOR_CONNECTION="callPoorConnection",b.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",b.RELAY_POLICY="callForceRelay",b.PAT_ALLOCATED="patAllocate",b.PAT_DEALLOCATED="patDeallocate",b.PAT_ERROR="patError",b.PAT_WAITING_TIME_ERROR="patWaitingTimeError",b.PAT_OUTDATED_RESPONSE="patOutdatedResponse",b))(Ar||{}),g=Ar;var Dr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(Dr||{}),Oe=Dr;var wr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(wr||{}),Or=wr;function kr(n){switch(n){case 1:return"no-available-tracks";default:return"unknown-error"}}var xr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(xr||{}),st=xr;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 Nr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(Nr||{}),te=Nr;var hi=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,Zn=512*1024,yt=100*1024,ea=5,mi="_okcls_logs_session_",ta=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(mi)!==0)continue;let i=e.getItem(t);if(!i){Vr(t);continue}let r=Fr(i);this.add(t,r)}}catch(e){console.error("Storage is blocked",e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(yt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(mi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Vr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>Lr||this.length>ea-1||this.size+e>this.available);)this.deleteOldestItem()}};function Br(){return`${mi}${Date.now()}`}function Fr(n){return new Blob([n]).size}function Vr(n){try{window.localStorage.removeItem(n)}catch(e){console.error("Failed to remove log from storage",e)}}function _i(){let n=Je.toString();if(!Ee.available||!n)return;let e=Fr(n);Ee.cleanup(e);try{window.localStorage.setItem(Ft,n)}catch(t){if(console.warn("Failed to write log to storage",t),Ee.storageSize=Ee.size+e,Ee.cleanup(yt+e),Ee.available>=yt+e){_i();return}if(e>yt){Je.bisect(),_i();return}Ee.storageSize=0;return}e>Zn&&(Ee.add(Ft,e),Ft=Br(),Je.clear(),Ee.cleanup(yt))}function gi(){!Ee.available||!Je.length||_i()}function ia(n=!1){let e=[];try{let r=window.localStorage;for(let s of Ee.items){let d=r.getItem(s.key);e.push(d)}let a=Je.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 ra(t,i),i}function ra(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 Hr(n,e){!Ee.available||(Je.push({t:Date.now(),l:n,d:e}),Si||(Si=window.setTimeout(()=>{Si=null,gi()},ta)))}function fi(){Ee||(Ee=new Ur,Je=new hi,Ft=Br(),window.addEventListener("beforeunload",gi))}var Ee,Je,Ft,Si=null;window.__VKCallsSDKLogs__=(n=!1)=>(Ee||fi(),gi(),ia(n));import{saveAs as bn}from"file-saver";import Gr from"@vkontakte/libvpx";var Se=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(Se||{});var m=class extends Tt{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={};typeof t!="undefined"&&(r.param=t),this._logInternal(e,r,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){m._instance||(m._instance=new m(e,t))}static log(e,t,i=!1){m._instance&&m._instance.log(e,t,i)}static logCustom(e,t,i=!1){m._instance&&m._instance.logCustom(e,t,i)}static destroy(){m._instance&&m._instance.destroy(),m._instance=null}};var xe=class{constructor(){this._worker=null}_createWorker(s,d){return o(this,arguments,function*(e,t,i=[],r={},a=[]){return new Promise((p,u)=>{let _=i.join(","),f=new Blob([e,`exports.default(${_});`],{type:"application/javascript; charset=utf-8"}),W=window.URL.createObjectURL(f);this._worker=new Worker(W),this._worker.onmessage=K=>{switch(K.data.type){case Se.READY:p();break;case Se.ERROR:u(K.data.error);break;case Se.FRAME:t(K.data);break;case Se.DEBUG:c.debug(K.data.message);break;case Se.LOG_ERROR:m.log(g.ERROR,K.data.message);break}},this._sendToWorker(Se.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 ot=class extends xe{init(e){return o(this,null,function*(){c.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var b=Object.defineProperty;var M=a=>b(a,"__esModule",{value:!0});var V=(a,i)=>{M(a);for(var e in i)b(a,e,{get:i[e],enumerable:!0})};var h={};V(h,{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,i)=>{let e=null,n=null,g=!0;function R(){return a({locateFile:i}).then(r=>n=r)}function s(r,m,l,y,x,E){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(E),!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 c=e.getImageBuffer();if(!c){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let d=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 p=new Uint8ClampedArray(c.byteLength);if(p.set(c),x){let o=new ImageData(p,d,f);createImageBitmap(o,0,0,d,f).then(u=>{self.postMessage({type:t.FRAME,crc:y,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:p.buffer,crc:y,width:d,height:f},[p.buffer])}R().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.crc,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return h;})();\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,t.crc)}else e(t.data,t.crc)},[Gr,Gr.getUrl])})}decodeFrame(e,t,i,r,a){let s="ImageBitmap"in window;this._sendToWorker(Se.FRAME,{timestamp:e,data:t.buffer,isVP9:i,crc:r,keyFrame:a,useImageBitmap:s,debug:c.enabled()},[t.buffer])}destroy(){this._removeWorker(),c.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var Ye=class extends xe{init(e){return o(this,null,function*(){c.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var i=Object.defineProperty;var E=e=>i(e,"__esModule",{value:!0});var g=(e,d)=>{E(e);for(var r in d)i(e,r,{get:d[r],enumerable:!0})};var y={};g(y,{default:()=>V});var s=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(s||{}),o=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(o||{});var V=()=>{let e=null,d=!0;function r(){self.postMessage({type:o.READY})}function l(a,p,t,m,u=!1){(!e||d!==t)&&(d=t,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${t?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${t?"VP9":"VP8"}`}),e=new VideoDecoder({output:c=>{("createImageBitmap"in c?c.createImageBitmap():createImageBitmap(c)).then(n=>{self.postMessage({type:o.FRAME,crc:m,data:n}),n.close()}).finally(()=>c.close())},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:t?s.VP9:s.VP8}));let f=new EncodedVideoChunk({type:u?"key":"delta",timestamp:a,data:p});e.decode(f)}self.onmessage=a=>{switch(a.data.type){case o.INIT:r();break;case o.FRAME:l(a.data.timestamp,a.data.data,a.data.isVP9,a.data.crc,a.data.keyFrame);break}}};return y;})();\n',t=>{t.error?c.warn("WebCod_createWorkerecsDecoder",t.error):e(t.data,t.crc)})})}decodeFrame(e,t,i,r,a=!1){this._sendToWorker(Se.FRAME,{timestamp:e,data:t.buffer,isVP9:i,crc:r,keyFrame:a},[t.buffer])}destroy(){this._removeWorker(),c.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window&&"ImageBitmap"in window&&"createImageBitmap"in window}};var ji=ur(Mi());import gn from"crc";var Ai="_okcls_",pt=(()=>{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 Na(n){let e=pt?pt.getItem(Ai+n):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function La(n,e){try{pt&&pt.setItem(Ai+n,JSON.stringify(e))}catch(t){}}function Ua(n){pt&&pt.removeItem(Ai+n)}var Di;(i=>{function n(r){return Na(r)||null}i.get=n;function e(r,a){La(r,a)}i.set=e;function t(r){Ua(r)}i.remove=t})(Di||(Di={}));var $e=Di;import Rt from"big-integer";function sn(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 on=n=>n.stop(),cn=n=>n.getTracks().forEach(on),wi=n=>n.getVideoTracks().forEach(on),dn=n=>n.getVideoTracks()[0].clone();var x=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(P).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,x)}};var Ce=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(Ce||{}),ge=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(ge||{}),Oi=class extends Q{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]){if(this._stream)return;let t=e.includes(he.VIDEO),i=e.includes(he.AUDIO);if(!y.isBrowserSupported())throw new x(ne.UNSUPPORTED);try{this._stream=yield y.getUserMedia(t,i),this._mediaSettings.isVideoEnabled=t&&this._stream.getVideoTracks().filter(r=>r.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=i&&this._stream.getAudioTracks().filter(r=>r.enabled).length>0||!1}catch(r){throw new x(r)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t=!1){let i=this.getStream(),r=this._getSendAudioTrack(),a=this.getSendVideoTrack(t);if(!i||!r&&!a)throw new Error("No local stream found");r&&e.addTrack(r,i),a&&e.addTrack(a,i)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return o(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return o(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=T.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);navigator.mediaDevices.addEventListener("devicechange",()=>o(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],a=r&&r.enabled&&r.getSettings(),s=a&&a.groupId,d=this._stream.getVideoTracks()[0],p=d&&d.enabled&&d.getSettings(),u=p&&p.groupId;if(!s&&!u)return;let _=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!_.find(f=>f.groupId===s)),!t&&u&&(t=!_.find(f=>f.groupId===u)),i()}))}_changeVideoInput(e=null){return o(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield y.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{l.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),a=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),m.log(g.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 m.log(g.ERROR,"change_video"),c.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=dn(e)),t=this._trackVideoStreamBackup.clone(),wi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),wi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return o(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return o(this,null,function*(){try{if(e=e||(yield y.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),m.log(g.DEVICE_CHANGED,"audio"),c.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(g.ERROR,"change_audio"),c.error("Microphone change failed",t),t}})}_changeScreen(e){return o(this,null,function*(){try{if(e=e||(yield y.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=l.consumerScreenTrack?t:yield this._videoEffect(null,t);m.log(g.DEVICE_CHANGED,"screen"),c.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,l.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=l.consumerScreenDataChannel?y.getBlackMediaTrack(l.videoMinWidth,l.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(g.ERROR,"screen"),c.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return o(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,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(!l.videoEffects)return t;try{return m.log(g.DEVICE_CHANGED,`effect_${e}`),l.videoEffects.setEffect(e,t)}catch(i){return c.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){l.videoEffects&&(this._effect=null,l.videoEffects.destroy()),this._stream&&(cn(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return o(this,null,function*(){return e?this._changeScreen():l.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return o(this,null,function*(){if(!this._stream)return;l.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield y.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=y.getBlackMediaTrack(l.videoMinWidth,l.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return o(this,null,function*(){if(!this._stream)return;let t;e?t=(yield y.getUserAudio()).getAudioTracks()[0]:t=y.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return o(this,null,function*(){if(!l.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:l.noiseSuppression})})}videoEffect(e){return o(this,null,function*(){if(!l.videoEffects)throw new Error("Video Effects library is not set");if(!l.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var ki;(sr=>{function n(C,R,M,b,w=!1){let Pe=/[\r\n]+/,X=`\r
|
|
8
|
+
`;if(!R&&!M&&!b)return w?U(C.split(Pe)).join(X):C;function U(z){let ke=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],me="a=rtcp-fb:111",oe=z.findIndex(ee=>ee.startsWith(me));return~oe&&(z[oe]=z[oe]+X+ke.join(X)),z}function Z(z,ke,me){let oe=z.split(" "),ee=oe.slice(0,3),ue;for(ue=3;ue<oe.length;ue++)me.includes(oe[ue])&&ee.push(oe[ue]);for(ue=3;ue<oe.length;ue++)!me.includes(oe[ue])&&!ke.includes(oe[ue])&&ee.push(oe[ue]);return ee.join(" ")}function A(z,ke){let me=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),oe,ee=[];for(oe=0;oe<z.length;++oe){let ue=z[oe].match(me);ue&&ue.length===3&&ue[2]===ke&&ee.push(ue[1])}return ee}function q(z,ke,me,oe){let ee,ue="m="+ke;for(ee=0;ee<z.length;++ee)if(z[ee].startsWith(ue)){z[ee]=Z(z[ee],me,oe);break}}let pe=[],D=C.split(Pe);(M||R)&&(pe=A(D,"H264"));let Fe=[];if(b&&(Fe=A(D,"VP9")),M){let z=pe.slice(0),ke=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),me;for(me=0;me<D.length;++me){let ee=D[me].match(ke);ee&&ee.length===3&&z.includes(ee[2])&&z.push(ee[1])}let oe=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(me=D.length;me--;){let ee=D[me].match(oe);ee&&ee.length===3&&z.includes(ee[2])&&D.splice(me,1)}q(D,"video",z,[])}else R&&q(D,"video",[],pe);return b&&q(D,"video",[],Fe),w&&U(D),D.join(X)}sr.patchSDP=n;function e(C){return C?`${C.type||"WEB_SOCKET"}_${C.id}`:"_"}sr.getPeerIdString=e;function t(C,R){return C&&C.id===R.id&&(C.type||"WEB_SOCKET")===(R.type||"WEB_SOCKET")}sr.comparePeerId=t;function i(C){return o(this,null,function*(){return!C||!C.getStats?Promise.resolve(null):C.getStats(null).then(R=>{let M=null,b=null;if(R.forEach(w=>{w.type==="transport"&&w.selectedCandidatePairId?b=R.get(w.selectedCandidatePairId):w.type==="candidate-pair"&&w.state==="succeeded"&&!b&&(!w.hasOwnProperty("selected")||w.selected)&&(b=w)}),b&&b.localCandidateId){let w=R.get(b.localCandidateId);w&&(M={type:w.candidateType,ip:w.ip||w.ipAddress,port:w.port||w.portNumber})}return M}).catch(()=>null)})}sr.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,a=/^([gu])([0-9]+)$/;function s(C,R){let M=String(C);return a.test(M)?(c.warn(`Already composite id [${C}] type supplied [${R}]`),M):R===te.GROUP?"g"+M:R===te.USER?"u"+M:(c.warn(`Unknown type [${R}] for id [${C}]`),M.match(r)?"u"+M:M)}sr.composeId=s;function d(C){return s(C.id,C.idType||te.USER)}sr.composeParticipantId=d;function p(C){return C.participant?d(C.participant):s(C.participantId,C.participantType||te.USER)}sr.composeMessageId=p;function u(C){let R=String(C),M=R.match(a);return M?{id:Number(M[2]),type:M[1]==="g"?te.GROUP:te.USER}:(c.warn(`Unsupported compositeId [${C}]`),{id:Number(R),type:te.USER})}sr.decomposeId=u;function _(){let C="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),R=new Array(36),M=0,b,w;for(w=0;w<36;w++)w===8||w===13||w===18||w===23?R[w]="-":w===14?R[w]="4":(M<=2&&(M=33554432+Math.random()*16777216|0),b=M&15,M=M>>4,R[w]=C[w===19?b&3|8:b]);return R.join("")}sr.uuid=_;function f(C,R){let M;function b(){let w=this,Pe=arguments;M&&window.clearTimeout(M),M=window.setTimeout(()=>{C.apply(w,Pe)},R)}return b}sr.throttle=f;function W(C){let R="",M=C.split(`
|
|
9
|
+
`);for(let X of M)if(X.startsWith("a=fingerprint")){let U=X.split(" ");if(U.length===2){R=U[1];break}}if(!R)return Rt.minusOne;let b=R.split(":"),w=Rt.zero;for(let X=Math.min(7,b.length-1);X>=0;X--){let U=Rt(b[X],16);w=w.shiftLeft(8).or(U)}return((X,U)=>{let Z=U.value;if(typeof Z=="bigint")return Rt(BigInt.asIntN(X,Z));let A=Rt.one.shiftLeft(X),q=U.and(A.subtract(1));return q.greaterOrEquals(A.subtract(q))?q.subtract(A):q})(64,w)}sr.sdpFingerprint=W;function K(C){return o(this,null,function*(){return new Promise(R=>window.setTimeout(R,C))})}sr.delay=K;function O(C,R,M){let b=[];return C.getSenders().forEach(w=>J(R,w,w.track,M,b)),b}sr.applySettings=O;function J(C,R,M,b,w){if(C&&M&&M.kind===ge.video){let Pe=M.getSettings();if(Pe){let X=C.maxBitrateK?C.maxBitrateK*1024:null,U=Pe.width,Z=Pe.height,A=U&&Z&&C.maxDimension?Math.max(1,Math.max(U,Z)/C.maxDimension):null,q=C.maxFramerate?C.maxFramerate:null,pe=C.degradationPreference?C.degradationPreference:"balanced",D=b[M.id];if(D&&D.bitrate===X&&D.scaleResolutionDownBy===A&&D.maxFramerate===q&&D.degradationPreference===pe){w[M.id]=D;return}w[M.id]={bitrate:X,scaleResolutionDownBy:A,maxFramerate:q,degradationPreference:pe};let Fe=R.getParameters();Fe.encodings||(Fe.encodings=[{}]),Fe.encodings.forEach(z=>{X?z.maxBitrate=X:delete z.maxBitrate,A?z.scaleResolutionDownBy=A:delete z.scaleResolutionDownBy,q?z.maxFramerate=q:delete z.maxFramerate}),Fe.degradationPreference=pe,R.setParameters(Fe)}}}sr.applyVideoTrackSettings=J;function se(C,R){Array.isArray(R)||(R=[R]);for(let M of R)if(C.includes(M))return!0;return!1}sr.includesOneOf=se;function ce(C){var R;return Object.entries(((R=C.participantState)==null?void 0:R.state)||{}).reduce((M,[b,w])=>(C.participantState&&(M[b]={ts:C.participantState.stateUpdateTs[b],state:w}),M),{})}sr.mapParticipantState=ce;function at(C){return Object.entries(C).reduce((R,[M,{state:b}])=>(R[M]=b,R),{})}sr.mapLegacyParticipantState=at;function le(C){return C.map(R=>{let M={uid:R.externalId,mediaSettings:R.mediaSettings,status:R.status,muteStates:R.muteStates,unmuteOptions:R.unmuteOptions};return l.participantStateMapped&&(M.participantState=R.participantState),M})}sr.mapSharedParticipants=le;function $(C,R){let M=Object.keys(C),b=Object.keys(R);if(M.length!==b.length)return!1;for(let w of M)if(!b.hasOwnProperty(w)||C[w].state!==R[w].state||C[w].ts!==R[w].ts)return!1;return!0}sr.isEqualParticipantState=$;function we(C,R){let M=Object.keys(C),b=Object.keys(R);if(M.length!==b.length)return!1;for(let w of M)if(!R.hasOwnProperty(w)||C[w]!==R[w])return!1;return!0}sr.isObjectsEquals=we;function St(C,R){if(C.length!==R.length)return!1;for(let M of C)if(R.indexOf(M)<0)return!1;return!0}sr.isArraysEquals=St;function ar(C){return!Object.keys(C).length}sr.isEmptyObject=ar})(ki||(ki={}));var T=ki;var Xe=null,xi=null,Wt=[],jt=[],Ni=[],bt=null,Pt=null,Li=null,Ui=!1,Bi=!1,Kt,lt,$t,pn=!1,ln=!1,Fi=null,Vi="",qt=[],Hi=null,un=navigator.appVersion,Ba=navigator.appName,Ie=navigator.userAgent,hn=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(hn||{}),Mt=class{constructor(e,t=!1,i=l.videoMaxWidth,r=l.videoMaxHeight){let a=!1;if(e){a={noiseSuppression:l.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let d;Pt&&(d=Pt.deviceId),typeof e=="string"&&(d=e),d&&(a.deviceId={exact:d})}let s=!1;if(t){s={width:{min:l.videoMinWidth,max:i,ideal:i},height:{min:l.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:l.videoAspectRatio},frameRate:{ideal:l.videoFrameRate}};let d;bt&&(d=bt.deviceId),typeof t=="string"&&(d=t),d&&(s.deviceId={exact:d}),l.videoFacingMode&&(s.facingMode={exact:l.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}},mn=class extends Mt{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=l.screenFrameRate}};function Fa(){return o(this,null,function*(){Xe=null,yield Jt()})}function Va(){Xe=null,Jt().then(()=>E.onDeviceChange())}function Jt(){return o(this,null,function*(){return Xe||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!xi&&navigator.mediaDevices.addEventListener&&(xi=T.throttle(Va,1e3),navigator.mediaDevices.addEventListener("devicechange",xi)),Xe=navigator.mediaDevices.enumerateDevices().then(n=>{Wt=n.filter(r=>r.kind==="videoinput"?(r.label&&(Ui=!0),!0):!1),jt=n.filter(r=>r.kind==="audioinput"?(r.label?Bi=!0:Ze.isMobile()&&Ze.browserName()==="Firefox"&&(Bi=Ui),!0):!1),Ni=n.filter(r=>r.kind==="audiooutput");let e=$e.get("videoinput"),t=$e.get("audioinput"),i=$e.get("audiooutput");return bt=Wt.find(r=>r.deviceId===e)||null,Pt=jt.find(r=>r.deviceId===t)||null,Li=Ni.find(r=>r.deviceId===i)||null,Xe=Promise.resolve(n),n}).catch(()=>(Xe=null,[]))))})}function Ha(){return o(this,null,function*(){return Ze.isBrowserSupported()?new Promise(n=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(pn=!0),/^a=mid:0$/m.test(t.sdp)&&(ln=!0),n()}).catch(n)}):Promise.resolve()})}function Yt(n,e){return o(this,null,function*(){c.debug("Try to get media",n.getNative());let t=Ze.hasPermissions(n.isVideo());!t&&!e&&E.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(n.getNative());return t||(yield Fa()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=n.isVideo()?ne.CAMERA_PERMISSION:ne.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=n.isVideo()?ne.CAMERA_ACCESS:ne.MIC_ACCESS;break}if(n.canSimplify())return Yt(n.simplify(),e);let r=e||ne.UNKNOWN;throw E.onPermissionsError(r),r}})}function Ga(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 ne.SCREEN_PERMISSION;default:throw ne.SCREEN_ACCESS}}})}function Gi(){return qt.length||(qt=(()=>{let n,e=!1,t=0,i=Ie.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return n=/\brv[ :]+(\d+)/g.exec(Ie),["IE",n&&n[1]||"Unknown",e,t];if(i[1]==="Safari"){if(n=Ie.match(/\bEdge\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t];if(n=Ie.match(/\bCriOS\/(\d+)/),n)return["Chrome",n[1],!0,n[1]];if(n=Ie.match(/\bFxiOS\/(\d+)/),n)return["Firefox",n[1],!1,t];if(n=Ie.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1],!1,t];if(n=Ie.match(/\bOPT\/(\d+)/),n)return["Opera",n[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),n=Ie.match(/\bOPR\/(\d+)/),n)return["Opera",n[1]||"Unknown",e,t];if(n=Ie.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1]||"Unknown",e,t];if(n=Ie.match(/\bSferum\/((\d+)(?:\.\d+)*)/),n)return["Sferum",n[1]||"Unknown",e,t];if(n=Ie.match(/\bEdge?\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t]}return n=Ie.match(/version\/(\d+)/i),[i[2]?i[1]:Ba,n&&n[1]||i[2]||un,e,t]})()),qt}var Ze;(X=>{function n(){return o(this,null,function*(){return yield Ha(),Jt()})}X.init=n;function e(){return Wt}X.getCameras=e;function t(){return jt}X.getMicrophones=t;function i(){return Ni}X.getOutput=i;function r(){return Wt.length>0}X.hasCamera=r;function a(){return jt.length>0}X.hasMicrophone=a;function s(){return bt}X.getSavedCamera=s;function d(){return Pt}X.getSavedMicrophone=d;function p(){return Li}X.getSavedOutput=p;function u(){return Ui}X.hasCameraPermission=u;function _(){return Bi}X.hasMicrophonePermission=_;function f(U=!1){return _()?r()&&U?u():!0:!1}X.hasPermissions=f;function W(U=!1,Z=!0){return o(this,null,function*(){let A=a()&&Z,q=r()&&U,pe;if(!A&&!q)pe=new MediaStream;else try{pe=yield Yt(new Mt(A,q))}catch(D){pe=new MediaStream}return pe.getVideoTracks().length||pe.addTrack(at()),pe.getAudioTracks().length||pe.addTrack(ce()),pe})}X.getUserMedia=W;function K(){return o(this,null,function*(){return Ga(new mn(window.screen.width,window.screen.height))})}X.getScreenMedia=K;function O(U,Z=!1){return o(this,null,function*(){let A=Z?l.videoEffectMaxWidth:l.videoMaxWidth,q=Z?l.videoEffectMaxHeight:l.videoMaxHeight;return Yt(new Mt(!1,U||!0,A,q))})}X.getUserVideo=O;function J(U){return o(this,null,function*(){return Yt(new Mt(U||!0,!1))})}X.getUserAudio=J;function se(U,Z){return o(this,null,function*(){let q=(yield Jt()).find(pe=>pe.kind===U&&pe.deviceId===Z);return q?(U==="videoinput"?bt=q:U==="audioinput"?Pt=q:U==="audiooutput"&&(Li=q),$e.set(U,Z),q):null})}X.saveDeviceId=se;function ce(){if(!$t||$t.readyState==="ended"){let U=Pe(),Z=U.createMediaStreamDestination(),A=U.createGain();A.gain.value=1e-5,A.connect(Z),A.connect(U.destination);let q=U.createOscillator();q.type="sine",q.frequency.value=0,q.connect(A),q.start(),$t=Z.stream.getAudioTracks()[0]}return Object.assign($t.clone(),{enabled:!1})}X.getSilentMediaTrack=ce;function at(U=l.videoMinWidth,Z=l.videoMinHeight){return lt||(lt=document.createElement("canvas"),lt.getContext("2d")),lt.width=U,lt.height=Z,(!Kt||Kt.readyState==="ended")&&(Kt=lt.captureStream(l.videoFrameRate).getVideoTracks()[0]),Object.assign(Kt.clone(),{enabled:!1})}X.getBlackMediaTrack=at;function le(){if(M()==="Edge"&&b()<70)return!1;try{let U=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&U.RTCPeerConnection&&U.RTCIceCandidate&&U.RTCSessionDescription&&U.HTMLCanvasElement&&U.HTMLCanvasElement.prototype.captureStream&&U.RTCRtpSender&&U.RTCRtpSender.prototype.replaceTrack&&U.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(U){return!1}}X.isBrowserSupported=le;function $(){return!!navigator.mediaDevices.getDisplayMedia}X.isScreenCapturingSupported=$;function we(){return pn}X.canVP8=we;function St(){return ln}X.isUnifiedPlan=St;function ar(){return X.browserName()==="Opera"&&X.os()==="Windows"}X.isBrokenH264=ar;function sr(){return!(X.baseChromeVersion()&&X.isMobile())}X.canPreferH264=sr;function C(){return Vi||(Vi=(()=>{let U={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 U)if(U.hasOwnProperty(Z)&&U[Z].test(Ie))return Z;return"Unknown"})()),Vi}X.os=C;function R(){return Fi===null&&(Fi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(un)),Fi}X.isMobile=R;function M(){return Gi()[0]}X.browserName=M;function b(){return Gi()[1]}X.browserVersion=b;function w(){return Gi()[3]}X.baseChromeVersion=w;function Pe(){return Hi||(Hi=new(window.AudioContext||window.webkitAudioContext)),Hi}X.getAudioContext=Pe})(Ze||(Ze={}));var y=Ze;var Wi=ur(Mi());import{BitStream as Wa}from"bit-buffer";import _n from"crc";var ja=65536,et=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(c.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%ja!==e.sequence){c.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:a}=et.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((d,p)=>d+p.data.byteLength,0),i=new Uint8Array(t),r=[],a=0;for(let d of e)r.push(_n.crc32(Wi.default.Buffer.from(d.data)).toFixed()),i.set(new Uint8Array(d.data),a),a+=d.data.byteLength;let s=_n.crc32(Wi.default.Buffer.from(i)).toFixed();return c.debug("processed screenshare frame data",s,r),i}static getFrameSize(e){let t={width:0,height:0},i=new Wa(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 At=class extends et{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;c.debug(`StreamBuilder started for participant [${e}]`),this._useImageBitmap="ImageBitmap"in window,Ye.isBrowserSupported()?this._decoder=new Ye:this._decoder=new ot,this._decoder.init((i,r)=>this._drawImage(i,r)).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}_drawImage(e,t){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let i=this._canvas;if(i.width=e.width,i.height=e.height,e instanceof ImageData){let r=this._canvasContext;r.clearRect(0,0,i.width,i.height),r.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}_processFrame(e){if(!this._decoderReady||this._decoderQueue.length)this._decoderQueue.push(e),this._decodeQueue();else{let t=gn.crc32(ji.default.Buffer.from(e.frameData)).toFixed();this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,t,e.keyframe)}}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{let i=gn.crc32(ji.default.Buffer.from(t.frameData)).toFixed();this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,i,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._removeStream(),c.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(y.browserName()==="Safari"&&y.browserVersion()>=15)}};var zt=1,Ka=1,fn=0,Sn=11,vn=1,En=2,Tn=4,Cn=8;function In(n,e,t,i,r,a,s){let d=0;e&&(d|=vn),t&&(d|=En),i&&(d|=Tn),s||(d|=Cn);let p=new ArrayBuffer(Sn),u=new DataView(p);if(u.setUint8(0,zt),u.setUint16(1,r),u.setUint32(3,n),u.setUint8(7,a?1:0),u.setUint16(8,fn),u.setUint8(10,d),!s)return p;let _=new Uint8Array(p.byteLength+s.byteLength);return _.set(new Uint8Array(p),0),_.set(new Uint8Array(s),p.byteLength),_.buffer}function yn(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),d=e.getUint8(10),p=!!(d&vn),u=!!(d&En),_=!!(d&Tn),f=!!(d&Cn);if(t!==zt)throw new Error(`Unexpected protocol version. Got ${t}, expected ${zt}`);return{timestamp:r,start:p,end:u,keyframe:_,sequence:i,isVP9:a,ssrc:s,eos:f,data:n.slice(Sn)}}function Rn(n){if(!n||!n.byteLength||n.byteLength!==4)return!1;let e=new DataView(n);return!(e.getUint8(0)!==zt||e.getUint8(1)!==Ka||e.getUint16(2)!==fn)}import*as S from"simple-ebml-builder";var $a=dr(2,15)-1,Ki=1,qa=5,Ja=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 S.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=S.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;let e=(a=this._sourceBuffer)==null?void 0:a.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-qa);r-i>Ja&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},We=class extends et{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;c.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return 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"))]),a=[S.element(S.ID.PixelWidth,S.number(e)),S.element(S.ID.PixelHeight,S.number(t))],s=S.element(S.ID.Tracks,S.element(S.ID.TrackEntry,[S.element(S.ID.TrackNumber,S.number(Ki)),S.element(S.ID.TrackUID,S.number(Ki)),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,a)]));return S.unknownSizeElement(S.ID.Segment,[r,s])}static _genClusterHeader(e){return S.unknownSizeElement(S.ID.Cluster,[S.element(S.ID.Timecode,S.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new 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,c.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=We._genWebmHeader();this._mediaBuffer.append(s);let d=We._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(d),this._mediaBuffer.cleanup()}let r=Math.round(i-this._clusterStartTime);if(r>$a&&(this._clusterStartTime=i,r=0),r===0){c.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=We._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let a=S.element(S.ID.SimpleBlock,[S.vintEncodedNumber(Ki),S.bytes(We._intToU16BE(r)),S.number((e.keyframe?1:0)<<7),S.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 tt=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};this._parts=[];this._lastChunk=0;c.debug("ScreenCaptureReceiver started"),e instanceof RTCDataChannel?(this._datachannel=e,this._datachannel.onmessage=a=>this._onDataChannelMessage(a.data)):this._replay(e),this._participantIdRegistry=t,this._onStream=i,this._onEos=r}_replay(e){return o(this,null,function*(){let t=yield e.arrayBuffer(),i=new DataView(t),r=0;for(;r<i.byteLength;){let a=this._readUint32(i,r);yield this._sleep(a);let s=this._readUint32(i,r+=4),d=t.slice(r+=4,r+=s);this._onDataChannelMessage(d)}})}_sleep(e){return o(this,null,function*(){return new Promise((t,i)=>{setTimeout(()=>{t()},e)})})}_readUint32(e,t){return e.getUint8(t)+(e.getUint8(t+1)<<8)+(e.getUint8(t+2)<<16)+(e.getUint8(t+3)<<24)}_onDataChannelMessage(e){var a,s;if(c.debug("Received "+e.byteLength+" bytes of screenshare data"),this._datachannel){let d=new Date().getTime(),p=this._lastChunk?d-this._lastChunk:0;this._lastChunk=d,this._parts.push(new Uint32Array([p,e.byteLength])),this._parts.push(new Uint8Array(e))}let t=yn(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){if(this.close(i),this._onEos(i),this._lastChunk){let d=new Date().toISOString().replace(/:/g,"-").replace(/.\d+Z/,"").replace("T","_");bn(new Blob(this._parts),"screenshare-"+i+"-"+d+".dat"),this._parts=[],this._lastChunk=0}return}let r=this._streamBuilders[i];if(!r){let d=p=>this._onStream(i,p);r=new At(i,d),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){if(this._lastChunk){let e=new Date().toISOString().replace(/:/g,"-").replace(/.\d+Z/,"").replace("T","_");bn(new Blob(this._parts),"screenshare-"+e+".dat"),this._parts=[],this._lastChunk=0}this._datachannel&&(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(Ye.isBrowserSupported()||ot.isBrowserSupported())&&(At.isBrowserSupported()||We.isBrowserSupported())}};import Pn from"@vkontakte/libvpx";var Ya=1e3,Dt=class extends xe{constructor(e,t){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return o(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=d=>t(),r.onerror=()=>i(new Error("Video element error"));let 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})},[Pn,Pn.getUrl],{isVP9:this.isVP9(),debug:c.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(Se.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(),c.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var ut=class extends xe{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return o(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;c.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var b=Object.defineProperty;var g=i=>b(i,"__esModule",{value:!0});var F=(i,n)=>{g(i);for(var r in n)b(i,r,{get:n[r],enumerable:!0})};var A={};F(A,{default:()=>h});var l=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(l||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,n,r,c,s,f,t,a=null,p=0,u=!1;function V(e){n=e.readable,r=n.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&E(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),n.cancel();return}a=R,E(R,e)}}))}function E(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
|
|
11
|
+
`,r=>{var 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:l.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(Se.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 za=16*1024,Qa=11,Mn=za-Qa,Xa=65536,$i=0,ht=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 Dt(e,i),this._datachannel.onmessage=r=>{Rn(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=In(e,t,i,r,$i,this._encoder.isVP9(),a);return $i=($i+1)%Xa,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+Mn),s=e.data.byteLength<=t+a.byteLength,d=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(d)}catch(p){c.warn("Error send data to DataChannel",p),r();return}s||window.setTimeout(()=>this._sendChunk(e,t+Mn,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()||Dt.isBrowserSupported()}};var ie=class{static get sessionKey(){return ie._sessionKey}static set sessionKey(e){ie._sessionKey=e}static get sessionSecretKey(){return ie._sessionSecretKey}static set sessionSecretKey(e){ie._sessionSecretKey=e}static get accessToken(){return ie._accessToken}static set accessToken(e){ie._accessToken=e}static isEmpty(){return!ie._sessionKey||!ie._sessionSecretKey}};var v=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(v._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(v._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(v._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(ie.accessToken=e.apiAuth.accessToken,ie.sessionKey=e.apiAuth.sessionKey,ie.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(v._params,e)}static get(e){return v._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.5.2-dev.75f890a.0"}static get debug(){return!1}static get protocolVersion(){return 5}static get platform(){return v._params.platform}static set platform(e){v._params.platform=e}static get clientType(){return v._params.clientType}static set clientType(e){v._params.clientType=e}static get device(){return v._params.device}static get apiAppId(){return 42}static get apiKey(){return v._params.apiKey}static get apiEnv(){return v._params.apiEnv}static get apiEndpoint(){switch(v.apiEnv){case"AUTO":case"PROD":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return v._params.apiEnv}}static get authToken(){return v._params.authToken}static set authToken(e){v._params.authToken=e}static get anonymToken(){return v._params.anonymToken}static set anonymToken(e){v._params.anonymToken=e}static get domain(){return v._params.domain}static get iceServers(){return v._params.iceServers}static set iceServers(e){v._params.iceServers=e}static get wssBase(){return v._params.wssBase}static set wssBase(e){v._params.wssBase=e}static get wssToken(){return v._params.wssToken}static set wssToken(e){v._params.wssToken=e}static get signalingReconnectDelay(){return v._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return v._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return v._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return v._params.waitConnectionDelay}static get waitResponseDelay(){return v._params.waitResponseDelay}static get waitMessageDelay(){return v._params.waitMessageDelay}static get debugLog(){return v._params.debugLog}static get forceRelayPolicy(){return v._params.forceRelayPolicy}static set forceRelayPolicy(e){v._params.forceRelayPolicy=e}static get videoMinWidth(){return v._params.videoMinWidth}static get videoMaxWidth(){return v._params.videoMaxWidth}static set videoMaxWidth(e){v._params.videoMaxWidth=e}static get videoMinHeight(){return v._params.videoMinHeight}static get videoMaxHeight(){return v._params.videoMaxHeight}static set videoMaxHeight(e){v._params.videoMaxHeight=e}static get videoAspectRatio(){return v._params.videoAspectRatio}static get videoFrameRate(){return v._params.videoFrameRate}static get videoFacingMode(){return v._params.videoFacingMode}static get screenFrameRate(){return v._params.screenFrameRate}static get videoEffects(){return v._params.videoEffects}static set videoEffects(e){v._params.videoEffects=e}static get videoEffectMaxWidth(){return v._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){v._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return v._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){v._params.videoEffectMaxHeight=e}static get voiceParams(){return v._params.voiceParams}static get specListenerParams(){return v._params.specListenerParams}static get iceRestartWaitTime(){return v._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return v._params.transportConnectionWaitTime}static get statisticsInterval(){return v._params.statisticsInterval}static set statisticsInterval(e){v._params.statisticsInterval=e}static get networkStatisticsInterval(){return v._params.networkStatisticsInterval}static get perfStatReportEnabled(){return v._params.perfStatReportEnabled}static get callStatReportEnabled(){return v._params.callStatReportEnabled}static get producerNotificationDataChannel(){return v._params.producerNotificationDataChannel&&tt.isBrowserSupported()}static get producerCommandDataChannel(){return v._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return v._params.consumerScreenDataChannel&&ht.isBrowserSupported()}static get producerScreenDataChannel(){return v._params.producerScreenDataChannel&&v.producerNotificationDataChannel}static get screenShareWebmBuilder(){return v._params.screenShareWebmBuilder}static get noiseSuppression(){return v._params.noiseSuppression}static set noiseSuppression(e){v._params.noiseSuppression=e}static get preferH264(){return v._params.preferH264}static get preferVP9(){return v._params.preferVP9}static get audioNack(){return v._params.audioNack}static get consumerScreenTrack(){return v._params.consumerScreenTrack&&v.consumerScreenDataChannel}static get producerScreenTrack(){return v._params.producerScreenTrack&&v.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=v._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return v._params.movieShare&&v.videoTracksCount>0}static get videoTracksCount(){return v.producerNotificationDataChannel?v._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return v._params.breakVideoPayloadTypes}static get filteredMessages(){return v._params.filteredMessages}static get batchParticipantsOnStart(){return v._params.batchParticipantsOnStart}static get participantStateMapped(){return v._params.participantStateMapped}},l=v;l._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,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:!1,producerScreenTrack:!1,videoTracksCount:0,movieShare:!1,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!1};var Y=(p=>(p.WAITING_HALL="WAITING_HALL",p.WAITING="WAITING",p.CONNECTING="CONNECTING",p.CONNECTED="CONNECTED",p.RECONNECT="RECONNECT",p.ERROR="ERROR",p.HANGUP="HANGUP",p.PERMISSIONS="PERMISSIONS",p))(Y||{});function V(n,...e){let t=l.get(n);t&&setTimeout(t,0,...e)}function Ue(n){return Object.assign({},n)}function mt(n){return n.slice()}var qi;(ue=>{function n(I,B){V("onLocalStream",I,Ue(B))}ue.onLocalStream=n;function e(I,B){V("onScreenStream",I,Ue(B))}ue.onScreenStream=e;function t(I,B){V("onLocalStreamUpdate",Ue(I),B)}ue.onLocalStreamUpdate=t;function i(I){V("onLocalStatus",I)}ue.onLocalStatus=i;function r(I,B){V("onRemoteStream",I,B)}ue.onRemoteStream=r;function a(I,B,de){V("onRemoteLive",I,B,de)}ue.onRemoteLive=a;function s(I,B){V("onRemoteScreenStream",I,B)}ue.onRemoteScreenStream=s;function d(I,B,de,vt){V("onConversation",I,Ue(B),Ue(de),vt)}ue.onConversation=d;function p(I,B){V("onRemoteMediaSettings",I,Ue(B))}ue.onRemoteMediaSettings=p;function u(I,B){V("onRemoteParticipantState",I,Ue(B))}ue.onRemoteParticipantState=u;function _(I,B,de=null){V("onRemoteStatus",I,B,de)}ue.onRemoteStatus=_;function f(I,B,de=null){V("onParticipantStatus",I,B,de)}ue.onParticipantStatus=f;function W(){V("onPermissionsRequested")}ue.onPermissionsRequested=W;function K(I){V("onPermissionsError",I)}ue.onPermissionsError=K;function O(I){V("onRemoteRemoved",I)}ue.onRemoteRemoved=O;function J(I,B,de){V("onCallState",I,B,Ue(de))}ue.onCallState=J;function se(I,B){V("onDeviceSwitched",I,B)}ue.onDeviceSwitched=se;function ce(I,B,de,vt=!1,ci=!1,di=null,Kn=null){V("onMuteStates",Ue(I),mt(B),mt(de),vt,ci,di,Kn)}ue.onMuteStates=ce;function at(I,B){V("onRolesChanged",I,mt(B))}ue.onRolesChanged=at;function le(I){V("onLocalRolesChanged",mt(I))}ue.onLocalRolesChanged=le;function $(I,B){V("onPinnedParticipant",I,B)}ue.onPinnedParticipant=$;function we(I){V("onLocalPin",I)}ue.onLocalPin=we;function St(I){V("onOptionsChanged",mt(I))}ue.onOptionsChanged=St;function ar(){V("onCallAccepted")}ue.onCallAccepted=ar;function sr(){V("onRateNeeded")}ue.onRateNeeded=sr;function C(I){V("onSpeakerChanged",I)}ue.onSpeakerChanged=C;function R(I){V("onVolumesDetected",mt(I))}ue.onVolumesDetected=R;function M(I,B){V("onLocalVolume",I,B)}ue.onLocalVolume=M;function b(I,B){V("onJoinStatus",I,B)}ue.onJoinStatus=b;function w(I,B){V("onHangup",I,B)}ue.onHangup=w;function Pe(I){V("onMultipartyChatCreated",Ue(I))}ue.onMultipartyChatCreated=Pe;function X(){V("onDeviceChange")}ue.onDeviceChange=X;function U(I){V("onFingerprintChange",I)}ue.onFingerprintChange=U;function Z(){V("onTokenExpired")}ue.onTokenExpired=Z;function A(I,B,de=!1){V("onChatMessage",I,B,de)}ue.onChatMessage=A;function q(I,B,de=!1){V("onCustomData",I,B,de)}ue.onCustomData=q;function pe(I,B,de,vt,ci,di){V("onRecordStarted",I,B,de,vt,ci,di)}ue.onRecordStarted=pe;function D(){V("onRecordStopped")}ue.onRecordStopped=D;function Fe(I){V("onLocalNetworkStatusChanged",I)}ue.onLocalNetworkStatusChanged=Fe;function z(I){V("onNetworkStatusChanged",I)}ue.onNetworkStatusChanged=z;function ke(I,...B){V("onDebugMessage",I,...B)}ue.onDebugMessage=ke;function me(I,B){let de=Object.assign({},I,{memory:B});V("onStatistics",de)}ue.onStatistics=me;function oe(){V("onAutoplayError")}ue.onAutoplayError=oe;function ee(I,B,de){V("onChatRoomUpdated",I,B,de)}ue.onChatRoomUpdated=ee})(qi||(qi={}));var E=qi;var An=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(An||{}),Ji;(le=>{let n="📞",e=($,...we)=>{E.onDebugMessage($,...we)},t=!1,i=($,we)=>(...St)=>{$(...St),Hr(we,St)},r=console.debug.bind(console,n),a=console.log.bind(console,n),s=console.warn.bind(console,n),d=console.error.bind(console,n),p=e.bind(null,"DEBUG"),u=e.bind(null,"LOG"),_=e.bind(null,"WARN"),f=e.bind(null,"ERROR");le.debug=p,le.log=u,le.warn=_,le.error=f;function se(){return t}le.enabled=se;function ce($){t=$,l.debugLog&&fi(),$?(le.debug=l.debugLog?i(r,"DEBUG"):r,le.log=l.debugLog?i(a,"LOG"):a,le.warn=l.debugLog?i(s,"WARN"):s,le.error=l.debugLog?i(d,"ERROR"):d):(le.debug=l.debugLog?i(p,"DEBUG"):p,le.log=l.debugLog?i(u,"LOG"):u,le.warn=l.debugLog?i(_,"WARN"):_,le.error=l.debugLog?i(f,"ERROR"):f)}le.toggle=ce;function at($,...we){switch($){case"DEBUG":le.debug(...we);break;case"LOG":le.log(...we);break;case"WARN":le.warn(...we);break;case"ERROR":le.error(...we);break}}le.send=at})(Ji||(Ji={}));var c=Ji;var _t=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(_t||{}),re;(d=>{function n(p){return p.length?typeof p[0]=="object"?p:p.map(u=>e(u)):[]}d.fromIds=n;function e(p,u="USER"){return{id:p,type:u}}d.fromId=e;function t(p){return{id:p.id,type:p.type==="ANONYM"?"ANONYM":"USER"}}d.fromSignaling=t;function i(p){return`{"id":"${p.id}","type":"${p.type}"}`}d.toString=i;function r(p,u="USER"){return i(e(p,u))}d.fromIdToString=r;function a(p){try{return JSON.parse(p)}catch(u){throw new Error(`Failed to parse ExternalId from string '${p}'`)}}d.fromString=a;function s(p,u){return p.id===u.id&&p.type===u.type}d.compare=s})(re||(re={}));var ye=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(ye||{}),Yi=":",Dn="s",wn="m";function it(n){return n.participantId+(n.mediaType?Yi+Dn+n.mediaType:"")+(n.streamName?Yi+wn+n.streamName:"")}function wt(n){let e=n.split(Yi),t=e.shift();if(!t)throw new Error("Illegal stream description: "+n);let i={participantId:t,mediaType:null};for(let r of e)switch(r.charAt(0)){case Dn:i.mediaType=Za(r.slice(1));break;case wn:i.streamName=r.slice(1);break;default:throw new Error("Unexpected parameter type "+r.charAt(0)+" in stream description "+n)}return i}function Za(n){for(let e of Object.keys(ye))if(e===n)return ye[e];return null}function zi(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 Xt(n,e){return!(!zi(n.camera,e.camera)||!zi(n.screenSharing,e.screenSharing))}function Qi(n,e){return{camera:Object.assign({},n.camera,e.camera),screenSharing:Object.assign({},n.screenSharing,e.screenSharing)}}function On(n){try{return btoa(JSON.stringify(n))}catch(e){c.warn("WaitingParticipant: failed convert to string",n,e)}return null}function kn(n){try{return JSON.parse(atob(n))}catch(e){c.warn("WaitingParticipant: failed convert from string",n,e)}return null}var Ot=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,m.log(g.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,m.log(g.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(c.log("Failed to fix RV"),m.log(g.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),m.log(g.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,c.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===ge.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Zt=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(!((s=this._output)==null?void 0:s.audioTrack))return;let e=y.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{c.warn("Error on play audio"),E.onAutoplayError()},r=d=>{t.srcObject=new MediaStream([d]),t.load();let p=t.play();p?p.catch(i):i()},a=()=>{var p;c.debug("Recover audio playback");let d=(p=this._output)==null?void 0:p.audioTrack;d?r(d):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=y.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw m.log(g.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var es=90,ts=3,ei=class extends Q{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),E.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>es?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=ts)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var is=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=y.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=is/this._fftBins.length,t=Math.ceil(l.voiceParams.minFreq/e),i=Math.floor(l.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*l.voiceParams.smoothing+i*(1-l.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 ti=class extends Q{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&E.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,l.voiceParams.interval)};this._interval=window.setTimeout(t,l.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,Ce.SOURCE_CHANGED,r=>{r.kind===ge.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 rs=1e3;function Re(n,e,t=0){return e in n&&n[e]?n[e]:t}function xn(...n){return e=>{for(let t of n)if(t(e))return!0;return!1}}function qe(n,e){return t=>t[n]===e}function ns(n){return(e,t)=>e[n]-t[n]}function ii(n,e){return e.reduce((t,i)=>(t[i[n]]=i,t),{})}function as(n){let e={},t=[];for(let i of n)e[i.id]||(e[i.id]=!0,t.push(i));return t}function ss(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]]=ss(t[1])?Xi(t[1]):t[1],e),{})}function os(n){let e=[];for(let t of n)t.forEach(i=>e.push(i));return e}function cs(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(os).then(as)})}function ds(n){let e=n.filter(qe("type","candidate-pair")).sort(ns("priority")).find(xn(qe("nominated",!0),qe("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(qe("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(qe("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 ps(n,e){let t=ii("id",n),i=n.filter(xn(qe("type","inbound-rtp"),qe("type","outbound-rtp")));y.browserName()==="Firefox"&&(i=Object.values(i.reduce((a,s)=>{if(!a[s.ssrc])a[s.ssrc]=s;else{let d=Object.assign({},a[s.ssrc],s),p=a[s.ssrc].isRemote?s:a[s.ssrc];d.id=p.id,d.type=p.type,delete d.isRemote,delete d.remoteId,a[d.ssrc]=d}return a},{})));let r={};if(y.browserName()==="Safari"){let a=n.filter(qe("type","track"));r=ii("trackIdentifier",a)}return i.map(a=>{let s=Number(a.ssrc),d=a.mediaType||a.kind,p=a.trackId,u=a.type,_=a.codecId;if(y.browserName()==="Safari"){let se=/^.+_([\d]+)$/.exec(a.id);if(se&&(s=parseInt(se[1],10)),d=a.id.indexOf("Audio")>0?"audio":"video",e[s]){let ce=d+"-"+e[s];r[ce]&&(p=r[ce].id)}}if(!u||!s||!d)return null;let f=Re(a,"framesDecoded"),W=Re(a,"totalInterFrameDelay"),O=(Re(a,"totalSquaredInterFrameDelay")-W*W/f)/f,J={ssrc:s,type:u,kind:d,bytesReceived:Re(a,"bytesReceived"),bytesSent:Re(a,"bytesSent"),jitter:Re(a,"jitter"),packetsLost:Re(a,"packetsLost"),packetsReceived:Re(a,"packetsReceived"),packetsSent:Re(a,"packetsSent"),fractionLost:Re(a,"fractionLost"),pliCount:Re(a,"pliCount"),firCount:Re(a,"firCount"),nackCount:Re(a,"nackCount"),userId:e[s],interframeDelayVariance:O};if(_&&t[_]){let se=t[_];J.clockRate=se.clockRate,J.mimeType=se.mimeType}if(p&&t[p]){let se=t[p];J.frameHeight=se.frameHeight,J.frameWidth=se.frameWidth,J.framesDecoded=se.framesDecoded,J.framesReceived=se.framesReceived,J.framesDropped=se.framesDropped}return Xi(J)}).filter(a=>!!a)}function ls(n,e){if(!e||!e.rtps||!n.rtps)return n;let t=ii("ssrc",n.rtps),i=ii("ssrc",e.rtps),r=(n.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(a=>{let s=t[a],d=i[a];if(!(!s||!d)){if(s.bytesReceived&&s.bytesReceived>d.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-d.bytesReceived)/r)),s.bytesSent&&s.bytesSent>d.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-d.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>d.packetsReceived||s.packetsLost>d.packetsLost){let p=s.packetsLost-d.packetsLost,u=s.packetsReceived-d.packetsReceived;s.packetLoss=parseFloat((100*p/(p+u)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&d.framesDropped&&s.framesDropped>d.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-d.framesDropped)/r).toFixed(0)))}}),n}function xt(i,r){return o(this,arguments,function*(n,e,t={}){let a=yield cs(n),s={timestamp:Date.now(),transport:ds(a),rtps:ps(a,t)};return e?ls(s,e):(yield T.delay(rs),xt(n,s,t))})}var ri=.8,rt=class extends Q{constructor(e,t,i,r,a){super();this._remoteSDP={};this._remoteCandidates={};this._state=F.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.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Ce.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Ce.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:l.iceServers,iceTransportPolicy:l.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(s){m.log(g.ERROR,"addTrack-direct"),c.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===F.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==F.IDLE&&e!==F.CLOSED&&e!==F.FAILED&&this._startStatInterval()}open(e=null){return o(this,null,function*(){if(this._isOpen){c.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(c.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(i){m.log(g.ERROR,"addTrack-direct"),c.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(F.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(N.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Xt(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(N.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(F.FAILED)):(c.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(F.CLOSED)),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,a;switch(e.notification){case k.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case k.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case k.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((a=e.data.sdk)==null?void 0:a.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 o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){c.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw m.log(g.ERROR,"addIceCandidate-direct"),c.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else c.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return o(this,null,function*(){if(!this._remoteCandidates[e]){c.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){c.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw m.log(g.ERROR,"setRemoteDescription-direct"),c.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){c.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(N.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===F.IDLE||e===F.OPENED?this._setState(F.CONNECTING):this._setState(F.RECONNECTING);break}}_onConnectionStateChange(){switch(c.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),m.log(g.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(F.CONNECTED),this._stopReconnection(),T.getPeerConnectionHostInfo(this._pc).then(e=>{e&&m.log(g.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(F.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()},l.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(c.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(be.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(m.log(g.ICE_RESTART),c.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):c.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,c.error("Ice restart failed",{participantId:this._participantId}),m.log(g.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},l.iceRestartWaitTime)}_createOffer(e){return o(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return c.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw c.error("Unable to create offer",i,{participantId:this._participantId}),m.log(g.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=rt._patchDescription(i),c.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw c.error("Unable to set local description",i,{participantId:this._participantId}),m.log(g.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return o(this,null,function*(){return c.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw c.error("Unable to create answer",e,{participantId:this._participantId}),m.log(g.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=rt._patchDescription(e),c.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw c.error("Unable to set local description",e,{participantId:this._participantId}),m.log(g.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=T.patchSDP(e.sdp,l.preferH264&&y.canPreferH264(),y.isBrokenH264(),l.preferVP9,t&&l.audioNack),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{c.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),m.log(g.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}xt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:be.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:be.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(N.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,l.statisticsInterval)})};this._statInterval=window.setTimeout(e,l.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=ce=>ce.rtt<=this._networkLimits.goodNet.rtt&&ce.loss<=this._networkLimits.goodNet.loss,i=ce=>ce.rtt>=this._networkLimits.badNet.rtt||ce.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,a=e.inbound.rtps.reduce((ce,at)=>Math.max(ce,at.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-ri)+r*ri,loss:this._lastNetworkStat.loss*(1-ri)+a*ri},d=i(s),p=t(s),u=i(this._remoteNetworkStat),_=t(this._remoteNetworkStat),f=i(this._lastNetworkStat),W=t(this._lastNetworkStat),J=d||u?.2:p&&_?1:0,se=Date.now();if((f!==d||W!==p||se-this._lastNetworkStat.date>l.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(ce=>{c.warn("Unable to send [bad-net]",ce)})),J){let ce={};ce[this._participantId]=ce[""]=J,this._triggerEvent(N.NETWORK_STATUS,ce)}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=T.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(E.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=T.applySettings(this._pc,e,this._prevConsumerSettings))}};var Nn=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Nn||{}),Nt=Nn;import{decode as gt}from"messagepack";var Zi=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 d=gt(r);return Object.entries(d).forEach(([O,J])=>{let se=wt(O);this.streamDescriptionByCompactId.set(J,se)}),null;case 2:case 4:let p=gt(r),u=[];for(let O of p){let J=this.getStreamDescription(O);J&&u.push(J.participantId)}return i===2?{type:"notification",notification:k.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:k.STALLED_ACTIVITY,stalledParticipants:u};case 3:let _=gt(r);return{type:"notification",notification:k.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(_))==null?void 0:a.participantId};case 5:let f=gt(r);return{type:"notification",notification:k.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:f[0],maxDimension:f[1]}};case 6:let W=gt(r),K={};for(let[O,J]of Object.entries(W)){let se=(s=this.getStreamDescription(Number(O)))==null?void 0:s.participantId;se&&(K[se]=J/100)}return{type:"notification",notification:k.NETWORK_STATUS,statuses:K};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=gt(e),i=[];for(let[r,a]of Object.entries(t)){let s=a[0],d=a[1],p=a[2],u;if(s!==null){if(u=this.getStreamDescription(s),!u){c.error(`could not uncompress participant ID ${s}`);continue}}else u=null;if(p===null){c.error("unexpected null sequenceNumber",r,a);continue}let _=Oe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,f=d?d>>>0:null;i.push({participantStreamDescription:u,streamId:_,rtpTimestamp:f,sequenceNumber:p})}return{type:"notification",notification:k.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Ln="videochat-epi",us=5e3,hs=3e4,Lt=class extends Q{constructor(e,t){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};this._signaling=t,this.subscribe(e,N.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Ln)||"",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();l.perfStatReportEnabled&&this._previousTimestamp+us<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),l.callStatReportEnabled&&this._previousCallStatReportTimestamp+hs<=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(Ln,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,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,a)=>(a.kind==="video"?(a.jitter&&(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_received+=a.nackCount||0,r.pli_received+=a.pliCount||0,r.fir_received+=a.firCount||0):a.jitter&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+a.jitter*1e3/(r.inbound_audio_count+1),r.inbound_audio_count++),r),t),e.outbound.rtps.reduce((r,a)=>(a.kind==="video"&&(r.nack_sent+=a.nackCount||0,r.pli_sent+=a.pliCount||0,r.fir_sent+=a.firCount||0),r),t);let i={nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),m.logCustom("callStat",i),this._previousCallStatReport=t}};var ms=90,_s=4294967295,Ae=class extends Q{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._reconnectionPrevented=!1;this._state=F.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,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Ce.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Ce.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,Ce.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Lt(this,e),this._serverSettings=i,c.debug("ServerTransport: Created")}getState(){return this._state||F.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==F.IDLE&&e!==F.CLOSED&&e!==F.FAILED&&this._startStatInterval()}open(){if(this._isOpen){c.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(c.error("ServerTransport: Closed",e),this._setState(F.FAILED)):(c.debug("ServerTransport: Closed"),this._setState(F.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Xt(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,Ae._closeDataChannel(this._producerNotification),Ae._closeDataChannel(this._producerCommand),Ae._closeDataChannel(this._producerScreen),Ae._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{c.debug(`[${t}] data channel opened`),r.onerror=a=>{c.error(`[${t}] data channel error`,a)},i(r)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection");let t={};y.baseChromeVersion()&&(t.sdpSemantics=Ae._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=Ae._onSignalingStateChange.bind(this,this._pc),l.producerNotificationDataChannel&&this._createDataChannel(this._pc,Nt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Zi,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),l.producerCommandDataChannel&&this._createDataChannel(this._pc,Nt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),l.producerScreenDataChannel&&this._createDataChannel(this._pc,Nt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){c.error("ServerTransport: Unable to add media source tracks",i),m.log(g.ERROR,"addTrack-single"),this.close(i);return}l.consumerScreenDataChannel&&this._createDataChannel(this._pc,Nt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(F.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==F.OPENED&&(this._setState(F.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(N.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(N.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(N.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(N.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
|
|
12
|
+
`).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Oe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!l.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new ht(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!l.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new tt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,null)}))}replayShare(e){var t;!this._participantIdRegistry||((t=this._captureReceiver)==null||t.destroy(),this._captureReceiver=new tt(e,this._participantIdRegistry,(i,r)=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,i,r)},i=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,i,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!l.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==ge.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(y.getBlackMediaTrack()).catch(d=>{c.error("Could not disable video upload",d)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&a&&s){c.log("Enabling video upload"),this._disabledSenders.delete(i);let d=i.track;d.enabled=s.enabled,i.replaceTrack(s).then(()=>d.stop()).catch(p=>{c.error("Could not enable video upload",p)})}T.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(N.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,l.statisticsInterval)};this._statInterval=window.setTimeout(e,l.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){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 xt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(N.REMOTE_DATA_STATS,{inbound:{topology:be.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:be.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=Oe.AUDIO_MIX,r=this._statBytes[i],a=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(a=!0),r.stalled!==a&&this._triggerEvent(N.REMOTE_ALL_STALL,a)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:a}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Lt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:l.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:l.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:l.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:l.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:Ae._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:l.videoTracksCount};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return o(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,c.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(c.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw c.error("[single] unable to set remote offer",i),m.log(g.ERROR,"setRemoteDescription-single"),i}).then(()=>o(this,null,function*(){if(c.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw c.error("[single] unable to create answer",i),m.log(g.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=T.patchSDP(i.sdp,!1,y.isBrokenH264(),!1),i)).then(i=>o(this,null,function*(){if(c.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw c.error("[single] unable to set local answer",i),m.log(g.ERROR,"setLocalDescription-single"),i}).then(i=>o(this,null,function*(){c.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),c.debug("[single] remote offer has been processed")})).catch(i=>{c.warn("[single] unable to send local answer",i),m.log(g.ERROR,"acceptProducer")}).then(()=>o(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){c.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return o(this,null,function*(){if(!!this._isOpen)switch(e.notification){case k.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case k.REALLOC_CON:this._reconnect();break;case k.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case k.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case k.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case k.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return o(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),l.breakVideoPayloadTypes&&(c.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){c.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=a=>{this._triggerEvent(N.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(N.REMOTE_TRACK_ADDED,i.id,i,t.track)):c.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){c.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(c.debug("[single] connection state changed",{state:e.connectionState},t),m.log(g.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===F.IDLE||i===F.OPENED?this._setState(F.CONNECTING):e.iceConnectionState==="checking"&&this._setState(F.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(F.RECONNECTING);break;case"connected":this._setState(F.CONNECTED),T.getPeerConnectionHostInfo(e).then(r=>{r&&m.log(g.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(l.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{c.error("ServerTransport: Unable to replace track",r),m.log(g.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=y.baseChromeVersion();return e?l.isUnifiedPlanSupported("Chrome",e):l.isUnifiedPlanSupported(y.browserName(),y.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return m.log(g.PAT_WAITING_TIME_ERROR,"noConnection"),c.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return m.log(g.PAT_WAITING_TIME_ERROR,"noReceiver"),c.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return c.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return m.log(g.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),c.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let d=t-s&_s,p=Math.ceil(d/ms);return Math.min(100,Math.max(0,p))}};var N=(O=>(O.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",O.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",O.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",O.REMOTE_ALL_STALL="REMOTE_ALL_STALL",O.REMOTE_DATA_STATS="REMOTE_DATA_STATS",O.STATE_CHANGED="STATE_CHANGED",O.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",O.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",O.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",O.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",O.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",O.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",O.NETWORK_STATUS="NETWORK_STATUS",O.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",O))(N||{}),F=(d=>(d.IDLE="IDLE",d.OPENED="OPENED",d.CONNECTING="CONNECTING",d.RECONNECTING="RECONNECTING",d.CONNECTED="CONNECTED",d.CLOSED="CLOSED",d.FAILED="FAILED",d))(F||{}),be=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(be||{}),er=class extends Q{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){c.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){c.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){c.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),c.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&c.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===k.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===k.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),m.log(g.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],a=i.length&&r.length?T.composeId(i[0],r[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 s=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let d=a===s;this._directTransport=this._createDirectTransport(s,d)}this._opened.indexOf(s)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new rt(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),this._dtListeners&&this._dtListeners.length>0&&c.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new Ae(this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!1),this._stListeners&&this._stListeners.length>0&&c.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("ACTIVE_PARTICIPANTS_NO_SIGNAL",this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;l.noiseSuppression!==e&&(l.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent("ACTIVE_PARTICIPANTS_NO_SIGNAL")}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(m.log(g.PAT_WAITING_TIME_ERROR,"wrongTopology"),c.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(m.log(g.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}replayShare(e){var t;(t=this._serverTransport)==null||t.replayShare(e)}};var nt=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(nt||{}),tr=class extends Q{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===ge.audio&&((r=this._detector)==null||r.destroy(),this._detector=new kt(e,t),!this._interval)){let a=()=>{this._collectVolumes(),this._interval=window.setTimeout(a,l.voiceParams.interval)};this._interval=window.setTimeout(a,l.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===ge.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===Oe.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var ir=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(ir||{}),rr=class extends Q{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,nt.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,N.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let a=e[r].smoothed;a>t&&a>l.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*l.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent("SPEAKER_CHANGED",e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var ni=class extends Q{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,nt.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===F.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),l.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),l.specListenerParams.volumeTimeout))),t===F.FAILED&&this._connectionTimeout&&(c.warn("Transport failed, send callSpecError"),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==F.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(c.warn("There is not connected transport, send callSpecError"),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&c.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var gs=1e3,fs=1e4;var H=class extends Q{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=j.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;m.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),m.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new Zt,l.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),gs))}static current(){return H._current}static hangupAfterInit(){H._activationMutex&&!H._current&&(H._delayedHangup=!0)}static id(){var e,t;return((t=(e=H._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",a=!1,s=!1){return o(this,null,function*(){if(H._activationMutex)throw m.log(g.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new x(P.FAILED);H._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let d=this._mediaSource.getMediaSettings();t===Ve.CHAT||e.length>1?this._logWithMediaSettings(g.OUTGOING_MULTIPARTY_CALL,d):this._logWithMediaSettings(g.OUTGOING_CALL,d);let p=yield this._startConversation(e,t,je.OUTGOING,i,r,a,s);if(!this._conversation)throw new x(P.UNKNOWN_ERROR);if(this._participantState=j.ACCEPTED,this._signaling.changeMediaSettings(d),yield this._registerParticipants(p.conversation.participants),this._processConnectionData(p),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),H._delayedHangup)throw new x(P.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let u=Object.values(this._participants),_;return l.batchParticipantsOnStart&&(_=T.mapSharedParticipants(u)),E.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,_),E.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),H._current=this,this._conversation.concurrent?yield this._acceptConcurrent():l.batchParticipantsOnStart||this._setParticipantsStatus(u,Y.WAITING),this._conversation}catch(d){throw this._close(d,"Unable to start conversation"),d}finally{H._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){if(H._activationMutex)throw m.log(g.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new x(P.FAILED);H._activationMutex=!0,this._state="PROCESSING";try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new x(P.UNKNOWN_ERROR);return E.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(c.log("In waiting hall"),H._current=this,H._activationMutex=!1,this._signaling.readyToSend(),E.onLocalStatus(Y.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw H._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return o(this,null,function*(){c.debug("Join conversation part 2"),H._activationMutex=!0;try{if(this._participantState=j.ACCEPTED,!this._conversation||!this._mediaSource)throw new x(P.UNKNOWN_ERROR);if(this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),H._delayedHangup)throw new x(P.CANCELED);let t=Object.values(this._participants),i;return l.batchParticipantsOnStart&&(i=T.mapSharedParticipants(t)),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),E.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),H._current=this,l.batchParticipantsOnStart||this._setParticipantsStatus(t,Y.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{H._activationMutex=!1}})}onPush(r){return o(this,arguments,function*(e,t=te.USER,i){if(H._activationMutex)throw c.warn("Conversation: there is already running activation"),new x(P.REJECTED);H._activationMutex=!0;try{let a=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new x(P.UNKNOWN_ERROR);if(!a.conversation.participants.find(d=>{var p;return d.state===j.CALLED&&d.id===((p=this._conversation)==null?void 0:p.userId)}))throw c.log("Push rejected (there is an active call)"),m.log(g.PUSH,"rejected"),new x(P.REJECTED);if(yield this._registerParticipants(a.conversation.participants),this._processConnectionData(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),m.log(g.PUSH,"accepted"),H._current=this,H._delayedHangup)throw new x(P.CANCELED);H._activationMutex=!1}catch(a){throw H._activationMutex=!1,this._close(a,"Unable to handle inbound call push"),a}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(ui.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 o(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new x(P.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_CONCURRENT,e),c.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),E.onCallAccepted(),this._state="ACTIVE",this._participantState=j.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return o(this,null,function*(){if(this._state!=="IDLE")throw m.log(g.ERROR,"acceptIncoming"),c.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new x(P.UNKNOWN_ERROR);this._state="PROCESSING",c.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=j.ACCEPTED;let i=Object.values(this._participants),r;l.batchParticipantsOnStart&&(r=T.mapSharedParticipants(i)),E.onCallAccepted(),E.onLocalStream(this._mediaSource.getStream(),t),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),E.onLocalStatus(Y.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(),l.batchParticipantsOnStart||this._setParticipantsStatus(i,Y.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return o(this,null,function*(){var e;if(this._state!=="IDLE")throw m.log(g.ERROR,"declineIncoming"),c.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",c.debug("Decline incoming call"),this._logWithMediaSettings(g.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=j.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(P.REJECTED)),this._close(new x(P.REJECTED))})}hangup(){return o(this,null,function*(){c.debug("Hangup");let e=this._state==="ACTIVE"?P.HUNGUP:P.CANCELED;m.log(g.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new x(e))):E.onHangup(new x(P.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new x(P.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=P.UNKNOWN_ERROR);let a=i.participant;yield this._onAddParticipant(e,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){if(!this._transport)return;let i=[];for(let r of e)(r.state===j.CALLED||r.state===j.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===j.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&c.error(t,e),c.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(P.FAILED):m.log(g.ERROR,e.hangup),H._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([P.CANCELED,P.NOT_FRIENDS,P.CALLEE_IS_OFFLINE,P.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===P.REJECTED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.HUNGUP&&(!e.remote||this._participantState===j.CALLED)){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.MISSED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.SOCKET_CLOSED&&H._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===P.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=j.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),m.destroy(),this._conversation=null,H._current=null,H._delayedHangup=!1,E.onHangup(e||new x(P.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;c.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),m.destroy(),this._conversation=null,H._current=null,H._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return o(this,null,function*(){let t=yield this._api.getConversationParams(e);c.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:a}=t;if(a&&i.push(a),r){let s=r.urls.filter((d,p,u)=>u.indexOf(d)===p);s.forEach(d=>s.push(`${d}?transport=tcp`)),i.push({urls:s,username:r.username,credential:r.credential})}l.iceServers=i,l.wssBase=t.endpoint,l.wssToken=t.token,t.client_type&&(l.clientType=t.client_type)})}_startConversation(e,t,i,r,a="",s=!1,d=!1){return o(this,null,function*(){let p=T.uuid();c.debug("Conversation: start",{conversationId:p,opponentIds:e,opponentType:t,direction:i});let u=r.includes(he.VIDEO),_=yield this._api.startConversation(p,e,t,u,a,s,d);c.debug("Api.startConversation",_),yield this._getConversationParams(_.id);let f=yield this._connectSignaling(He.START,_);return yield this._setConversation(_,f,i),f})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:a}=e;c.debug("Conversation: join",{conversationId:t,joinLink:a});let s=i.includes(he.VIDEO),d;if(t)d=yield this._api.joinConversation(t,s,r);else if(a)d=yield this._api.joinConversationByLink(a,s);else throw new x(P.UNKNOWN_ERROR);c.debug("Api.joinConversation",d),yield this._getConversationParams(d.id);let p=yield this._connectSignaling(He.JOIN,d);return yield this._setConversation(d,p,je.JOINING),p})}_prepareConversation(r){return o(this,arguments,function*(e,t=te.USER,i){c.debug("Conversation: push",{conversationId:e,type:t,peerId:i}),yield this._getConversationParams(e);let a=this._api.getUserId();if(!a)throw new x(P.UNKNOWN_ERROR);let s={id:e,peerId:i,endpoint:`${l.wssBase}?userId=${a}&entityType=${t}&conversationId=${e}&token=${l.wssToken}`,is_concurrent:!1,p2p_forbidden:!1},d=yield this._connectSignaling(He.ACCEPT,s);return H._current&&(H._current._participantState===j.ACCEPTED||H._current._participantState===j.CALLED)?(c.log("Push rejected (busy)"),m.log(g.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(P.BUSY),Promise.reject({hangup:P.BUSY})):(H._current&&(H._current.destroy(),H._current=null),yield this._setConversation(s,d,je.INCOMING,t),d)})}_createParticipant(e){return o(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:ve(),participantState:{},state:j.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);return e.externalId?this._api.cacheExternalId(t.id,e.externalId):t.externalId=yield this._getUserId(t.id),t})}_getUserId(e){return o(this,null,function*(){try{return yield this._api.userId(e)}catch(t){throw this._close(new x(P.NETWORK_ERROR),t),t}})}_setConversation(a,s,d){return o(this,arguments,function*(e,t,i,r=te.USER){let p=t.conversation.participants.map(W=>W.id);yield this._api.prepareUserIds(p);let u=this._api.getUserId();if(!u){let W=(t.conversation.participants||[]).find(K=>T.comparePeerId(K.peerId,t.peerId));if(!W)throw new x(P.UNKNOWN_ERROR);u=Number(W.id),W.idType&&(r=W.idType),this._api.setUserId(u)}let _=T.composeId(u,r),f=yield this._getUserId(_);this._conversation={userId:u,compositeUserId:_,externalId:f,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||be.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(l.forceRelayPolicy=e.p2p_forbidden),m.log(g.RELAY_POLICY,l.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new x(P.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||be.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 Oi;return this.subscribe(e,Ce.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Ce.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new Ot(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,fe.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,fe.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return o(this,null,function*(){if(!!this._conversation)for(let t of e){let i=T.composeParticipantId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(c.debug(`Local roles changed: ${t.roles}`),E.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===j.HUNGUP||t.state===j.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],P.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&re.fromSignaling(t.externalId),mediaSettings:ve(t.mediaSettings),participantState:T.mapParticipantState(t),state:t.state,roles:t.roles||[],status:l.batchParticipantsOnStart?Y.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(c.debug(`Roles for participant [${i}] changed: ${t.roles}`),E.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(li.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new er(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new ei,this.subscribe(this._transport,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,N.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,N.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,N.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,N.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,N.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,N.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,N.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,N.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===je.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===j.ACCEPTED||t.state===j.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new tr(this._transport),this.subscribe(this._volumesDetector,nt.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new rr(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,ir.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new ti(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new ni(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=y.getCameras().length,t=y.getMicrophones().length;c.debug("Cameras: "+e+(y.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(y.hasMicrophonePermission()?"✔":"✖")),m.log(g.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){m.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===j.CALLED||e.state===j.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===P.HUNGUP?this._setParticipantsStatus([e],Y.HANGUP):this._setParticipantsStatus([e],Y.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:ye.CAMERA,stopStream:!0}]),delete this._participants[e.id],E.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(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===j.ACCEPTED||r.state===j.CALLED)){c.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&re.fromSignaling(t.externalId),mediaSettings:ve(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],Y.WAITING),i?(r.state=j.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=j.CALLED,this._transport.allocate(r.id,!0),m.log(g.ADD_PARTICIPANT))})}_onRemoveParticipant(e){c.debug(`Remove participant [${e}]`);let t=this._participants[e];if(!t){c.warn(`Participant [${e}] isn't in conversation`);return}this._transport&&this._transport.close(t.id),m.log(g.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new Ot(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ne.UNKNOWN)})}toggleScreenCapturing(e){return o(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ne.UNKNOWN)})}setVideoStream(e,t=!1){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return o(this,null,function*(){if(this._mediaSource)return m.log(g.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return m.log(g.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return o(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let a=typeof r.uid=="object"?r.uid:re.fromId(r.uid),s=re.toString(a);i[s]=r.priority}for(let r of Object.values(this._participants)){let a=re.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)})}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:re.fromId(r.uid),s=re.toString(a),d=this._api.getCachedOkIdByExternalId(a);if(!d){c.log(`Unknown participant external ID ${s}`);continue}let p=it({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),u=this._participants[d];u&&(u.lastRequestedLayouts[p]=r),H._isStopStreaming(r)?this._streamIdByStreamDescription.has(p)&&!this._cooldownTimestampByStreamDescription.has(p)&&this._cooldownTimestampByStreamDescription.set(p,Date.now()):(this._cooldownTimestampByStreamDescription.delete(p),!this._streamIdByStreamDescription.has(p)&&l.videoTracksCount>0&&this._streamIdByStreamDescription.set(p,null),t[p]=H._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>l.videoTracksCount;){let r=i.next();if(r.done){c.error("Cannot accommodate all streaming requests: tracks available "+l.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]=H._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=wt(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===ye.STREAM||i.mediaType===ye.SCREEN)?E.onRemoteLive(r.externalId,i.streamName,null):E.onRemoteStream(r.externalId,null),m.log(g.PAT_DEALLOCATED)):c.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return o(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,a]of Object.entries(t.errorCodeByParticipantId||{})){let s=wt(r),d=this._participants[s.participantId];if(d){let p;typeof a!="number"?(c.warn(`Unexpected error code ${a} received for participant ${s.participantId}`),p=Or.UNKNOWN_ERROR):p=kr(a),i.push({externalId:d.externalId,errorReason:p})}}if(i&&i.length)throw new ai("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]+fs>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=H._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(H._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),e.keyFrame&&(t!==""&&(t+=":"),t+="kf"),t}_onParticipantSourcesUpdate(e){if(this._conversation){c.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){c.log("Promoted in waiting hall",!e.demote),e.demote?(c.log("Kicked from waiting hall"),this._close(new x(P.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(d=>{if(d.externalId){let p=re.fromSignaling(d.externalId);a.push(p),this._api.cacheExternalId(d.id.id,p)}else s.push(T.decomposeId(d.id.id).id)}),s.length&&!a.length&&(a=yield this._api.getExternalIdsByOkIds(s))),E.onChatRoomUpdated(e,t,a)})}_waitForStreamIfNeeded(e){var d,p;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||l.producerScreenTrack&&t.mediaType===ye.SCREEN)return;let i=it(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){c.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),m.log(g.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 u=t.participantId,_=this._participants[u];if(!_){m.log(g.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${u}`);return}let f=this._streamByStreamId.get(a);if(!f){m.log(g.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}m.log(g.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,a);let W=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(W===ye.STREAM||W===ye.MOVIE)((p=e.participantStreamDescription)==null?void 0:p.streamName)&&E.onRemoteLive(_.externalId,e.participantStreamDescription.streamName,f);else{let K=(l.producerScreenTrack?null:_.secondStream)||f;E.onRemoteStream(_.externalId,K)}}else{c.debug(`Waiting for ${s} until stream ${a} for ${i} is switched`);let u=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,u)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(it(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(it(i)))return i}else{let i={participantId:t,mediaType:ye.CAMERA};if(this._streamIdByStreamDescription.has(it(i)))return i;let r={participantId:t,mediaType:ye.SCREEN};if(this._streamIdByStreamDescription.has(it(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?T.includesOneOf(this._conversation.roles,[st.ADMIN,st.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!T.includesOneOf(this._conversation.roles,[st.ADMIN,st.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return o(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return o(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return o(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Er(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return o(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=kn(e));let a=yield this._signaling.getWaitingHall(r,t,i);if(a.error)return Promise.reject(a.message);let s=a.participants||[],d=[],p=[],u=null;return s.length&&(s.forEach(_=>{if(_.externalId){let f=re.fromSignaling(_.externalId);d.push(f),this._api.cacheExternalId(_.id.id,f)}else p.push(T.decomposeId(_.id.id).id)}),p.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(p)),a.hasMore&&(u=On(s[s.length-1].id))),{participants:d,pageMarker:u,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(e){return o(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return o(this,null,function*(){var d;let a={movieId:e,participantId:(d=this._conversation)==null?void 0:d.compositeUserId};(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*(){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",a=null){return o(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:a,streamMovie:!e},d=yield this._signaling.startStream(s);return d.error?Promise.reject(d.message):d})}stopStream(){return o(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return o(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return o(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return o(this,null,function*(){var r;if(e<l.videoMinWidth||t<l.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<l.videoMinWidth||i.effect.height<l.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");l.videoEffectMaxHeight=i.effect.height,l.videoEffectMaxWidth=i.effect.width}return l.videoMaxWidth=e,l.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return o(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t;!this._conversation||(c.debug("Local media stream changed",e.mediaSettings),E.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return o(this,null,function*(){var t;if(c.log("Screen sharing changed",e.track,e.mediaSettings),l.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;E.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){c.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&E.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){c.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&(l.participantStateMapped?E.onRemoteParticipantState(i.externalId,i.participantState):E.onRemoteParticipantState(i.externalId,T.mapLegacyParticipantState(i.participantState))))}_onSignalingNotification(e){switch(e.notification){case k.ACCEPTED_CALL:return this._onAcceptedCall(e);case k.HUNGUP:return this._onHungup(e);case k.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case k.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case k.CLOSED_CONVERSATION:return this._onClosedConversation(e);case k.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case k.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case k.RATE_CALL_DATA:return this._onNeedRate();case k.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case k.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case k.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case k.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case k.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case k.REGISTERED_PEER:return this._onPeerRegistered(e);case k.SWITCH_MICRO:return this._onMicSwitched(e);case k.CHAT_MESSAGE:return this._onChatMessage(e);case k.CUSTOM_DATA:return this._onCustomData(e);case k.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case k.RECORD_STOPPED:return this._onRecordInfo(null);case k.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case k.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case k.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case k.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case k.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case k.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case k.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return o(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let a of e.conversation.participants){let s=T.composeParticipantId(a),d=a.roles||[];if(s===this._conversation.compositeUserId){t=ve(a.mediaSettings),It(this._conversation.roles,d)||this._onRolesChanged(s,d);continue}r.push(s);let p=this._participants[s];if(!p)yield this._onJoinedParticipant({participantId:a.id,participant:a,mediaSettings:a.mediaSettings});else{let u=ve(a.mediaSettings);sn(u,p.mediaSettings)||this._changeRemoteMediaSettings(s,u);let _=T.mapParticipantState(a),f=p.participantState;T.isEqualParticipantState(_,f)||this._changeRemoteParticipantState(s,_),It(d,p.roles)||this._onRolesChanged(p.id,d)}}for(let a of i)r.indexOf(a)<0&&this._removeParticipant(this._participants[a],P.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=T.composeMessageId(e),i=T.getPeerIdString(e.peerId);if(c.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new x(P.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:ve(e.mediaSettings)}),r=this._participants[t]),r.state=j.ACCEPTED,r.mediaSettings=ve(e.mediaSettings),this._logWithMediaSettings(g.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===je.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){c.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=T.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new x(e.reason));return}let i=this._participants[t];if(!i){c.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===P.REJECTED?j.REJECTED:j.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,P.HUNGUP)}_onAddedParticipant(e){return o(this,null,function*(){var r,a;c.debug(`Participant added [${e.participantId}]`);let t=T.composeMessageId(e),i=this._participants[t];if(i&&i.state!==j.HUNGUP&&i.state!==j.REJECTED){c.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&re.fromSignaling(e.participant.externalId),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:T.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=j.CALLED,i.mediaSettings=ve((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=T.mapParticipantState(e.participant),i.roles=((a=e.participant)==null?void 0:a.roles)||[],this._setParticipantsStatus([i],Y.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onJoinedParticipant(e){return o(this,null,function*(){var r;c.debug(`Participant joined [${e.participantId}]`);let t=T.composeMessageId(e),i=this._participants[t];if(i&&i.state===j.ACCEPTED){c.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&re.fromSignaling(e.participant.externalId),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:T.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===je.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=j.ACCEPTED,i.mediaSettings=ve(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],Y.CONNECTED):this._setParticipantsStatus([i],Y.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id])),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new x(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=T.composeMessageId(e);this._changeRemoteMediaSettings(t,ve(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(),E.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)),l.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Qi(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=Qi(this._serverSettings,r),c.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 o(this,null,function*(){E.onDeviceSwitched(he.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return o(this,null,function*(){let t=T.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),E.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return o(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._getUserId(t),E.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return o(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getUserId(e.initiator);E.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else E.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,E.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,E.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],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 d=this._participants[e.participantId];d&&(c.debug(`Mute states for participant [${e.participantId}] changed`,i),E.onMuteStates(i,r,a,e.muteAll,e.unmute,d.externalId,s==null?void 0:s.externalId));return}T.isObjectsEquals(this._conversation.muteStates,i)&&T.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!==j.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),d=this._conversation.unmuteOptions,p=this._mediaSource.getMediaSettings(),u=Object.entries(s);for(let[_,f]of u)if(!(f!==Ke.MUTE&&f!==Ke.MUTE_PERMANENT)&&(this._isCallAdmin()&&f===Ke.MUTE_PERMANENT&&(s[_]=Ke.MUTE),!(!e.includes(_)||i)))switch(_){case he.VIDEO:p.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(E.onDeviceSwitched(he.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case he.AUDIO:p.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(E.onDeviceSwitched(he.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case he.SCREEN_SHARING:p.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(E.onDeviceSwitched(he.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}E.onMuteStates(s,d,e,t,i,null,a==null?void 0:a.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?E.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&E.onLocalPin(!0)),this._participants[e]?E.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&E.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!vr(this._conversation.options,e)&&(this._conversation.options=e,E.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let 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,E.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;c.log("Received network status update: ",e),E.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(l.producerScreenTrack){E.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,l.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){m.log(g.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}E.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&E.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===be.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(fr.ADD_PARTICIPANT);E.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&E.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let a=this._participants[i];a&&a.externalId&&t.push({uid:a.externalId,volume:r.real})}E.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){c.debug(`Transport state has changed: ${t}`,e);let i;if(t===F.CONNECTED?i=Y.CONNECTED:t===F.CONNECTING||t===F.OPENED?i=Y.CONNECTING:t===F.RECONNECTING&&(i=Y.RECONNECT),!i)return;let r=e.reduce((a,s)=>{if(s in this._participants){let d=this._participants[s];a.push(d),t===F.CONNECTED&&(d.remoteStream||(d.mediaSettings&&this._changeRemoteMediaSettings(s,d.mediaSettings),this._changeRemoteParticipantState(s,d.participantState)),this._updateDisplayLayoutFromCache(s))}else c.warn(`Participant [${s}] isn't in conversation`);return a},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){c.debug(`Local transport state has changed: ${e}`),e===F.CONNECTED&&E.onLocalStatus(Y.CONNECTED),e===F.CONNECTING&&E.onLocalStatus(Y.CONNECTING),e===F.RECONNECTING&&E.onLocalStatus(Y.RECONNECT),e===F.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(P.FAILED)),this._close(new x(P.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(Oe.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(Oe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))c.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{c.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(c.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],Y.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===ge.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;E.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),l.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(c.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case ge.audio:this._removeAudioTrack(e,t,i);break;case ge.video:case ge.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Oe.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onRemoteActivityNoSignal(){this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)}_onTopologyChanged(e){this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let a=this._participants[r];e||this._lastStalled[r]?t.push(a):i.push(a)}t.length&&this._setParticipantsStatus(t,Y.RECONNECT),i.length&&this._setParticipantsStatus(i,Y.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,Y.RECONNECT),r.length&&this._setParticipantsStatus(r,Y.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!y.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(c.debug("Toggle join availability",{available:t,chatId:e}),E.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==be.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,l.batchParticipantsOnStart?a.push(s.externalId):E.onParticipantStatus(s.externalId,t,i)),a),[]);!r.length||l.batchParticipantsOnStart&&E.onRemoteStatus(r,t,i)}replayShare(e){var t;(t=this._transport)==null||t.replayShare(e)}},L=H;L._delayedHangup=!1;var ai=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,ai.prototype),this.participantErrors=t}};var si;function Ss(){return o(this,null,function*(){var n;if(l.apiEnv!=="AUTO")return l.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT1hcGkuX2VuZHBvaW50Lm9rLnJ1JnR5cGU9VFhU"),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),l.apiEndpoint}})}function Un(){if(!l.apiAppId||!l.apiKey)throw new x(ne.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function nr(n,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Fn(n,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${si}/fb.do`,r)}function Bn(i){return o(this,arguments,function*(n,e={},t=!1){si||(si=yield Ss());let r=Fn(n,e,t);return vs(r)})}function vs(n){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${si}/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 Fn(n,e={},t=!1){e.method=n,e.format="JSON",e.application_key||(e.application_key=l.apiKey),t||(ie.sessionKey?e.session_key=ie.sessionKey:ie.accessToken&&(e.access_token=ie.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 Ts=10,Cs=700,Is=3e3,oi=class extends Et{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 Bn(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<Ts))return yield T.delay(Math.min(s*Cs,Is)),a(s);throw c.warn(e,"error",d),d}});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=ne.API;switch(a.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=P.SERVICE_DISABLED;break;case 1102:s=P.CALLEE_IS_OFFLINE;break;case 1103:s=P.NOT_FRIENDS;break;case 1104:case 1106:s=P.EXTERNAL_API_ERROR;break}throw new x(s,{message:a.error_msg,code:a.error_code})}})}userId(e){return o(this,null,function*(){let t=T.decomposeId(e).id;return ie.isEmpty()?re.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),re.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return o(this,null,function*(){ie.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return o(this,null,function*(){if(!this._uuid){let t=$e.get("uuid");t||(t=T.uuid(),$e.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:l.appVersion,client_type:"SDK_JS"}};return l.authToken&&(e.session_data.auth_token=l.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),ie.sessionKey=t.session_key,ie.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&E.onTokenExpired(),new x(ne.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${l.appName}:${l.sdkVersion}`,platform:l.platform,items:e})};nr("log.externalLog",t)}init(){Un()}joinConversation(e,t=!1,i){return o(this,null,function*(){let r={conversationId:e,isVideo:t};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return o(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1};return t&&(r.payload=t),l.domain&&(r.domainId=l.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,a="",s=!1,d=!1){return o(this,null,function*(){let p={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case Ve.USER:p.uids=t.join(",");break;case Ve.GROUP:p.gid=t[0];break;case Ve.CHAT:p.chatId=t[0];break}return s&&(p.createJoinLink=!0),a&&(p.payload=a),l.domain&&(p.domainId=l.domain),d&&(p.requireAuthToJoin=!0),this._startConversation(p)})}_startConversation(e){return o(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return o(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return o(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return o(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1){return o(this,null,function*(){let i={joinLink:e,isVideo:t};return l.anonymToken&&(i.anonymToken=l.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=re.fromIds(e),i=[],r={methods:[]},a=[],s=Object.keys(this._externalUidsCache),d=Object.values(this._externalUidsCache);for(let u of t){let _=re.toString(u),f=d.indexOf(_);f>-1?i.push(Number(s[f])):(a.push(_),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:u.id,anonym:u.type===_t.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((u,_)=>{if(u.ok){let f=Number(u.ok.ok_id);this._externalUidsCache[f]=a[_],i.push(f)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let a of e)this._externalUidsCache.hasOwnProperty(a)?t.push(re.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(re.fromString(r[a]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=re.toString(e),a=i.indexOf(r);return a>-1?T.composeId(t[a],te.USER):null}cacheExternalId(e,t){let i=T.decomposeId(e).id;this._externalUidsCache[i]=re.toString(t)}getConversationParams(e){return o(this,null,function*(){let t={};return l.anonymToken&&(t.anonymToken=l.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:P.HUNGUP};l.anonymToken&&(t.anonymToken=l.anonymToken),nr("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]=re.fromIdToString(a,_t.USER);if(i.anonym_ids)for(let[r,a]of Object.entries(i.anonym_ids))t[r]=re.fromIdToString(a,_t.ANONYM);return t}catch(i){return t}})}getTokenForAnonym(e,t){return o(this,null,function*(){let i={id:e};return t&&(i.application_key=t),(yield this._callUnsafe("auth.getTokenForAnonym",i,!0)).token})}call(i){return o(this,arguments,function*(e,t={}){return this._call(e,t)})}};var Vn=(A=>(A.RECOVER="recover",A.ACCEPT_CALL="accept-call",A.ADD_PARTICIPANT="add-participant",A.REMOVE_PARTICIPANT="remove-participant",A.HANGUP="hangup",A.TRANSMIT_DATA="transmit-data",A.ACCEPT_PRODUCER="accept-producer",A.ALLOCATE_CONSUMER="allocate-consumer",A.CHANGE_MEDIA_SETTINGS="change-media-settings",A.CHANGE_PARTICIPANT_STATE="change-participant-state",A.CHANGE_STREAM_PRIORITIES="change-streams-priorities",A.UPDATE_DISPLAY_LAYOUT="update-display-layout",A.REPORT_PERF_STAT="report-perf-stat",A.RECORD_START="record-start",A.RECORD_STOP="record-stop",A.RECORD_SET_ROLE="record-set-role",A.RECORD_GET_STATUS="record-get-status",A.SWITCH_MICRO="switch-micro",A.SWITCH_TOPOLOGY="switch-topology",A.REQUEST_REALLOC="request-realloc",A.CHAT_MESSAGE="chat-message",A.CHAT_HISTORY="chat-history",A.CUSTOM_DATA="custom-data",A.GRANT_ROLES="grant-roles",A.MUTE_PARTICIPANT="mute-participant",A.PIN_PARTICIPANT="pin-participant",A.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",A.CHANGE_OPTIONS="change-options",A.GET_WAITING_HALL="get-waiting-hall",A.PROMOTE_PARTICIPANT="promote-participant",A.REQUEST_TEST_MODE="request-test-mode",A.ADD_MOVIE="add-movie",A.UPDATE_MOVIE="update-movie",A.REMOVE_MOVIE="remove-movie",A))(Vn||{}),G=Vn;var Hn="open",Gn=[()=>l.producerScreenTrack,()=>l.videoTracksCount>0,()=>!0,()=>l.filteredMessages,()=>l.consumerScreenTrack,()=>!0,()=>l.movieShare],ys=10,De=class extends Ct{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="+l.platform+"&appVersion="+l.appVersion+"&version="+l.protocolVersion+"&device="+l.device+"&capabilities="+De._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<Gn.length;t++)Gn[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=${l.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){m.log(g.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return o(this,arguments,function*(e,t={},i=0){if(t.participantId){let a=T.decomposeId(t.participantId);t=Object.assign({},t,{participantId:a.id,participantType:a.type})}return this._sendRaw(e,t,i)})}_sendRaw(r){return o(this,arguments,function*(e,t={},i=0){let a=s=>{var p;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((p=this.producerCommandDataChannel)==null?void 0:p.readyState)===Hn&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){m.log(g.SOCKET_ACTION,"not_opened"),c.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(m.log(g.SOCKET_ACTION,"invalid_state"),c.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,d)=>{let p=(_,f=!1)=>{!i||f?d(_):(c.debug("Resending a signaling message",e,u.sequence),i--,a(u))},u={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:p};a(u)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(G.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return o(this,null,function*(){return this._send(G.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return o(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(G.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(G.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},ys)})}changeParticipantState(e){return o(this,null,function*(){return this._send(G.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(G.ADD_PARTICIPANT,lr({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(G.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return o(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(G.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(G.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(G.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(G.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return o(this,null,function*(){return this._send(G.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(G.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(G.REMOVE_MOVIE,e)})}startStream(e){return o(this,null,function*(){return this._send(G.RECORD_START,e)})}stopStream(){return o(this,null,function*(){return this._send(G.RECORD_STOP)})}recordSetRole(e,t){return o(this,null,function*(){return this._send(G.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return o(this,null,function*(){return this._send(G.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(G.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(G.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(G.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(G.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(G.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(G.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return o(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(G.GRANT_ROLES,r)})}muteParticipant(e,t,i){return o(this,null,function*(){return this._sendRaw(G.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return o(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(G.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(G.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(G.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return o(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(G.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(G.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===He.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),c.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){c.debug("Socket opened"),m.log(g.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){m.log(g.SOCKET_ACTION,"parse_error"),c.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(c.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(fe.RECONNECT,e),e.conversation.topology&&this._triggerEvent(fe.NOTIFICATION,{type:"notification",notification:k.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(fe.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(m.log(g.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(m.log(g.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new x(P.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(fe.NOTIFICATION,{notification:k.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new x(ne.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(m.log(g.SOCKET_ACTION,"unknown_message"),c.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(fe.FAILED,e)}_onError(e){m.log(g.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){m.log(g.SOCKET_ACTION,"closed"),c.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<De.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(De.RECONNECT_MAX_DELAY,De.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),m.log(g.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,He.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],m.log(g.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),De.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)!==Hn){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}De._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,a),De.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),De.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(a))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new x(ne.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},De.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(He.RETRY)},De.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Be=De;Be.RECONNECT_DELAY=l.signalingReconnectDelay,Be.RECONNECT_MAX_DELAY=l.signalingReconnectMaxDelay,Be.RECONNECT_MAX_COUNT=l.signalingReconnectMaxCount,Be.WAIT_CONNECTION_DELAY=l.waitConnectionDelay,Be.WAIT_RESPONSE_DELAY=l.waitResponseDelay,Be.WAIT_MESSAGE_DELAY=l.waitMessageDelay;var Wn=(t=>(t.KING="KING",t.PAWN="PAWN",t))(Wn||{}),Rs=Wn;var ft,ae,Ut=null,Yh={getCameras:y.getCameras,getMicrophones:y.getMicrophones,getOutput:y.getOutput,hasCamera:y.hasCamera,hasMicrophone:y.hasMicrophone,getSavedCamera:y.getSavedCamera,getSavedMicrophone:y.getSavedMicrophone,getSavedOutput:y.getSavedOutput,hasCameraPermission:y.hasCameraPermission,hasMicrophonePermission:y.hasMicrophonePermission,hasPermissions:y.hasPermissions,getUserMedia:y.getUserMedia,getUserVideo:y.getUserVideo,getUserAudio:y.getUserAudio,saveDeviceId:y.saveDeviceId,isBrowserSupported:y.isBrowserSupported,isScreenCapturingSupported:y.isScreenCapturingSupported,os:y.os,isMobile:y.isMobile,browserName:y.browserName,browserVersion:y.browserVersion,baseChromeVersion:y.baseChromeVersion,getAudioContext:y.getAudioContext};function bs(n){ae=n}function Ps(n){ft=n}function zh(n){Ut=n}function Qh(n){l.videoEffects=n}function Xh(n){return o(this,null,function*(){if(l.set(n),y.browserName()==="Sferum"&&(l.platform=`SFERUM:${y.browserVersion()}`),ae||bs(new oi),ft||Ps(()=>new Be),l.debug&&(jn.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${l.sdkVersion}`,n),yield y.init(),!y.isBrowserSupported())throw new x(ne.UNSUPPORTED);ae.init()})}function Zh(a){return o(this,arguments,function*(n,e=[he.AUDIO],t="",i=!1,r=!1){let s=[],d=[];if(Array.isArray(n)?s=n.length?n:[]:n&&(s=[n]),s.length&&(d=yield ae.getOkIdsByExternalIds(s),!d.length))throw new x(P.CALLEE_IS_OFFLINE);return Ms(d,Ve.USER,e,t,i,r)})}function Ms(s){return o(this,arguments,function*(n,e=Ve.USER,t,i="",r=!1,a=!1){if(L.current())throw c.error("There is already active call"),new x(P.FAILED);return new L(ae,ft(),Ut).onStart(n,e,t,i,r,a)})}function em(n){return o(this,null,function*(){return As(n)})}function As(i){return o(this,arguments,function*(n,e=te.USER,t){if(n===L.id())throw new Error("Push has already been processed");return new L(ae,ft(),Ut).onPush(n,e,t)})}function tm(n,e){return o(this,null,function*(){return ae.getTokenForAnonym(n,e)})}function im(t){return o(this,arguments,function*(n,e={}){return ae.call(n,e)})}function rm(n){return o(this,null,function*(){return n&&(l.authToken=n),ae.authorize()})}function nm(){return o(this,arguments,function*(n=[he.AUDIO]){let e=L.current();if(e)return e.accept(n);throw new Error("Conversation not found")})}function am(){return o(this,null,function*(){let n=L.current();if(n)return n.decline()})}function sm(t){return o(this,arguments,function*(n,e=[he.AUDIO]){return Ds(n,e)})}function Ds(n,e,t){return o(this,null,function*(){if(L.current())throw c.error("There is already active call"),new x(P.FAILED);return new L(ae,ft(),Ut).onJoin({conversationId:n,mediaOptions:e,chatId:t})})}function om(i){return o(this,arguments,function*(n,e=[he.AUDIO],t){if(L.current())throw c.error("There is already active call"),new x(P.FAILED);return t&&(l.anonymToken=t),new L(ae,ft(),Ut).onJoin({joinLink:n,mediaOptions:e})})}function cm(){return o(this,null,function*(){let n=L.current();if(n)return n.hangup();L.hangupAfterInit()})}function dm(n,e){return o(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);if(!t.length)throw new Error("User not found");return ws(t[0],e)})}function ws(n,e){return o(this,null,function*(){let t=L.current();t&&(yield t.addParticipant(T.composeId(n,te.USER),e))})}function pm(n,e=!1){return o(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);return Os(t[0],e)})}function Os(n,e=!1){return o(this,null,function*(){let t=L.current();t&&(yield t.removeParticipant(T.composeId(n,te.USER),e))})}function lm(n,e){return o(this,null,function*(){let t=yield y.saveDeviceId(n,e),i=L.current();return t&&i?i.changeDevice(n):Promise.reject()})}function um(n){return o(this,null,function*(){let e=L.current();return e?e.toggleScreenCapturing(n):Promise.reject()})}function hm(n,e=!1){return o(this,null,function*(){let t=L.current();t&&(yield t.setVideoStream(n,e))})}function mm(n){return o(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalVideo(n))})}function _m(n){return o(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalAudio(n))})}function gm(n,e,t){return o(this,null,function*(){let i=L.current();if(i)return i.setLocalResolution(n,e,t)})}function fm(n){return o(this,null,function*(){let e=L.current();e&&(yield e.changePriorities(n))})}function Sm(n){return o(this,null,function*(){let e=L.current();e&&(yield e.changeParticipantState(n))})}function vm(n){return o(this,null,function*(){let e=L.current();e&&(yield e.updateDisplayLayout(n))})}function Em(n,e,t=!1){return o(this,null,function*(){let i=yield ae.getOkIdsByExternalIds([n]);return ks(i[0],e,t)})}function ks(n,e,t=!1){return o(this,null,function*(){let i=L.current();i&&(yield i.grantRoles(T.composeId(n,te.USER),e,t))})}function Tm(){return o(this,arguments,function*(n=null,e,t=[]){let i=null;return n&&(i=(yield ae.getOkIdsByExternalIds([n]))[0]),xs(i,e,t)})}function xs(){return o(this,arguments,function*(n=null,e,t=[]){let i=L.current();if(i){let r=n?T.composeId(n,te.USER):null;yield i.muteParticipant(r,e,t)}})}function Cm(n,e=!1){return o(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);return Ns(t[0],e)})}function Ns(n,e=!1){return o(this,null,function*(){let t=L.current();t&&(yield t.pinParticipant(T.composeId(n,te.USER),e))})}function Im(n){return o(this,null,function*(){let e=L.current();e&&(yield e.updateMediaModifiers(n))})}function ym(n){return o(this,null,function*(){let e=L.current();e&&(yield e.changeOptions(n))})}function Rm(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),Ls(n,t)})}function Ls(n,e=null){return o(this,null,function*(){let t=L.current();if(t){let i=e?T.composeId(e,te.USER):null;yield t.chatMessage(n,i)}})}function bm(n=10){return o(this,null,function*(){let e=L.current();if(e)return e.chatHistory(n)})}function Pm(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),Us(n,t)})}function Us(n,e=null){return o(this,null,function*(){let t=L.current();if(t){let i=e?T.composeId(e,te.USER):null;yield t.customData(n,i)}})}function Mm(n="",e=!1){return o(this,null,function*(){return(yield ae.createConversation(T.uuid(),n,e)).join_link})}function Am(){return o(this,null,function*(){let n=L.current();return n?n.createJoinLink():Promise.reject()})}function Dm(){return o(this,null,function*(){let n=L.current();return n?n.removeJoinLink():Promise.reject()})}function wm(n,e){return o(this,null,function*(){return ae.getAnonymTokenByLink(n,e)})}function Om(n){let e=L.current();e&&e.setVolume(n)}function km(n){l.forceRelayPolicy=n}function xm(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 Nm(){return o(this,null,function*(){let n=L.current();return n?n.stopStream():Promise.reject()})}function Lm(n,e){return o(this,null,function*(){let t=L.current();if(t){let i=yield ae.getOkIdsByExternalIds([n]);return t.recordSetRole(T.composeId(i[0],te.USER),e)}return Promise.reject()})}function Um(){return o(this,null,function*(){let n=L.current();return n?n.getStreamInfo():Promise.reject()})}function Bm(n){return o(this,null,function*(){let e=L.current();return e?e.addMovie(n):Promise.reject()})}function Fm(n,e,t,i){return o(this,null,function*(){let r=L.current();return r?r.updateMovie(n,e,t,i):Promise.reject()})}function Vm(n){return o(this,null,function*(){let e=L.current();return e?e.removeMovie(n):Promise.reject()})}function Hm(n){l.statisticsInterval=n;let e=L.current();if(e)return e.updateStatisticsInterval()}function Gm(n){jn.disableLog(!n),c.toggle(n)}function Wm(n,...e){!l.debugLog||c.send(n,"[external]",...e)}function jm(n){return o(this,null,function*(){let e=L.current();if(e)return e.videoEffect(n)})}function Km(n){return o(this,null,function*(){let e=L.current();e&&(yield e.setAudioStream(n))})}function $m(n=null,e,t=!1){return o(this,null,function*(){let i=L.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(n,e,t)})}function qm(n,e=!1){return o(this,null,function*(){let t=L.current();if(!t)throw new Error("Conversation not found");let i=yield ae.getOkIdsByExternalIds([n]);return t.promoteParticipant(T.composeId(i[0],te.USER),e)})}function Jm(n){return o(this,null,function*(){yield ae.removeHistoryRecords(n)})}function Ym(){return L.current()}export{oi as Api,Et as BaseApi,Tt as BaseLogger,Ct as BaseSignaling,je as CallDirection,Ve as CallType,li as ChatRoomEventType,ui as ConversationOption,An as DebugMessageType,_t as ExternalIdType,hn as FacingMode,ne as FatalError,x as HangupReason,P as HangupType,he as MediaOption,ge as MediaTrackKind,ye as MediaType,Ke as MuteState,j as ParticipantState,Y as ParticipantStatus,Rs as RecordRole,Be as Signaling,G as SignalingCommandType,He as SignalingConnectionType,k as SignalingNotification,st as UserRole,te as UserType,T as Utils,nm as acceptCall,Bm as addMovie,dm as addParticipant,ws as addParticipantInternal,im as apiCall,rm as authorize,Yh as browser,Ms as callInternal,Zh as callTo,um as captureScreen,ym as changeConversationOptions,lm as changeDevice,Sm as changeParticipantState,fm as changePriorities,jm as changeVideoEffect,bm as chatHistory,Rm as chatMessage,Ls as chatMessageInternal,Am as createJoinLink,Pm as customData,Us as customDataInternal,Gm as debug,Wm as debugMessage,am as declineCall,km as forceRelayPolicy,wm as getAnonymTokenByLink,Ym as getCurrentConversation,Um as getStreamInfo,tm as getTokenForAnonym,$m as getWaitingHall,Em as grantRoles,ks as grantRolesInternal,cm as hangup,Xh as init,sm as joinCall,om as joinCallByLink,Ds as joinCallInternal,Tm as muteParticipant,xs as muteParticipantInternal,Cm as pinParticipant,Ns as pinParticipantInternal,em as processPush,As as processPushInternal,qm as promoteParticipant,Lm as recordSetRole,Jm as removeHistoryRecords,Dm as removeJoinLink,Vm as removeMovie,pm as removeParticipant,Os as removeParticipantInternal,bs as setApi,Km as setAudioStream,gm as setLocalResolution,zh as setLogger,Im as setMediaModifiers,Ps as setSignalingFactory,Hm as setStatisticsInterval,Qh as setVideoEffects,hm as setVideoStream,Om as setVolume,Mm as startConversation,xm as startStream,Nm as stopStream,_m as toggleLocalAudio,mm as toggleLocalVideo,vm as updateDisplayLayout,Fm as updateMovie};
|
|
13
|
+
/*!
|
|
14
|
+
* The buffer module from node.js, for the browser.
|
|
15
|
+
*
|
|
16
|
+
* @author Feross Aboukhadijeh <https://feross.org>
|
|
17
|
+
* @license MIT
|
|
18
|
+
*/
|
|
19
|
+
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|