@vkontakte/calls-sdk 2.6.2-dev.2d30cdd.0 → 2.6.2-dev.30ea81e.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.
Files changed (45) hide show
  1. package/CallsSDK.d.ts +35 -13
  2. package/abstract/BaseApi.d.ts +1 -1
  3. package/abstract/BaseSignaling.d.ts +9 -3
  4. package/calls-sdk.cjs.js +8 -8
  5. package/calls-sdk.esm.js +8 -8
  6. package/classes/Conversation.d.ts +22 -6
  7. package/classes/MediaSource.d.ts +7 -2
  8. package/classes/ProducerCommandSerializationService.d.ts +2 -0
  9. package/classes/codec/IEncoder.d.ts +3 -0
  10. package/classes/codec/LibVPxEncoder.d.ts +4 -1
  11. package/classes/codec/Types.d.ts +6 -1
  12. package/classes/codec/WebCodecsEncoder.d.ts +4 -1
  13. package/classes/screenshare/PacketHistory.d.ts +30 -0
  14. package/classes/screenshare/PacketHistory.test.d.ts +1 -0
  15. package/classes/screenshare/ScreenCaptureSender.d.ts +15 -1
  16. package/classes/screenshare/ScreenCongestionControl.d.ts +25 -0
  17. package/classes/screenshare/SharingStatReport.d.ts +6 -0
  18. package/classes/screenshare/Utils.d.ts +5 -0
  19. package/classes/transport/ServerTransport.d.ts +2 -0
  20. package/default/Api.d.ts +1 -1
  21. package/default/Signaling.d.ts +9 -3
  22. package/enums/ConversationOption.d.ts +2 -1
  23. package/enums/LiveStatus.d.ts +7 -0
  24. package/enums/MediaOption.d.ts +2 -1
  25. package/enums/SignalingCommandType.d.ts +5 -1
  26. package/enums/SignalingNotification.d.ts +5 -1
  27. package/package.json +1 -1
  28. package/static/External.d.ts +26 -3
  29. package/static/Params.d.ts +41 -3
  30. package/static/Polyfills.d.ts +6 -0
  31. package/static/WebRTCUtils.d.ts +2 -1
  32. package/types/Asr.d.ts +5 -0
  33. package/types/ConversationFeature.d.ts +3 -0
  34. package/types/Feedback.d.ts +22 -0
  35. package/types/MediaSettings.d.ts +4 -0
  36. package/types/MovieShare.d.ts +18 -2
  37. package/types/Participant.d.ts +1 -0
  38. package/types/ParticipantListChunk.d.ts +2 -0
  39. package/types/ParticipantStreamDescription.d.ts +2 -1
  40. package/types/Room.d.ts +16 -4
  41. package/types/SignalingMessage.d.ts +22 -3
  42. package/types/WaitingHall.d.ts +2 -8
  43. package/utils/ArrayDequeue.d.ts +24 -0
  44. package/utils/ArrayDequeue.spec.d.ts +1 -0
  45. package/worker/LibVPxEncoderWorker.d.ts +1 -1
package/calls-sdk.esm.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
- * @vkontakte/calls-sdk v2.6.2-dev.2d30cdd.0
3
- * Wed, 30 Nov 2022 05:28:35 GMT
2
+ * @vkontakte/calls-sdk v2.6.2-dev.30ea81e.0
3
+ * Fri, 27 Jan 2023 08:03:27 GMT
4
4
  * https://st.mycdn.me/static/callssdk/2-6-2/doc/
5
5
  */
6
6
 
7
- var xa=Object.defineProperty,La=Object.defineProperties;var Na=Object.getOwnPropertyDescriptors;var ur=Object.getOwnPropertySymbols;var Ua=Object.prototype.hasOwnProperty,Ba=Object.prototype.propertyIsEnumerable;var mr=Math.pow,hr=(a,e,t)=>e in a?xa(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,ze=(a,e)=>{for(var t in e||(e={}))Ua.call(e,t)&&hr(a,t,e[t]);if(ur)for(var t of ur(e))Ba.call(e,t)&&hr(a,t,e[t]);return a},Ii=(a,e)=>La(a,Na(e));var o=(a,e,t)=>new Promise((i,r)=>{var n=l=>{try{d(t.next(l))}catch(u){r(u)}},s=l=>{try{d(t.throw(l))}catch(u){r(u)}},d=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,s);d((t=t.apply(a,e)).next())});import Aa from"webrtc-adapter";var Mt=class{createJoinLink(e){return o(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return o(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return o(this,null,function*(){return""})}log(e){}prepareUserIds(e){return o(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return o(this,null,function*(){})}cleanup(){}};var Dt=class{log(e,t,i=!1){}destroy(){}};var ee=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 At=class extends ee{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e,t){}getNextCommandSequenceNumber(){return 0}};var _r=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(_r||{}),Qe=_r;var gr=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(gr||{}),qe=gr;var fr=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(fr||{}),Ti=fr;var Sr=(i=>(i.ADD_PARTICIPANT="ADD_PARTICIPANT",i.RECORD="RECORD",i.MOVIE_SHARE="MOVIE_SHARE",i))(Sr||{}),vr=Sr;var Er=(r=>(r.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",r.AUDIENCE_MODE="AUDIENCE_MODE",r.WAITING_HALL="WAITING_HALL",r.ASR="ASR",r))(Er||{}),Ci=Er;function Ir(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function Tr(a,e){let t=new Set(a);for(let[i,r]of Object.entries(e))r?t.add(i):t.delete(i);return Array.from(t)}var Cr=(H=>(H.CAMERA_PERMISSION="camera",H.MIC_PERMISSION="mic",H.CAMERA_ACCESS="cameralock",H.MIC_ACCESS="miclock",H.MIC_NOT_FOUND="nomic",H.SCREEN_PERMISSION="screenpermission",H.SCREEN_ACCESS="screenlock",H.CONNECTION="connection",H.NETWORK="network",H.UNKNOWN="unknown",H.UNSUPPORTED="unsupported",H.SIGNALING_FAILED="signalingfailed",H.API="api",H.AUTH="auth",H))(Cr||{}),ne=Cr;var Rr=(Q=>(Q.CANCELED="CANCELED",Q.REJECTED="REJECTED",Q.REMOVED="REMOVED",Q.HUNGUP="HUNGUP",Q.MISSED="MISSED",Q.BUSY="BUSY",Q.FAILED="FAILED",Q.NETWORK_ERROR="NETWORK_ERROR",Q.KILLED="KILLED",Q.BANNED="BANNED",Q.HAS_ACTIVE_CALL="HAS_ACTIVE_CALL",Q.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",Q.NOT_FRIENDS="NOT_FRIENDS",Q.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",Q.CALLER_IS_REJECTED="CALLER_IS_REJECTED",Q.UNKNOWN_ERROR="UNKNOWN_ERROR",Q.UNSUPPORTED="UNSUPPORTED",Q.OLD_VERSION="OLD_VERSION",Q.SERVICE_DISABLED="SERVICE_DISABLED",Q.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",Q.SOCKET_CLOSED="SOCKET_CLOSED",Q.ENDED="ENDED",Q.KILLED_WITHOUT_DELETE="KILLED_WITHOUT_DELETE",Q.ANOTHER_DEVICE="ANOTHER_DEVICE",Q))(Rr||{}),D=Rr;var yr=(r=>(r.AUDIO="AUDIO",r.VIDEO="VIDEO",r.SCREEN_SHARING="SCREEN_SHARING",r.MOVIE_SHARING="MOVIE_SHARING",r))(yr||{}),ge=yr;var Pr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(Pr||{}),Ne=Pr;var br=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(br||{}),j=br;var Mr=(i=>(i.UPDATE="UPDATE",i.REMOVE="REMOVE",i.ACTIVATE="ACTIVATE",i))(Mr||{}),Ri=Mr;var Dr=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(Dr||{}),$e=Dr;var Ar=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(Ar||{}),Te=Ar;var Or=(k=>(k.TRANSMITTED_DATA="transmitted-data",k.ACCEPTED_CALL="accepted-call",k.HUNGUP="hungup",k.PARTICIPANT_ADDED="participant-added",k.PARTICIPANT_JOINED="participant-joined",k.CLOSED_CONVERSATION="closed-conversation",k.MEDIA_SETTINGS_CHANGED="media-settings-changed",k.PARTICIPANT_STATE_CHANGED="participant-state-changed",k.RATE_CALL_DATA="rate-call-data",k.FEATURE_SET_CHANGED="feature-set-changed",k.TOPOLOGY_CHANGED="topology-changed",k.PRODUCER_UPDATED="producer-updated",k.CONSUMER_ANSWERED="consumer-answered",k.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",k.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",k.SETTINGS_UPDATE="settings-update",k.VIDEO_QUALITY_UPDATE="video-quality-update",k.REGISTERED_PEER="registered-peer",k.SWITCH_MICRO="switch-micro",k.RECORD_STARTED="record-started",k.RECORD_STOPPED="record-stopped",k.REALLOC_CON="realloc-con",k.AUDIO_ACTIVITY="audio-activity",k.SPEAKER_CHANGED="speaker-changed",k.STALLED_ACTIVITY="stalled-activity",k.CHAT_MESSAGE="chat-message",k.CUSTOM_DATA="custom-data",k.ROLES_CHANGED="roles-changed",k.MUTE_PARTICIPANT="mute-participant",k.PIN_PARTICIPANT="pin-participant",k.OPTIONS_CHANGED="options-changed",k.NETWORK_STATUS="network-status",k.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",k.PROMOTE_PARTICIPANT="promote-participant",k.CHAT_ROOM_UPDATED="chat-room-updated",k.PROMOTION_APPROVED="promotion-approved",k.JOIN_LINK_CHANGED="join-link-changed",k.MOVIE_UPDATE_NOTIFICATION="movie-update-notification",k.MOVIE_SHARE_INFO="movie-share-info",k.MOVIE_SHARE_STARTED="movie-share-started",k.MOVIE_SHARE_STOPPED="movie-share-stopped",k.ROOM_UPDATED="room-updated",k.ROOMS_UPDATED="rooms-updated",k.ROOM_PARTICIPANTS_UPDATED="room-participants-updated",k))(Or||{}),O=Or;var kr=($=>($.ERROR="callError",$.DEVICES="callDevices",$.CALL_SPEC_ERROR="callSpecError",$.ICE_CONNECTION_STATE="callIceConnectionState",$.ICE_CONNECTION_TYPE="callIceConnectionType",$.ICE_RESTART="callIceRestart",$.PUSH="callPush",$.OUTGOING_CALL="callStart",$.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",$.JOIN_CONVERSATION="callJoinConversation",$.ACCEPTED_OUTGOING="callAcceptedOutgoing",$.ACCEPT_INCOMING="callAcceptIncoming",$.DECLINE_INCOMING="callDeclineIncoming",$.ACCEPT_CONCURRENT="callAcceptConcurrent",$.HANGUP="callHangup",$.MEDIA_STATUS="callMediaStatus",$.DEVICE_CHANGED="callDeviceChanged",$.SOCKET_ACTION="callSocketAction",$.ADD_PARTICIPANT="callAddParticipant",$.REMOVE_PARTICIPANT="callRemoveParticipant",$.POOR_CONNECTION="callPoorConnection",$.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",$.RELAY_POLICY="callForceRelay",$.PAT_ALLOCATED="patAllocate",$.PAT_DEALLOCATED="patDeallocate",$.PAT_ERROR="patError",$.PAT_WAITING_TIME_ERROR="patWaitingTimeError",$.PAT_OUTDATED_RESPONSE="patOutdatedResponse",$))(kr||{}),E=kr;var wr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(wr||{}),Ue=wr;var xr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(xr||{}),Lr=xr;function Nr(a){switch(a){case 1:return"no-available-tracks";default:return"unknown-error"}}var Ur=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(Ur||{}),lt=Ur;function Ot(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var Br=(t=>(t.USER="USER",t.GROUP="GROUP",t))(Br||{}),Z=Br;var yi=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 Vr=2*1024*1024,Va=512*1024,kt=100*1024,Fa=5,Pi="_okcls_logs_session_",Ha=3e4,Fr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=Vr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(Pi)!==0)continue;let i=e.getItem(t);if(!i){Wr(t);continue}let r=Gr(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(kt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(Pi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Wr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>Vr||this.length>Fa-1||this.size+e>this.available);)this.deleteOldestItem()}};function Hr(){return`${Pi}${Date.now()}`}function Gr(a){return new Blob([a]).size}function Wr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function bi(){let a=et.toString();if(!Re.available||!a)return;let e=Gr(a);Re.cleanup(e);try{window.localStorage.setItem($t,a)}catch(t){if(console.warn("Failed to write log to storage",t),Re.storageSize=Re.size+e,Re.cleanup(kt+e),Re.available>=kt+e){bi();return}if(e>kt){et.bisect(),bi();return}Re.storageSize=0;return}e>Va&&(Re.add($t,e),$t=Hr(),et.clear(),Re.cleanup(kt))}function Mi(){!Re.available||!et.length||bi()}function Ga(a=!1){let e=[];try{let r=window.localStorage;for(let s of Re.items){let d=r.getItem(s.key);e.push(d)}let n=et.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 Wa(t,i),i}function Wa(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 jr(a,e){!Re.available||(et.push({t:Date.now(),l:a,d:e}),Ai||(Ai=window.setTimeout(()=>{Ai=null,Mi()},Ha)))}function Di(){Re||(Re=new Fr,et=new yi,$t=Hr(),window.addEventListener("beforeunload",Mi))}var Re,et,$t,Ai=null;window.__VKCallsSDKLogs__=(a=!1)=>(Re||Di(),Mi(),Ga(a));import Kr from"@vkontakte/libvpx";var Ce=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(Ce||{});var h=class extends Dt{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){h._instance||(h._instance=new h(e,t))}static log(e,t,i=!1){h._instance&&h._instance.log(e,t,i)}static logCustom(e,t,i=!1){h._instance&&h._instance.logCustom(e,t,i)}static destroy(){h._instance&&h._instance.destroy(),h._instance=null}};var Fe=class{constructor(){this._worker=null}_createWorker(s,d){return o(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((l,u)=>{let I=i.join(","),R=new Blob([e,`exports.default(${I});`],{type:"application/javascript; charset=utf-8"}),A=window.URL.createObjectURL(R);this._worker=new Worker(A),this._worker.onmessage=w=>{switch(w.data.type){case Ce.READY:l();break;case Ce.ERROR:u(w.data.error);break;case Ce.FRAME:t(w.data);break;case Ce.DEBUG:c.debug(w.data.message);break;case Ce.LOG_ERROR:h.log(E.ERROR,w.data.message);break}},this._sendToWorker(Ce.INIT,r,n)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var ut=class extends Fe{init(e){return o(this,null,function*(){c.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var b=Object.defineProperty;var E=a=>b(a,"__esModule",{value:!0});var M=(a,p)=>{E(a);for(var e in p)b(a,e,{get:p[e],enumerable:!0})};var V={};M(V,{default:()=>D});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var D=(a,p)=>{let e=null,n=null,g=!0;function y(){return a({locateFile:p}).then(r=>n=r)}function s(r,m,l,R,x){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(x),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let d=e.getImageBuffer();if(!d){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let c=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(d.byteLength);if(i.set(d),R){let o=new ImageData(i,c,f);createImageBitmap(o,0,0,c,f).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:i.buffer,width:c,height:f},[i.buffer])}y().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return V;})();\n',t=>{if(t.error)c.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i)}else e(t.data)},[Kr,Kr.getUrl])})}decodeFrame(e,t,i,r){let n="ImageBitmap"in window;this._sendToWorker(Ce.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:n,debug:c.enabled()},[t.buffer])}destroy(){this._removeWorker(),c.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var Oi="_okcls_",mt=(()=>{try{let a=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(a,a),t=e.getItem(a)===a,e.removeItem(a),t?e:null}catch(a){return null}})();function Ka(a){let e=mt?mt.getItem(Oi+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function qa(a,e){try{mt&&mt.setItem(Oi+a,JSON.stringify(e))}catch(t){}}function $a(a){mt&&mt.removeItem(Oi+a)}var ki;(i=>{function a(r){return Ka(r)||null}i.get=a;function e(r,n){qa(r,n)}i.set=e;function t(r){$a(r)}i.remove=t})(ki||(ki={}));var Xe=ki;function qr(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 Se(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}var $r=a=>a.stop(),Jr=a=>a.getTracks().forEach($r),wi=a=>a.getVideoTracks().forEach($r),Yr=a=>a.getVideoTracks()[0].clone();var L=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(D).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,L)}};var De=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(De||{}),me=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(me||{}),xi=class extends ee{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=Se();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return o(this,arguments,function*(e=[ge.AUDIO],t=!0){if(this._stream)return;let i=e.includes(ge.VIDEO),r=e.includes(ge.AUDIO);if(!b.isBrowserSupported())throw new L(ne.UNSUPPORTED);try{this._stream=yield b.getUserMedia(i,r,t),this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(n=>n.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=r&&this._stream.getAudioTracks().filter(n=>n.enabled).length>0||!1}catch(n){throw new L(n)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t,i,r){let n=this.getStream(),s=this._getSendAudioTrack(),d=this.getSendVideoTrack(i);if(!n||!s&&!d&&!t)throw new Error("No local stream found");if(s&&!t){if(r){let{codecs:l}=RTCRtpSender.getCapabilities("audio"),u="audio/red",I=48e3,R=l.findIndex(A=>A.mimeType===u&&A.clockRate===I);if(R>=0){let A=[];A.push(l[R]);for(let w=0;w<l.length;w++)w!==R&&A.push(l[w]);e.getTransceivers().forEach(w=>w.setCodecPreferences(A))}}e.addTrack(s,n)}d&&!t&&e.addTrack(d,n)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return o(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return o(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=S.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);this._onDeviceChange=()=>o(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),s=n&&n.deviceId,d=this._stream.getVideoTracks()[0],l=d&&d.enabled&&d.getSettings(),u=l&&l.deviceId;if(!s&&!u)return;let I=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!I.find(R=>R.deviceId===s)),!t&&u&&(t=!I.find(R=>R.deviceId===u)),i()}),navigator.mediaDevices.addEventListener("devicechange",this._onDeviceChange)}_destroyDeviceChangeListener(){this._onDeviceChange&&navigator.mediaDevices.removeEventListener("devicechange",this._onDeviceChange)}_changeVideoInput(e=null){return o(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield b.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{p.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),n=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),h.log(E.DEVICE_CHANGED,t),c.log("Video stream changed"),yield this._replaceLocalTrack(n),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw h.log(E.ERROR,"change_video"),c.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=Yr(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 b.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),h.log(E.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 h.log(E.ERROR,"change_audio"),c.error("Microphone change failed",t),t}})}_changeScreen(e){return o(this,null,function*(){try{if(e=e||(yield b.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=p.consumerScreenTrack?t:yield this._videoEffect(null,t);h.log(E.DEVICE_CHANGED,"screen"),c.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,p.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=p.consumerScreenDataChannel?b.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw h.log(E.ERROR,"screen"),c.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return o(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,n;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(n=this._stream)==null||n.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return o(this,null,function*(){if(!p.videoEffects)return t;try{return h.log(E.DEVICE_CHANGED,`effect_${e}`),p.videoEffects.setEffect(e,t)}catch(i){return c.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){this._destroyDeviceChangeListener(),p.videoEffects&&(this._effect=null,p.videoEffects.destroy()),this._stream&&(Jr(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return o(this,null,function*(){return e?this._changeScreen():p.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return o(this,null,function*(){if(!this._stream)return;p.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield b.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=b.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return o(this,null,function*(){if(!this._stream)return;let t;e?t=(yield b.getUserAudio()).getAudioTracks()[0]:t=b.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return o(this,null,function*(){if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return o(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks()[0];if(!e)throw new Error("Local audio track not found");if(!!e.enabled)return e.applyConstraints({noiseSuppression:p.noiseSuppression})})}videoEffect(e){return o(this,null,function*(){if(!p.videoEffects)throw new Error("Video Effects library is not set");if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var ht=":",Jt="d",Ja=533,Li="a=fmtp:",Ya="sps-pps-idr-in-keyframe=1",Ni;(vi=>{function a(_,T,y,v,P,B=!1,K=!1){let de=/[\r\n]+/,pe=`\r
8
- `;if(!T&&!y&&!v&&!K&&!B&&!P)return _;function we(q){let _e=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],Ie="a=rtcp-fb:111",z=q.findIndex(Y=>Y.startsWith(Ie));return~z&&(q[z]=q[z]+pe+_e.join(pe)),q}function je(q,_e,Ie){let z=q.split(" "),Y=z.slice(0,3),ae;for(ae=3;ae<z.length;ae++)Ie.includes(z[ae])&&Y.push(z[ae]);for(ae=3;ae<z.length;ae++)!Ie.includes(z[ae])&&!_e.includes(z[ae])&&Y.push(z[ae]);return Y.join(" ")}function xe(q,_e){let Ie=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),z,Y=[];for(z=0;z<q.length;++z){let ae=q[z].match(Ie);ae&&ae.length===3&&ae[2]===_e&&Y.push(ae[1])}return Y}function x(q,_e,Ie,z){let Y,ae="m="+_e;for(Y=0;Y<q.length;++Y)if(q[Y].startsWith(ae)){q[Y]=je(q[Y],Ie,z);break}}function k(q,_e){let Ie=new RegExp(Li+"(\\d+)");for(let z=0;z<q.length;++z){let Y=q[z].match(Ie);if(Y&&Y.length===2&&_e.includes(Y[1])){let ae=q[z].trim()===Li+Y[1]?" ":";";q[z]+=ae+Ya}}}function Ve(q){let _e=xe(q,"H264");if(y){let Ie=_e.slice(0),z=new RegExp(Li+"(\\d+) apt=(\\d+)"),Y;for(Y=0;Y<q.length;++Y){let Ke=q[Y].match(z);Ke&&Ke.length===3&&Ie.includes(Ke[2])&&Ie.push(Ke[1])}let ae=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(Y=q.length;Y--;){let Ke=q[Y].match(ae);Ke&&Ke.length===3&&Ie.includes(Ke[2])&&q.splice(Y,1)}x(q,"video",Ie,[])}else T&&x(q,"video",[],_e),P&&k(q,_e)}function Le(q){let _e=xe(q,"VP9");v&&x(q,"video",[],_e)}function yt(q){let _e=xe(q,"red");_e.length>0&&x(q,"audio",[],_e)}let pt=_.split(de);return(y||T||P)&&Ve(pt),v&&Le(pt),K&&yt(pt),B&&we(pt),pt.join(pe)}vi.patchSDP=a;function e(_){return _?`${_.type||"WEB_SOCKET"}_${_.id}`:"_"}vi.getPeerIdString=e;function t(_,T){return _&&_.id===T.id&&(_.type||"WEB_SOCKET")===(T.type||"WEB_SOCKET")}vi.comparePeerId=t;function i(_){return o(this,null,function*(){return!_||!_.getStats?Promise.resolve(null):_.getStats(null).then(T=>{let y=null,v=null;if(T.forEach(P=>{P.type==="transport"&&P.selectedCandidatePairId?v=T.get(P.selectedCandidatePairId):P.type==="candidate-pair"&&P.state==="succeeded"&&!v&&(!P.hasOwnProperty("selected")||P.selected)&&(v=P)}),v&&v.localCandidateId){let P=T.get(v.localCandidateId);P&&(y={type:P.candidateType,ip:P.ip||P.ipAddress,port:P.port||P.portNumber})}return y}).catch(()=>null)})}vi.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function s(_,T){let y=String(_);return n.test(y)?(c.warn(`Already composite id [${_}] type supplied [${T}]`),y):T===Z.GROUP?"g"+y:T===Z.USER?"u"+y:(c.warn(`Unknown type [${T}] for id [${_}]`),y.match(r)?"u"+y:y)}vi.composeUserId=s;function d(_,T,y){let v=s(_,T);return l(v,y)}vi.composeParticipantId=d;function l(_,T){return T?_+ht+Jt+T:_}vi.compose=l;function u(_){return d(_.id,_.idType||Z.USER,_.deviceIdx||0)}vi.composeId=u;function I(_){return _.participant?u(_.participant):d(_.participantId,_.participantType||Z.USER,_.deviceIdx||0)}vi.composeMessageId=I;function R(_){let T=String(_),y=T.match(n);return y?{id:Number(y[2]),type:y[1]==="g"?Z.GROUP:Z.USER}:(c.warn(`Unsupported compositeId [${_}]`),{id:Number(T),type:Z.USER})}vi.decomposeId=R;function A(_){let T=_.split(ht+Jt);return{compositeUserId:T[0],deviceIdx:T.length>1?parseInt(T[1],10):0}}vi.decomposeParticipantId=A;function w(){var K,de;let _=(de=(K=window.crypto)==null?void 0:K.randomUUID)==null?void 0:de.call(K);if(_)return _;let T="0123456789abcdefghijklmnopqrstuvwxyz".split(""),y=new Array(36),v=0,P,B;for(B=0;B<36;B++)B===8||B===13||B===18||B===23?y[B]="-":B===14?y[B]="4":(v<=2&&(v=33554432+Math.random()*16777216|0),P=v&15,v=v>>4,y[B]=T[B===19?P&3|8:P]);return y.join("")}vi.uuid=w;function H(_,T){let y;function v(){let P=this,B=arguments;y&&window.clearTimeout(y),y=window.setTimeout(()=>{_.apply(P,B)},T)}return v}vi.throttle=H;function re(_){if(!window.BigInt)return null;let T="",y=_.split(`
9
- `);for(let B of y)if(B.startsWith("a=fingerprint")){let K=B.split(" ");if(K.length===2){T=K[1];break}}if(!T)return BigInt(-1);let v=T.split(":"),P=BigInt(0);for(let B=Math.min(7,v.length-1);B>=0;B--){let K=BigInt(parseInt(v[B],16));P<<=BigInt(8),P|=K}return BigInt.asIntN(64,P)}vi.sdpFingerprint=re;function ve(_){return o(this,null,function*(){return new Promise(T=>window.setTimeout(T,_))})}vi.delay=ve;function ue(_,T,y){let v=[];return _.getSenders().forEach(P=>We(T,P,P.track,y,v)),v}vi.applySettings=ue;function We(_,T,y,v,P){var B;if(_&&y&&y.kind===me.video){let K=y.getSettings();if(K){let de=_.maxBitrateK?_.maxBitrateK*1024:null,pe=K.width,we=K.height,je=pe&&we&&_.maxDimension?Math.max(1,Math.max(pe,we)/_.maxDimension):null,xe=_.maxFramerate?_.maxFramerate:null;if(pe&&we&&_.maxDimension&&_.maxDimension>Math.max(pe,we)){let Le=Math.round(pe*we/256),yt=(Math.round(Le*Ja/1e4)+1)*1e4;de=de===null?yt:Math.min(yt,de)}let x=_.degradationPreference?_.degradationPreference:"balanced",k=v[y.id];if(k&&k.bitrate===de&&k.scaleResolutionDownBy===je&&k.maxFramerate===xe&&k.degradationPreference===x){P[y.id]=k;return}P[y.id]={bitrate:de,scaleResolutionDownBy:je,maxFramerate:xe,degradationPreference:x};let Ve=T.getParameters();Ve.encodings||(Ve.encodings=[{}]),Ve.encodings.forEach(Le=>{de?Le.maxBitrate=de:delete Le.maxBitrate,je?Le.scaleResolutionDownBy=je:delete Le.scaleResolutionDownBy,xe?Le.maxFramerate=xe:delete Le.maxFramerate}),Ve.degradationPreference=x,(B=T.setParameters)==null||B.call(T,Ve)}}}vi.applyVideoTrackSettings=We;function ce(_,T){Array.isArray(T)||(T=[T]);for(let y of T)if(_.includes(y))return!0;return!1}vi.includesOneOf=ce;function be(_){var T;return Object.entries(((T=_.participantState)==null?void 0:T.state)||{}).reduce((y,[v,P])=>(_.participantState&&(y[v]={ts:_.participantState.stateUpdateTs[v],state:P}),y),{})}vi.mapParticipantState=be;function Me(_){let T=_.map(y=>({uid:y.externalId,mediaSettings:y.mediaSettings,status:y.status,muteStates:y.muteStates,unmuteOptions:y.unmuteOptions,participantState:y.participantState,markers:y.markers,movieShareInfos:y.movieShareInfos}));return p.filterObservers?T.filter(y=>!y.uid.observer):T}vi.mapSharedParticipants=Me;function Ye(_,T){let y=Object.keys(_),v=Object.keys(T);if(y.length!==v.length)return!1;for(let P of y)if(!v.hasOwnProperty(P)||_[P].state!==T[P].state||_[P].ts!==T[P].ts)return!1;return!0}vi.isEqualParticipantState=Ye;function or(_,T){let y=Object.keys(_),v=Object.keys(T);if(y.length!==v.length)return!1;for(let P of y)if(!T.hasOwnProperty(P)||_[P]!==T[P])return!1;return!0}vi.isObjectsEquals=or;function Q(_,T){if(_.length!==T.length)return!1;for(let y of _)if(T.indexOf(y)<0)return!1;return!0}vi.isArraysEquals=Q;function cr(_){return!Object.keys(_).length}vi.isEmptyObject=cr;function dr(_,T){if(!_&&!T)return 0;if(!_||!T)return _?-1:1;return v(T.rank,_.rank)||v(_.ts,T.ts)||y(_,T);function y(P,B){let K={[Z.USER]:0,[Z.GROUP]:1},{compositeUserId:de,deviceIdx:pe}=A(P.id),{compositeUserId:we,deviceIdx:je}=A(B.id),{id:xe,type:x}=R(de),{id:k,type:Ve}=R(we);return v(K[x],K[Ve])||v(xe,k)||v(pe,je)}function v(P,B){return P<B?-1:P===B?0:1}}vi.participantMarkerCompare=dr;function pr(_,T){let y=Object.entries(_).filter(([,v])=>Array.isArray(T)?!T.includes(v):v!==T);return Object.fromEntries(y)}vi.objectFilterOutValues=pr;function $(_,T,y){let v=y;for(let P in _)!_.hasOwnProperty(P)||(v=T(v,_[P],P));return v}vi.objectReduce=$,vi.setImmediate=(()=>{let _=1,T={},y=null;return typeof MessageChannel!="undefined"&&(y=new MessageChannel,y.port1.onmessage=v=>{let P=v.data;T[P]&&(T[P](),delete T[P])}),function(v){if(y&&document.visibilityState==="hidden"){let B=_;return _=_>=Number.MAX_SAFE_INTEGER?1:_+1,T[B]=v,y.port2.postMessage(B),()=>{T[B]&&delete T[B]}}let P=setTimeout(v,0);return()=>clearTimeout(P)}})()})(Ni||(Ni={}));var S=Ni;var tt=null,Ui=null,Yt=[],zt=[],Bi=[],wt=null,xt=null,Vi=null,Fi=!1,Hi=!1,Qt,_t,Xt,zr=!1,Qr=!1,Gi=null,Wi="",Zt=[],ji=null,Xr=navigator.appVersion,za=navigator.appName,Ae=navigator.userAgent,Zr=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(Zr||{}),Lt=class{constructor(e,t=!1,i=p.videoMaxWidth,r=p.videoMaxHeight){let n=!1;if(e){n={noiseSuppression:p.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let d;xt&&(d=xt.deviceId),typeof e=="string"&&(d=e),d&&(n.deviceId={ideal:d})}let s=!1;if(t){s={width:{min:p.videoMinWidth,max:i,ideal:i},height:{min:p.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:p.videoAspectRatio},frameRate:{ideal:p.videoFrameRate}};let d;wt&&(d=wt.deviceId),typeof t=="string"&&(d=t),d&&(s.deviceId={ideal:d}),p.videoFacingMode&&(s.facingMode={ideal:p.videoFacingMode})}this.audio=n,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},ea=class extends Lt{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=p.screenFrameRate}};function Qa(){return o(this,null,function*(){tt=null,yield ei()})}function Xa(){tt=null,ei().then(()=>g.onDeviceChange())}function ei(){return o(this,null,function*(){return tt||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Ui&&navigator.mediaDevices.addEventListener&&(Ui=S.throttle(Xa,1e3),navigator.mediaDevices.addEventListener("devicechange",Ui)),tt=navigator.mediaDevices.enumerateDevices().then(a=>{Yt=a.filter(r=>r.kind==="videoinput"?(r.label&&(Fi=!0),!0):!1),zt=a.filter(r=>r.kind==="audioinput"?(r.label?Hi=!0:it.isMobile()&&it.browserName()==="Firefox"&&(Hi=Fi),!0):!1),Bi=a.filter(r=>r.kind==="audiooutput");let e=Xe.get("videoinput"),t=Xe.get("audioinput"),i=Xe.get("audiooutput");return wt=Yt.find(r=>r.deviceId===e)||null,xt=zt.find(r=>r.deviceId===t)||null,Vi=Bi.find(r=>r.deviceId===i)||null,tt=Promise.resolve(a),a}).catch(()=>(tt=null,[]))))})}function Za(){return o(this,null,function*(){return it.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(zr=!0),/^a=mid:0$/m.test(t.sdp)&&(Qr=!0),a()}).catch(a)}):Promise.resolve()})}function ti(a,e){return o(this,null,function*(){c.debug("Try to get media",a.getNative());let t=it.hasPermissions(a.isVideo());!t&&!e&&g.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield Qa()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?ne.CAMERA_PERMISSION:ne.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?ne.CAMERA_ACCESS:ne.MIC_ACCESS;break}if(a.canSimplify())return ti(a.simplify(),e);let r=e||ne.UNKNOWN;throw g.onPermissionsError(r),r}})}function en(a){return o(this,null,function*(){c.debug("Try to get screen",a.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(a.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(c.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw ne.SCREEN_PERMISSION;default:throw ne.SCREEN_ACCESS}}})}function ii(){return Zt.length||(Zt=(()=>{let a,e=!1,t=0,i="0",r=Ae.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return a=/\brv[ :]+(\d+)/g.exec(Ae),["IE",a&&a[1]||"Unknown",e,t,i];if(r[1]==="Safari"){if(a=Ae.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(a=Ae.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,Number(a[1]),i];if(a=Ae.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t,i];if(a=Ae.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t,i];if(a=Ae.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t,i]}if(r[1]==="Chrome"){if(e=!0,t=Number(r[2]),a=Ae.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t,i];if(a=Ae.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t,i];if(a=Ae.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t,i];if(a=Ae.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t,i]}return a=Ae.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),a&&a[2]!==void 0&&(i=a[2]),[r[2]?r[1]:za,a&&a[1]||r[2]||Xr,e,t,i]})()),Zt}var it;(y=>{function a(){return o(this,null,function*(){return yield Za(),ei()})}y.init=a;function e(){return Yt}y.getCameras=e;function t(){return zt}y.getMicrophones=t;function i(){return Bi}y.getOutput=i;function r(){return Yt.length>0}y.hasCamera=r;function n(){return zt.length>0}y.hasMicrophone=n;function s(){return wt}y.getSavedCamera=s;function d(){return xt}y.getSavedMicrophone=d;function l(){return Vi}y.getSavedOutput=l;function u(){return Fi}y.hasCameraPermission=u;function I(){return Hi}y.hasMicrophonePermission=I;function R(v=!1){return I()?r()&&v?u():!0:!1}y.hasPermissions=R;function A(v=!1,P=!0,B=!0){return o(this,null,function*(){let K=n()&&P,de=r()&&v,pe;if(!K&&!de)pe=new MediaStream;else try{pe=yield ti(new Lt(K,de))}catch(we){pe=new MediaStream}return!pe.getVideoTracks().length&&B&&pe.addTrack(We()),!pe.getAudioTracks().length&&B&&pe.addTrack(ue()),pe})}y.getUserMedia=A;function w(){return o(this,null,function*(){return en(new ea(window.screen.width,window.screen.height))})}y.getScreenMedia=w;function H(v,P=!1){return o(this,null,function*(){let B=P?p.videoEffectMaxWidth:p.videoMaxWidth,K=P?p.videoEffectMaxHeight:p.videoMaxHeight;return ti(new Lt(!1,v||!0,B,K))})}y.getUserVideo=H;function re(v){return o(this,null,function*(){return ti(new Lt(v||!0,!1))})}y.getUserAudio=re;function ve(v,P){return o(this,null,function*(){let K=(yield ei()).find(de=>de.kind===v&&de.deviceId===P);return K?(v==="videoinput"?wt=K:v==="audioinput"?xt=K:v==="audiooutput"&&(Vi=K),Xe.set(v,P),K):null})}y.saveDeviceId=ve;function ue(){if(!Xt||Xt.readyState==="ended"){let v=_(),P=v.createMediaStreamDestination(),B=v.createGain();B.gain.value=1e-5,B.connect(P),B.connect(v.destination);let K=v.createOscillator();K.type="sine",K.frequency.value=0,K.connect(B),K.start(),Xt=P.stream.getAudioTracks()[0]}return Object.assign(Xt.clone(),{enabled:!1})}y.getSilentMediaTrack=ue;function We(v=p.videoMinWidth,P=p.videoMinHeight){return _t||(_t=document.createElement("canvas"),_t.getContext("2d")),_t.width=v,_t.height=P,(!Qt||Qt.readyState==="ended")&&(Qt=_t.captureStream(p.videoFrameRate).getVideoTracks()[0]),Object.assign(Qt.clone(),{enabled:!1})}y.getBlackMediaTrack=We;function ce(){if($()==="Edge"&&Number(Si())<70)return!1;try{let v=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&v.RTCPeerConnection&&v.RTCIceCandidate&&v.RTCSessionDescription&&v.HTMLCanvasElement&&v.HTMLCanvasElement.prototype.captureStream&&v.RTCRtpSender&&v.RTCRtpSender.prototype.replaceTrack&&v.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(v){return!1}}y.isBrowserSupported=ce;function be(){return!!navigator.mediaDevices.getDisplayMedia}y.isScreenCapturingSupported=be;function Me(){return zr}y.canVP8=Me;function Ye(){return Qr}y.isUnifiedPlan=Ye;function or(){let v=y.browserName()==="Safari"&&y.browserVersion()==="15"&&y.browserSubVersion()==="1",P=y.browserName()==="Opera"&&y.os()==="Windows";return v||P}y.isBrokenH264=or;function Q(){return!(y.baseChromeVersion()&&y.isMobile())}y.canPreferH264=Q;function cr(){var v;return((v=window.RTCRtpTransceiver)==null?void 0:v.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}y.canPreferRed=cr;function dr(){return Wi||(Wi=(()=>{let v={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let P in v)if(v.hasOwnProperty(P)&&v[P].test(Ae))return P;return"Unknown"})()),Wi}y.os=dr;function pr(){return Gi===null&&(Gi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Xr)),Gi}y.isMobile=pr;function $(){return ii()[0]}y.browserName=$;function Si(){return ii()[1]}y.browserVersion=Si;function vi(){return ii()[3]}y.baseChromeVersion=vi;function _(){return ji||(ji=new(window.AudioContext||window.webkitAudioContext)),ji}y.getAudioContext=_;function T(){return ii()[4]}y.browserSubVersion=T})(it||(it={}));var b=it;var Je=class extends Fe{init(e){return o(this,null,function*(){c.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var i=Object.defineProperty;var E=a=>i(a,"__esModule",{value:!0});var g=(a,e)=>{E(a);for(var t in e)i(a,t,{get:e[t],enumerable:!0})};var V={};g(V,{default:()=>D});var n=(t=>(t.VP9="vp09.00.50.08",t.VP8="vp8",t))(n||{}),o=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(o||{});var D=a=>{let e=null,t=!0;function p(){self.postMessage({type:o.READY})}function f(d,r,s,l=!1){if(!e||t!==s){if(!l){self.postMessage({type:o.DEBUG,message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}t=s,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${s?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${s?"VP9":"VP8"}`}),e=new VideoDecoder({output:c=>{let m=a?[c]:[];self.postMessage({type:o.FRAME,data:c},m),c.close()},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:s?n.VP9:n.VP8})}let u=new EncodedVideoChunk({type:l?"key":"delta",timestamp:d,data:r});e.decode(u)}self.onmessage=d=>{switch(d.data.type){case o.INIT:p();break;case o.FRAME:f(d.data.timestamp,d.data.data,d.data.isVP9,d.data.keyFrame);break}}};return V;})();\n',t=>{t.error?c.warn("WebCodecsDecoder",t.error):e(t.data)},[b.baseChromeVersion()>=92])})}decodeFrame(e,t,i,r=!1){this._sendToWorker(Ce.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),c.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window}};import{BitStream as tn}from"bit-buffer";var rn=65536,rt=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)%rn!==e.sequence){c.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:n}=rt.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:n})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((n,s)=>n+s.data.byteLength,0),i=new Uint8Array(t),r=0;for(let n of e)i.set(new Uint8Array(n.data),r),r+=n.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new tn(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),s=i.readBits(1)<<1|r;return s===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,s>=2&&i.index++,i.readBits(3)!==7?(i.index++,(s===1||s===3)&&(i.index+=3)):(s===1||s===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var gt=class{constructor(e){this._onStream=e}drawFrame(e){return o(this,null,function*(){throw new Error("Method `drawFrame` is not supported by this implementation")})}drawImage(e){throw new Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Nt=class extends gt{constructor(e){super(e);this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;c.debug("CanvasRenderer started"),this._useImageBitmap="ImageBitmap"in window}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}drawFrame(e){return o(this,null,function*(){let t="createImageBitmap"in e?yield e.createImageBitmap():yield createImageBitmap(e);this.drawImage(t),t.close()})}drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}destroy(){this._removeStream(),c.debug("CanvasRenderer destroyed")}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(b.browserName()==="Safari"&&Number(b.browserVersion())===15)}};var ft=class extends gt{constructor(e){super(e);c.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:me.video}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}drawFrame(e){return o(this,null,function*(){yield this._writer.write(e)})}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),c.debug("TrackGeneratorRenderer destroyed")}static isBrowserSupported(){return"VideoFrame"in window&&"MediaStreamTrackGenerator"in window&&Je.isBrowserSupported()}};var Ut=class extends rt{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];c.debug(`StreamBuilder started for participant [${e}]`),ft.isBrowserSupported()?this._renderer=new ft(t):this._renderer=new Nt(t),Je.isBrowserSupported()?this._decoder=new Je:this._decoder=new ut;let i=r=>o(this,null,function*(){"VideoFrame"in window&&r instanceof VideoFrame?yield this._renderer.drawFrame(r):this._renderer.drawImage(r)});this._decoder.init(i).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._renderer.destroy(),c.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return Nt.isBrowserSupported()||ft.isBrowserSupported()}};var ri=1,an=1,ta=0,ai=11,ia=1,ra=2,aa=4,na=8;function sa(a,e,t,i,r,n,s){let d=0;e&&(d|=ia),t&&(d|=ra),i&&(d|=aa),s||(d|=na);let l=new ArrayBuffer(ai),u=new DataView(l);if(u.setUint8(0,ri),u.setUint16(1,r),u.setUint32(3,a),u.setUint8(7,n?1:0),u.setUint16(8,ta),u.setUint8(10,d),!s)return l;let I=new Uint8Array(l.byteLength+s.byteLength);return I.set(new Uint8Array(l),0),I.set(new Uint8Array(s),l.byteLength),I.buffer}function oa(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,s=e.getUint16(8),d=e.getUint8(10),l=!!(d&ia),u=!!(d&ra),I=!!(d&aa),R=!!(d&na);if(t!==ri)throw new Error(`Unexpected protocol version. Got ${t}, expected ${ri}`);return{timestamp:r,start:l,end:u,keyframe:I,sequence:i,isVP9:n,ssrc:s,eos:R,data:a.slice(ai)}}function ca(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==ri||e.getUint8(1)!==an||e.getUint16(2)!==ta)}import*as C from"simple-ebml-builder";var nn=mr(2,15)-1,Ki=1,sn=5,on=5;var ni=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=ni._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return C.build(e[0])}else return new Uint8Array;let t=e.reduce((n,s)=>n+s.countSize(),0),i=new Uint8Array(t),r=0;for(let n of e){let s=C.build(n);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var n,s,d;((n=this._mediaSource)==null?void 0:n.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let e=(d=this._sourceBuffer)==null?void 0:d.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-sn);r-i>on&&(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}},Be=class extends rt{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 C.element(C.ID.EBML,[C.element(C.ID.EBMLVersion,C.number(1)),C.element(C.ID.EBMLReadVersion,C.number(1)),C.element(C.ID.EBMLMaxIDLength,C.number(4)),C.element(C.ID.EBMLMaxSizeLength,C.number(8)),C.element(C.ID.DocType,C.string("webm")),C.element(C.ID.DocTypeVersion,C.number(2)),C.element(C.ID.DocTypeReadVersion,C.number(2))])}static _genSegmentHeader(e,t,i){let r=C.element(C.ID.Info,[C.element(C.ID.TimecodeScale,C.number(1e6)),C.element(C.ID.MuxingApp,C.string("vk-webm-builder")),C.element(C.ID.WritingApp,C.string("vk-webm-builder"))]),n=[C.element(C.ID.PixelWidth,C.number(e)),C.element(C.ID.PixelHeight,C.number(t))],s=C.element(C.ID.Tracks,C.element(C.ID.TrackEntry,[C.element(C.ID.TrackNumber,C.number(Ki)),C.element(C.ID.TrackUID,C.number(Ki)),C.element(C.ID.TrackType,C.number(1)),C.element(C.ID.FlagLacing,C.number(0)),C.element(C.ID.DefaultDuration,C.number(1e9)),C.element(C.ID.CodecID,C.string(`V_${i.toUpperCase()}`)),C.element(C.ID.Video,n)]));return C.unknownSizeElement(C.ID.Segment,[r,s])}static _genClusterHeader(e){return C.unknownSizeElement(C.ID.Cluster,[C.element(C.ID.Timecode,C.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new ni(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){c.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>c.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,c.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),c.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=Be._genWebmHeader();this._mediaBuffer.append(s);let d=Be._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(d)}let r=Math.round(i-this._clusterStartTime);if(r>nn&&(this._clusterStartTime=i,r=0),r===0){c.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=Be._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let n=C.element(C.ID.SimpleBlock,[C.vintEncodedNumber(Ki),C.bytes(Be._intToU16BE(r)),C.number((e.keyframe?1:0)<<7),C.bytes(e.frameData)]);this._mediaBuffer.append(n,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),c.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var St=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};c.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=n=>this._onDataChannelMessage(n.data)}_onDataChannelMessage(e){var n,s;let t=oa(e),i=(s=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){c.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];if(!r){let d=l=>this._onStream(i,l);p.screenShareWebmBuilder&&Be.isBrowserSupported()?r=new Be(i,d):r=new Ut(i,d),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,c.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(Je.isBrowserSupported()||ut.isBrowserSupported())&&(Ut.isBrowserSupported()||Be.isBrowserSupported())}};import da from"@vkontakte/libvpx";var cn=1e3,Bt=class extends Fe{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 n=r.play(),s=()=>i(new Error("Autoplay is disabled"));n?n.catch(s):s()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");this._video.paused&&this._video.play();let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return o(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return o(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;c.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var u=Object.defineProperty;var b=o=>u(o,"__esModule",{value:!0});var g=(o,n)=>{b(o);for(var t in n)u(o,t,{get:n[t],enumerable:!0})};var y={};g(y,{default:()=>R});var e=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(e||{});var R=(o,n)=>{let t;function m(a,r){return o({locateFile:n}).then(s=>{if(t=new s.VpxEncoder,t.debug(r),!t.init(a?s.VpxType.VP9:s.VpxType.VP8))throw self.postMessage({type:e.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");t.setMaxQuantizer(10),t.setTargetBitrate(1024)})}function E(a,r,s,i){let c=t.allocateImage(a,r);if(!c){self.postMessage({type:e.FRAME,error:"No buffer data"});return}c.set(new Uint8Array(s));let f=Math.round(performance.now()),l=150;if(!t.encode(f,l,i)){self.postMessage({type:e.FRAME,error:"Encode failed"});return}let p=t.readFrame();if(!p){self.postMessage({type:e.FRAME,error:"No encoded data"});return}t.readFrame()&&(self.postMessage({type:e.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:e.LOG_ERROR,message:"LibVPxEncoder-drop"}));let d=new Uint8Array(p.byteLength);d.set(p),self.postMessage({type:e.FRAME,frameType:i?"key":"delta",timestamp:f,duration:l,data:d.buffer},[d.buffer])}self.onmessage=a=>{switch(a.data.type){case e.INIT:m(a.data.isVP9,a.data.debug).then(()=>self.postMessage({type:e.READY})).catch(r=>self.postMessage({type:e.ERROR,error:String(r)}));break;case e.FRAME:E(a.data.width,a.data.height,a.data.imageData,a.data.keyFrame);break}}};return y;})();
10
- `,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength})},[da,da.getUrl],{isVP9:this.isVP9(),debug:c.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(Ce.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},cn),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),c.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var vt=class extends Fe{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return o(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;c.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var E=Object.defineProperty;var g=i=>E(i,"__esModule",{value:!0});var F=(i,l)=>{g(i);for(var r in l)E(i,r,{get:l[r],enumerable:!0})};var A={};F(A,{default:()=>h});var n=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(n||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,l,r,c,s,f,t,a=null,p=0,u=!1;function V(e){l=e.readable,r=l.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&b(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),l.cancel();return}a=R,b(R,e)}}))}function b(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?n.VP9:n.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
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:p.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(Ce.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),c.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var dn=65536,qi=0,Et=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;c.debug("ScreenCaptureSender started"),this.DATA_SIZE=p.consumerScreenDataChannelPacketSize-ai,this._datachannel=t;let i=(r,n)=>{if(!this._destroyed){if(!r){c.warn("requestFrame failed, keyFrame: "+this._needKeyframe,n),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{c.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};vt.isBrowserSupported()?this._encoder=new vt(e,i):this._encoder=new Bt(e,i),this._datachannel.onmessage=r=>{ca(r.data)&&(c.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>c.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,n){let s=sa(e,t,i,r,qi,this._encoder.isVP9(),n);return qi=(qi+1)%dn,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return o(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let n=e.data.slice(t,t+this.DATA_SIZE),s=e.data.byteLength<=t+n.byteLength,d=this._wrapHeader(e.timestamp,!t,s,e.type==="key",n);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(d)}catch(l){c.warn("Error send data to DataChannel",l),r();return}s||S.setImmediate(()=>this._sendChunk(e,t+this.DATA_SIZE,i,r))}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),c.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return vt.isBrowserSupported()||Bt.isBrowserSupported()}};var te=class{static get sessionKey(){return te._sessionKey}static set sessionKey(e){te._sessionKey=e}static get sessionSecretKey(){return te._sessionSecretKey}static set sessionSecretKey(e){te._sessionSecretKey=e}static get accessToken(){return te._accessToken}static set accessToken(e){te._accessToken=e}static isEmpty(){return!te._sessionKey||!te._sessionSecretKey}};var f=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(f._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(f._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(f._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(te.accessToken=e.apiAuth.accessToken,te.sessionKey=e.apiAuth.sessionKey,te.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(f._params,S.objectFilterOutValues(e,void 0))}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.6.2-dev.2d30cdd.0"}static get debug(){return undefined}static get protocolVersion(){return f._params.joinFromMultipleDevices?6:5}static get platform(){return f._params.platform}static set platform(e){f._params.platform=e}static get clientType(){return f._params.clientType}static set clientType(e){f._params.clientType=e}static get externalUserType(){return f._params.externalUserType}static set externalUserType(e){f._params.externalUserType=e}static get device(){return f._params.device}static get apiKey(){return f._params.apiKey}static get apiEnv(){return f._params.apiEnv}static get apiEndpoint(){switch(f.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return f._params.apiEnv}}static get authToken(){return f._params.authToken}static set authToken(e){f._params.authToken=e}static get anonymToken(){return f._params.anonymToken}static set anonymToken(e){f._params.anonymToken=e}static get domain(){return f._params.domain}static get externalDomain(){return f._params.externalDomain}static get iceServers(){return f._params.iceServers}static set iceServers(e){f._params.iceServers=e}static get wssBase(){return f._params.wssBase}static set wssBase(e){f._params.wssBase=e}static get wssToken(){return f._params.wssToken}static set wssToken(e){f._params.wssToken=e}static get signalingReconnectDelay(){return f._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return f._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return f._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return f._params.waitConnectionDelay}static get waitResponseDelay(){return f._params.waitResponseDelay}static get waitMessageDelay(){return f._params.waitMessageDelay}static get waitAnotherTabDelay(){return f._params.waitAnotherTabDelay}static get debugLog(){return f._params.debugLog}static get forceRelayPolicy(){return f._params.forceRelayPolicy}static set forceRelayPolicy(e){f._params.forceRelayPolicy=e}static get videoMinWidth(){return f._params.videoMinWidth}static get videoMaxWidth(){return f._params.videoMaxWidth}static set videoMaxWidth(e){f._params.videoMaxWidth=e}static get videoMinHeight(){return f._params.videoMinHeight}static get videoMaxHeight(){return f._params.videoMaxHeight}static set videoMaxHeight(e){f._params.videoMaxHeight=e}static get videoAspectRatio(){return f._params.videoAspectRatio}static get videoFrameRate(){return f._params.videoFrameRate}static get videoFacingMode(){return f._params.videoFacingMode}static get screenFrameRate(){return f._params.screenFrameRate}static get videoEffects(){return f._params.videoEffects}static set videoEffects(e){f._params.videoEffects=e}static get videoEffectMaxWidth(){return f._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){f._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return f._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){f._params.videoEffectMaxHeight=e}static get voiceParams(){return f._params.voiceParams}static get specListenerParams(){return f._params.specListenerParams}static get iceRestartWaitTime(){return f._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return f._params.transportConnectionWaitTime}static get statisticsInterval(){return f._params.statisticsInterval}static set statisticsInterval(e){f._params.statisticsInterval=e}static get networkStatisticsInterval(){return f._params.networkStatisticsInterval}static get perfStatReportEnabled(){return f._params.perfStatReportEnabled}static get callStatReportEnabled(){return f._params.callStatReportEnabled}static get producerNotificationDataChannel(){return f._params.producerNotificationDataChannel}static get producerCommandDataChannel(){return f._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return f._params.consumerScreenDataChannel&&Et.isBrowserSupported()}static get producerScreenDataChannel(){return f._params.producerScreenDataChannel&&f.producerNotificationDataChannel&&St.isBrowserSupported()}static get consumerScreenDataChannelPacketSize(){return f._params.consumerScreenDataChannelPacketSize}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}static isUnifiedPlanSupported(e,t){let i=f._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return f._params.movieShare&&f.videoTracksCount>0}static get videoTracksCount(){return f.producerNotificationDataChannel?f._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return f._params.breakVideoPayloadTypes}static get filteredMessages(){return f._params.filteredMessages}static get useParticipantListChunk(){return f._params.useParticipantListChunk&&f._params.videoTracksCount>0}static get participantListChunkInitIndex(){var e;return(e=f._params.participantListChunkInitIndex)!=null?e:0}static get participantListChunkInitCount(){var e;return(e=f._params.participantListChunkInitCount)!=null?e:null}static get serverAudioRed(){return f._params.serverAudioRed&&b.canPreferRed()}static get p2pAudioRed(){return f._params.p2pAudioRed&&b.canPreferRed()}static get h264spsPpsIdrInKeyframe(){return f._params.h264spsPpsIdrInKeyframe}static get batchParticipantsOnStart(){return f._params.batchParticipantsOnStart}static get filterObservers(){return f._params.filterObservers}static get muteMode(){return f._params.muteMode}static get preserveAudioTracks(){return f._params.preserveAudioTracks}},p=f;p._params={platform:"WEB",clientType:"PORTAL",externalUserType:"",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",externalDomain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,consumerScreenDataChannelPacketSize:16*1024,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,useParticipantListChunk:!1,participantListChunkInitIndex:0,participantListChunkInitCount:null,serverAudioRed:!1,p2pAudioRed:!1,h264spsPpsIdrInKeyframe:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1};var J=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))(J||{});function G(a,...e){let t=p.get(a);t&&setTimeout(t,0,...e)}function oe(a,e,...t){if(p.filterObservers){if(Array.isArray(e)){if(e=e.filter(i=>!i.observer),!e.length)return}else if(e.observer)return}G(a,e,...t)}function ye(a){return Object.assign({},a)}function at(a){return a.slice()}var $i;(ps=>{function a(m,M){G("onLocalStream",m,ye(M))}ps.onLocalStream=a;function e(m,M){G("onScreenStream",m,ye(M))}ps.onScreenStream=e;function t(m,M){G("onLocalStreamUpdate",ye(m),M)}ps.onLocalStreamUpdate=t;function i(m){G("onLocalStatus",m)}ps.onLocalStatus=i;function r(m,M){oe("onRemoteStream",m,M)}ps.onRemoteStream=r;function n(m,M){oe("onRemoteLive",m,M)}ps.onRemoteLive=n;function s(m,M){oe("onLocalLive",m,M)}ps.onLocalLive=s;function d(m,M){oe("onRemoteLiveUpdate",m,M)}ps.onRemoteLiveUpdate=d;function l(m,M){oe("onLocalLiveUpdate",m,M)}ps.onLocalLiveUpdate=l;function u(m,M){oe("onRemoteScreenStream",m,M)}ps.onRemoteScreenStream=u;function I(m,M,X,Pt,bt){oe("onConversation",m,ye(M),ye(X),Pt,bt)}ps.onConversation=I;function R(m){m&&G("onConversationParticipantListChunk",m)}ps.onConversationParticipantListChunk=R;function A(m,M,X){oe("onRemoteMediaSettings",m,ye(M),X)}ps.onRemoteMediaSettings=A;function w(m,M){oe("onLocalMediaSettings",m,ye(M))}ps.onLocalMediaSettings=w;function H(m,M){oe("onRemoteSharedMovieInfo",m,ye(M))}ps.onRemoteSharedMovieInfo=H;function re(m,M){oe("onRemoteSharedMovieStoppedInfo",m,ye(M))}ps.onRemoteSharedMovieStoppedInfo=re;function ve(m,M){oe("onLocalSharedMovieInfo",m,ye(M))}ps.onLocalSharedMovieInfo=ve;function ue(m,M){oe("onLocalSharedMovieStoppedInfo",m,ye(M))}ps.onLocalSharedMovieStoppedInfo=ue;function We(m,M){oe("onParticipantAdded",m,M)}ps.onParticipantAdded=We;function ce(m,M){oe("onParticipantJoined",m,M)}ps.onParticipantJoined=ce;function be(m,M,X){oe("onRemoteParticipantState",m,ye(M),X)}ps.onRemoteParticipantState=be;function Me(m,M,X=null){oe("onRemoteStatus",m,M,X)}ps.onRemoteStatus=Me;function Ye(m,M,X=null){oe("onParticipantStatus",m,M,X)}ps.onParticipantStatus=Ye;function or(){G("onPermissionsRequested")}ps.onPermissionsRequested=or;function Q(m){G("onPermissionsError",m)}ps.onPermissionsError=Q;function cr(m,M){oe("onRemoteRemoved",m,M)}ps.onRemoteRemoved=cr;function dr(m,M,X){G("onCallState",m,M,ye(X))}ps.onCallState=dr;function pr(m,M){G("onDeviceSwitched",m,M)}ps.onDeviceSwitched=pr;function $(m,M,X,Pt=!1,bt=!1,Ei=null,Oa=null,ka,lr){let wa=lr?at(lr):void 0;G("onMuteStates",ye(m),at(M),at(X),Pt,bt,Ei,Oa,ka,wa)}ps.onMuteStates=$;function Si(m,M){oe("onRolesChanged",m,at(M))}ps.onRolesChanged=Si;function vi(m){G("onLocalRolesChanged",at(m))}ps.onLocalRolesChanged=vi;function _(m,M,X){oe("onPinnedParticipant",m,M,X)}ps.onPinnedParticipant=_;function T(m){G("onLocalPin",m)}ps.onLocalPin=T;function y(m){G("onOptionsChanged",at(m))}ps.onOptionsChanged=y;function v(){G("onCallAccepted")}ps.onCallAccepted=v;function P(){G("onRateNeeded")}ps.onRateNeeded=P;function B(m){oe("onSpeakerChanged",m)}ps.onSpeakerChanged=B;function K(m){G("onVolumesDetected",at(m))}ps.onVolumesDetected=K;function de(m,M){G("onLocalVolume",m,M)}ps.onLocalVolume=de;function pe(m,M){G("onJoinStatus",m,M)}ps.onJoinStatus=pe;function we(m,M){G("onHangup",m,M)}ps.onHangup=we;function je(m){G("onMultipartyChatCreated",ye(m))}ps.onMultipartyChatCreated=je;function xe(){G("onDeviceChange")}ps.onDeviceChange=xe;function x(m){G("onFingerprintChange",m)}ps.onFingerprintChange=x;function k(){G("onTokenExpired")}ps.onTokenExpired=k;function Ve(m,M,X=!1){G("onChatMessage",m,M,X)}ps.onChatMessage=Ve;function Le(m,M,X=!1){G("onCustomData",m,M,X)}ps.onCustomData=Le;function yt(m,M,X,Pt,bt,Ei){G("onRecordStarted",m,M,X,Pt,bt,Ei)}ps.onRecordStarted=yt;function pt(){G("onRecordStopped")}ps.onRecordStopped=pt;function q(m){G("onLocalNetworkStatusChanged",m)}ps.onLocalNetworkStatusChanged=q;function _e(m){G("onNetworkStatusChanged",m)}ps.onNetworkStatusChanged=_e;function Ie(m,...M){G("onDebugMessage",m,...M)}ps.onDebugMessage=Ie;function z(m,M){let X=Object.assign({},m,{memory:M});G("onStatistics",X)}ps.onStatistics=z;function Y(){G("onAutoplayError")}ps.onAutoplayError=Y;function ae(m,M,X){G("onChatRoomUpdated",m,M,X)}ps.onChatRoomUpdated=ae;function Ke(m){G("onRemoteMixedAudioStream",m)}ps.onRemoteMixedAudioStream=Ke;function ss(m){G("onJoinLinkChanged",m)}ps.onJoinLinkChanged=ss;function os(m){G("onRoomsUpdated",m)}ps.onRoomsUpdated=os;function cs(m,M,X){G("onRoomUpdated",m,M,X)}ps.onRoomUpdated=cs;function ds(m){G("onRoomParticipantsUpdated",m)}ps.onRoomParticipantsUpdated=ds})($i||($i={}));var g=$i;var pa=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(pa||{}),Ji;(ce=>{let a="📞",e=(be,...Me)=>{g.onDebugMessage(be,...Me)},t=!1,i=(be,Me)=>(...Ye)=>{be(...Ye),jr(Me,Ye)},r=console.debug.bind(console,a),n=console.log.bind(console,a),s=console.warn.bind(console,a),d=console.error.bind(console,a),l=e.bind(null,"DEBUG"),u=e.bind(null,"LOG"),I=e.bind(null,"WARN"),R=e.bind(null,"ERROR");ce.debug=l,ce.log=u,ce.warn=I,ce.error=R;function ve(){return t}ce.enabled=ve;function ue(be){t=be,p.debugLog&&Di(),be?(ce.debug=p.debugLog?i(r,"DEBUG"):r,ce.log=p.debugLog?i(n,"LOG"):n,ce.warn=p.debugLog?i(s,"WARN"):s,ce.error=p.debugLog?i(d,"ERROR"):d):(ce.debug=p.debugLog?i(l,"DEBUG"):l,ce.log=p.debugLog?i(u,"LOG"):u,ce.warn=p.debugLog?i(I,"WARN"):I,ce.error=p.debugLog?i(R,"ERROR"):R)}ce.toggle=ue;function We(be,...Me){switch(be){case"DEBUG":ce.debug(...Me);break;case"LOG":ce.log(...Me);break;case"WARN":ce.warn(...Me);break;case"ERROR":ce.error(...Me);break}}ce.send=We})(Ji||(Ji={}));var c=Ji;var It=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(It||{}),Ee;(d=>{function a(l){return l.length?typeof l[0]=="object"?l:l.map(u=>e(u)):[]}d.fromIds=a;function e(l,u="USER"){return{id:l,type:u}}d.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}d.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}d.toString=i;function r(l,u="USER"){return i(e(l,u))}d.fromIdToString=r;function n(l){try{return JSON.parse(l)}catch(u){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}d.fromString=n;function s(l,u){return l.id===u.id&&l.type===u.type}d.compare=s})(Ee||(Ee={}));var fe;(r=>{function a(n,s="USER",d=0){return{id:n,type:s,deviceIdx:d}}r.fromId=a;function e(n){return`{"id":"${n.id}","type":"${n.type}","deviceIdx":"${n.deviceIdx}"}`}r.toString=e;function t(n,s){return Object.assign({deviceIdx:s},Ee.fromSignaling(n))}r.fromSignaling=t;function i(n){return n&&typeof n=="object"?n.deviceIdx:0}r.getDeviceIdx=i})(fe||(fe={}));var pn="kf";function Vt(a){return a.stopStream}function Yi(a){return a.keyFrameRequested}function la(a){if(Vt(a))return"ss";if(Yi(a))return pn;let e="";return a.priority!==void 0&&(e+="p="+a.priority),a.width!==void 0&&a.height!==void 0&&(e!==""&&(e+=":"),e+="sz="+Math.round(a.width)+"x"+Math.round(a.height)),a.fit!==void 0&&(e!==""&&(e+=":"),e+="fit="+a.fit),e}var Pe=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(Pe||{}),ua="s",ma="m";function He(a){return a.participantId+(a.mediaType?ht+ua+a.mediaType:"")+(a.streamName?ht+ma+a.streamName:"")}function Ft(a){let e=a.split(ht),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i=null,r,n=0;for(let d of e)switch(d.charAt(0)){case ua:i=ln(d.slice(1));break;case ma:r=d.slice(1);break;case Jt:n=Number.parseInt(d.slice(1),10);break;default:throw new Error("Unexpected parameter type "+d.charAt(0)+" in stream description "+a)}return{participantId:S.compose(t,n),mediaType:i,streamName:r}}function ln(a){for(let e of Object.keys(Pe))if(e===a)return Pe[e];return null}function zi(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 si(a,e){return!(!zi(a.camera,e.camera)||!zi(a.screenSharing,e.screenSharing))}function Qi(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function ha(a){try{return btoa(JSON.stringify(a))}catch(e){c.warn("WaitingParticipant: failed convert to string",a,e)}return null}function _a(a){try{return JSON.parse(atob(a))}catch(e){c.warn("WaitingParticipant: failed convert from string",a,e)}return null}var Tt=(a,e)=>S.objectReduce(a,(t,i,r)=>(i===e&&t.push(r),t),[]);var Ht=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,h.log(E.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,h.log(E.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"),h.log(E.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),h.log(E.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===me.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var oi=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(p.muteMode||!((s=this._output)==null?void 0:s.audioTrack))return;let e=b.browserName()!=="Safari"||b.isMobile(),t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{c.warn("Error on play audio"),g.onAutoplayError()},r=d=>{t.srcObject=new MediaStream([d]),t.load();let l=t.play();l?l.catch(i):i()},n=()=>{var l;c.debug("Recover audio playback");let d=(l=this._output)==null?void 0:l.audioTrack;d?r(d):c.warn("Broken audio track")};t.onpause=n,t.onstalled=n,t.onerror=n,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return o(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=b.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw h.log(E.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var un=90,mn=3,ci=class extends ee{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),g.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>un?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=mn)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var hn=44100,Gt=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=b.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=hn/this._fftBins.length,t=Math.ceil(p.voiceParams.minFreq/e),i=Math.floor(p.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((n,s)=>n+s,0)/e.length/255,r=this._lastSmoothedLevel*p.voiceParams.smoothing+i*(1-p.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var di=class extends ee{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&g.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,p.voiceParams.interval)};this._interval=window.setTimeout(t,p.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,De.SOURCE_CHANGED,r=>{r.kind===me.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new Gt("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 ga="videochat-epi",_n=5e3,gn=3e4,nt=class extends ee{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,F.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(ga)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return o(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&p.perfStatReportEnabled&&this._previousTimestamp+_n<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),p.callStatReportEnabled&&this._previousCallStatReportTimestamp+gn<=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(ga,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,n)=>(n.kind==="video"?(n.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+n.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+n.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=n.framesDropped,r.nack_sent+=n.nackCount,r.pli_sent+=n.pliCount,r.fir_sent+=n.firCount):(n.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+n.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+n.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=n.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=n.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=n.removedSamplesForAcceleration,r.concealed_audio_samples+=n.concealedSamples,r.silent_concealed_audio_samples+=n.silentConcealedSamples,r.audio_concealment_events+=n.concealmentEvents),r),t),e.outbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.nack_received+=n.nackCount,r.pli_received+=n.pliCount,r.fir_received+=n.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,n=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,d=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,l=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,u=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=n/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=d/r*1e3,i.concealed_silent_audio_samples=l/r*1e3,i.concealment_audio_avg_size=d/u,i.total_audio_energy=t.total_audio_energy}h.logCustom("callStat",i),c.log("Sent call stats",i),this._previousCallStatReport=t}};var fn=1e3;function he(a,e,t=0){return e in a&&a[e]?a[e]:t}function fa(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function Ze(a,e){return t=>t[a]===e}function Sn(a){return(e,t)=>e[a]-t[a]}function pi(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function vn(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function En(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Xi(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=En(t[1])?Xi(t[1]):t[1],e),{})}function In(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function Tn(a){return o(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...a.getReceivers().map(t=>t.getStats())),e.push(...a.getSenders().map(t=>t.getStats()))):e.push(a.getStats()),Promise.all(e).then(In).then(vn)})}function Cn(a){let e=a.filter(Ze("type","candidate-pair")).sort(Sn("priority")).find(fa(Ze("nominated",!0),Ze("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(Ze("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(Ze("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 Rn(a,e){let t=pi("id",a),i=a.filter(fa(Ze("type","inbound-rtp"),Ze("type","outbound-rtp")));b.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,s)=>{if(!n[s.ssrc])n[s.ssrc]=s;else{let d=Object.assign({},n[s.ssrc],s),l=n[s.ssrc].isRemote?s:n[s.ssrc];d.id=l.id,d.type=l.type,delete d.isRemote,delete d.remoteId,n[d.ssrc]=d}return n},{})));let r={};if(b.browserName()==="Safari"){let n=a.filter(Ze("type","track"));r=pi("trackIdentifier",n)}return i.map(n=>{let s=Number(n.ssrc),d=n.mediaType||n.kind,l=n.trackId,u=n.type,I=n.codecId;if(b.browserName()==="Safari"){let A=/^.+_([\d]+)$/.exec(n.id);if(A&&(s=parseInt(A[1],10)),d=n.id.indexOf("Audio")>0?"audio":"video",e[s]){let w=d+"-"+e[s];r[w]&&(l=r[w].id)}}if(!u||!s||!d)return null;let R={ssrc:s,type:u,kind:d,bytesReceived:he(n,"bytesReceived"),bytesSent:he(n,"bytesSent"),jitter:he(n,"jitter"),packetsLost:he(n,"packetsLost"),packetsReceived:he(n,"packetsReceived"),packetsSent:he(n,"packetsSent"),fractionLost:he(n,"fractionLost"),pliCount:he(n,"pliCount"),firCount:he(n,"firCount"),nackCount:he(n,"nackCount"),userId:e[s]};if(d==="video"){let A=he(n,"framesDecoded"),w=he(n,"totalInterFrameDelay"),H=he(n,"totalSquaredInterFrameDelay");R.interframeDelayVariance=(H-w*w/A)/A}if(d==="audio"&&(R.totalSamplesReceived=he(n,"totalSamplesReceived"),R.concealedSamples=he(n,"concealedSamples"),R.insertedSamplesForDeceleration=he(n,"insertedSamplesForDeceleration"),R.removedSamplesForAcceleration=he(n,"removedSamplesForAcceleration"),R.silentConcealedSamples=he(n,"silentConcealedSamples"),R.concealmentEvents=he(n,"concealmentEvents"),R.totalAudioEnergy=he(n,"totalAudioEnergy")),I&&t[I]){let A=t[I];R.clockRate=A.clockRate,R.mimeType=A.mimeType}if(l&&t[l]){let A=t[l];R.frameHeight=A.frameHeight,R.frameWidth=A.frameWidth,R.framesDecoded=A.framesDecoded,R.framesReceived=A.framesReceived,R.framesDropped=A.framesDropped}return Xi(R)}).filter(n=>!!n)}function yn(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=pi("ssrc",a.rtps),i=pi("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let s=t[n],d=i[n];if(!(!s||!d)){if(s.bytesReceived&&s.bytesReceived>d.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-d.bytesReceived)/r)),s.bytesSent&&s.bytesSent>d.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-d.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>d.packetsReceived||s.packetsLost>d.packetsLost){let l=s.packetsLost-d.packetsLost,u=s.packetsReceived-d.packetsReceived;s.packetLoss=parseFloat((100*l/(l+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)))}}),a}function Wt(i,r){return o(this,arguments,function*(a,e,t={}){let n=yield Tn(a),s={timestamp:Date.now(),transport:Cn(n),rtps:Rn(n,t)};return e?yn(s,e):(yield S.delay(fn),Wt(a,s,t))})}var li=.8,st=class extends ee{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=V.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=n,this._perfStatReporter=new nt(this,i,!0),this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,De.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,De.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:p.iceServers,iceTransportPolicy:p.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,p.p2pAudioRed),this._applySettings()}catch(s){h.log(E.ERROR,"addTrack-direct"),c.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===V.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==V.IDLE&&e!==V.CLOSED&&e!==V.FAILED&&this._startStatInterval()}open(e=null){return o(this,null,function*(){if(this._isOpen){c.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(c.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,p.p2pAudioRed),this._applySettings()}catch(i){h.log(E.ERROR,"addTrack-direct"),c.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(V.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={}})}updateSettings(e){si(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(F.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(c.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(V.FAILED)):(c.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(V.CLOSED)),this._triggerEvent(F.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(F.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case 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 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 h.log(E.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 h.log(E.ERROR,"setRemoteDescription-direct"),c.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){c.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(F.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(F.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return o(this,null,function*(){e.candidate&&this._signaling.ready&&(c.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(c.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>o(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(c.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===V.IDLE||e===V.OPENED?this._setState(V.CONNECTING):this._setState(V.RECONNECTING);break}}_onConnectionStateChange(){switch(c.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),h.log(E.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(V.CONNECTED),this._stopReconnection(),S.getPeerConnectionHostInfo(this._pc).then(e=>{e&&h.log(E.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(V.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(c.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},p.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(c.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(se.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(h.log(E.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}),h.log(E.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},p.iceRestartWaitTime)}_createOffer(e){return o(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return c.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw c.error("Unable to create offer",i,{participantId:this._participantId}),h.log(E.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=st._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}),h.log(E.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}),h.log(E.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=st._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}),h.log(E.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!b.baseChromeVersion();return e.sdp=S.patchSDP(e.sdp,p.preferH264&&b.canPreferH264(),b.isBrokenH264(),p.preferVP9,p.h264spsPpsIdrInKeyframe,t&&p.audioNack,p.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{c.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),h.log(E.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Wt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:se.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:se.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(F.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,p.statisticsInterval)})};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=ue=>ue.rtt<=this._networkLimits.goodNet.rtt&&ue.loss<=this._networkLimits.goodNet.loss,i=ue=>ue.rtt>=this._networkLimits.badNet.rtt||ue.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((ue,We)=>Math.max(ue,We.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-li)+r*li,loss:this._lastNetworkStat.loss*(1-li)+n*li},d=i(s),l=t(s),u=i(this._remoteNetworkStat),I=t(this._remoteNetworkStat),R=i(this._lastNetworkStat),A=t(this._lastNetworkStat),re=d||u?.2:l&&I?1:0,ve=Date.now();if((R!==d||A!==l||ve-this._lastNetworkStat.date>p.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(ue=>{c.warn("Unable to send [bad-net]",ue)})),re){let ue={};ue[this._participantId]=ue[""]=re,this._triggerEvent(F.NETWORK_STATUS,ue)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=S.sdpFingerprint(e);if(t===null){c.warn("Fingerprint calculation is unsupported");return}this._fingerprint===null?this._fingerprint=t:(g.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=S.applySettings(this._pc,e,this._prevConsumerSettings))}};var Sa=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Sa||{}),jt=Sa;import{decode as ot}from"messagepack";var Zi=class{constructor(){this.streamDescriptionByCompactId=new Map;this.compactIdByStreamDescription=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}getCompactId(e){return this.compactIdByStreamDescription.get(e)}handleMessage(e){var n,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let d=ot(r);return Object.entries(d).forEach(([H,re])=>{let ve=Ft(H);this.streamDescriptionByCompactId.set(re,ve),this.compactIdByStreamDescription.set(H,re)}),null;case 2:case 4:let l=ot(r),u=[];for(let H of l){let re=this.getStreamDescription(H);re&&u.push(re.participantId)}return i===2?{type:"notification",notification:O.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:O.STALLED_ACTIVITY,stalledParticipants:u};case 3:let I=ot(r);return{type:"notification",notification:O.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(I))==null?void 0:n.participantId};case 5:let R=ot(r);return{type:"notification",notification:O.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:R[0],maxDimension:R[1]}};case 6:let A=ot(r),w={};for(let[H,re]of Object.entries(A)){let ve=(s=this.getStreamDescription(Number(H)))==null?void 0:s.participantId;ve&&(w[ve]=re/100)}return{type:"notification",notification:O.NETWORK_STATUS,statuses:w};case 7:return this._createParticipantSourcesUpdateNotification(r);case 8:{let re=ot(r).map(ve=>{var Ye;let[ue,We,ce,be,Me]=ve;return{participantId:(Ye=this.getStreamDescription(ue))==null?void 0:Ye.participantId,gain:We,pause:ce,offset:be,duration:Me}});return{type:"notification",notification:O.MOVIE_UPDATE_NOTIFICATION,data:re}}default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=ot(e),i=[];for(let[r,n]of Object.entries(t)){let s=n[0],d=n[1],l=n[2],u;if(s!==null){if(u=this.getStreamDescription(s),!u){c.error(`could not uncompress participant ID ${s}`);continue}}else u=null;if(l===null){c.error("unexpected null sequenceNumber",r,n);continue}let I=Ue.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,R=d?d>>>0:null;i.push({participantStreamDescription:u,streamId:I,rtpTimestamp:R,sequenceNumber:l})}return{type:"notification",notification:O.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Pn=90,bn=4294967295,Oe=class extends ee{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=V.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,De.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,De.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,De.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new nt(this,e),this._serverSettings=i,c.debug("ServerTransport: Created")}getState(){return this._state||V.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==V.IDLE&&e!==V.CLOSED&&e!==V.FAILED&&this._startStatInterval()}open(e=!1){if(this._isOpen){c.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(c.error("ServerTransport: Closed",e),this._setState(V.FAILED)):(c.debug("ServerTransport: Closed"),this._setState(V.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){si(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,Oe._closeDataChannel(this._producerNotification),Oe._closeDataChannel(this._producerCommand),Oe._closeDataChannel(this._producerScreen),Oe._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(F.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let n=r.readyState;n==="open"?(c.debug(`[${t}] data channel opened`),r.onerror=s=>{c.error(`[${t}] data channel error`,s)},i(r)):c.error(`[${t}] data channel open failed, state [${n}]`)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection");let t={};b.baseChromeVersion()&&(t.sdpSemantics=Oe._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=S.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Oe._onSignalingStateChange.bind(this,this._pc),p.producerNotificationDataChannel&&this._createDataChannel(this._pc,jt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Zi,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),p.producerCommandDataChannel&&(this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,jt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)})),p.producerScreenDataChannel&&this._createDataChannel(this._pc,jt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,p.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){c.error("ServerTransport: Unable to add media source tracks",i),h.log(E.ERROR,"addTrack-single"),this.close(i);return}p.consumerScreenDataChannel&&this._createDataChannel(this._pc,jt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(V.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==V.OPENED&&(this._setState(V.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(F.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(F.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(F.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(F.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
- `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Ue.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!p.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new Et(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!p.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new St(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(F.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(F.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!p.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==me.video)return;let r=!this._disabledSenders.has(i),n=e.maxDimension!==0;if(r&&!n){c.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(b.getBlackMediaTrack()).catch(d=>{c.error("Could not disable video upload",d)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&n&&s){c.log("Enabling video upload"),this._disabledSenders.delete(i);let d=i.track;d.enabled=s.enabled,i.replaceTrack(s).then(()=>d.stop()).catch(l=>{c.error("Could not enable video upload",l)})}S.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(F.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,p.statisticsInterval)};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return o(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Wt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(F.REMOTE_DATA_STATS,{inbound:{topology:se.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:se.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=Ue.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(F.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:nt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:p.producerNotificationDataChannel?7:0,producerCommandDataChannelVersion:p.producerCommandDataChannel?3:0,consumerScreenDataChannelVersion:p.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:p.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:Oe._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:p.videoTracksCount,red:p.serverAudioRed};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return o(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,c.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(c.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw c.error("[single] unable to set remote offer",i),h.log(E.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),h.log(E.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=S.patchSDP(i.sdp,!1,b.isBrokenH264(),!1,p.h264spsPpsIdrInKeyframe),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),h.log(E.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),h.log(E.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 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 o(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),p.breakVideoPayloadTypes&&(c.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes",null)),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){c.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent(F.REMOTE_TRACK_REMOVED,i.id,i,n.track)}),i.getTracks().find(n=>n.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(F.REMOTE_TRACK_ADDED,i.id,i,t.track)):c.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){c.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(c.debug("[single] connection state changed",{state:e.connectionState},t),h.log(E.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===V.IDLE||i===V.OPENED?this._setState(V.CONNECTING):e.iceConnectionState==="checking"&&this._setState(V.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(V.RECONNECTING);break;case"connected":this._setState(V.CONNECTED),S.getPeerConnectionHostInfo(e).then(r=>{r&&h.log(E.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(p.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{c.error("ServerTransport: Unable to replace track",r),h.log(E.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=b.baseChromeVersion();return e?p.isUnifiedPlanSupported("Chrome",e):p.isUnifiedPlanSupported(b.browserName(),Number(b.browserVersion()))}getStreamWaitingTimeMs(e,t){if(!this._pc)return h.log(E.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 h.log(E.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 h.log(E.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&bn,l=Math.ceil(d/Pn);return Math.min(100,Math.max(0,l))}};var F=(w=>(w.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",w.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",w.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",w.REMOTE_ALL_STALL="REMOTE_ALL_STALL",w.REMOTE_DATA_STATS="REMOTE_DATA_STATS",w.STATE_CHANGED="STATE_CHANGED",w.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",w.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",w.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",w.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",w.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",w.NETWORK_STATUS="NETWORK_STATUS",w.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",w))(F||{}),V=(d=>(d.IDLE="IDLE",d.OPENED="OPENED",d.CONNECTING="CONNECTING",d.RECONNECTING="RECONNECTING",d.CONNECTED="CONNECTED",d.CLOSED="CLOSED",d.FAILED="FAILED",d))(V||{}),se=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(se||{}),er=class extends ee{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){c.log("Update transport settings",e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){c.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,i=!1,r=!1){let n=r;for(let s of e){if(this._opened.indexOf(s)!==-1){c.warn(`The participant [${s}] has already had opened transport`);continue}if(this._allocated.indexOf(s)===-1){c.warn(`The participant [${s}] has no allocated transport`);continue}this._opened.push(s),n=!0}!n||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),c.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&c.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}getState(){var e,t;return this._topology==="SERVER"?(e=this._serverTransport)==null?void 0:e.getState():(t=this._directTransport)==null?void 0:t.getState()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===O.TOPOLOGY_CHANGED)return this._onTopologyChanged(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),h.log(E.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],n=e.offerToDeviceIdxs||[],s=i.length&&r.length?S.composeParticipantId(i[0],r[0],n[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){c.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&c.warn("Topology changed to DIRECT, but the allocated participants count more then one");let d=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=s===d;this._directTransport=this._createDirectTransport(d,l)}this._opened.indexOf(d)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_createDirectTransport(e,t=!1){let i=new st(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._dtListeners&&this._dtListeners.length>0&&c.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new Oe(this._signaling,this._mediaSource,this._serverSettings);return this._stListeners&&this._stListeners.length>0&&c.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;p.noiseSuppression!==e&&(p.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(h.log(E.PAT_WAITING_TIME_ERROR,"wrongTopology"),c.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(h.log(E.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var ct=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(ct||{}),tr=class extends ee{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,F.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,F.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,F.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,F.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===me.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Gt(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,p.voiceParams.interval)};this._interval=window.setTimeout(n,p.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===me.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===Ue.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e===se.DIRECT&&(this._activeParticipants=null)}};var ir=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(ir||{}),rr=class extends ee{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i===se.SERVER,this.subscribe(e,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,F.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,F.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>p.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*p.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent("SPEAKER_CHANGED",e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e===se.SERVER}};var ui=class extends ee{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,F.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===V.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),p.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),p.specListenerParams.volumeTimeout))),t===V.FAILED&&this._connectionTimeout&&(c.warn("Transport failed, send callSpecError"),h.log(E.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==V.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(c.warn("There is not connected transport, send callSpecError"),h.log(E.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),h.log(E.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&c.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Mn=1e3,Dn=1e4;var An=15,W=class extends ee{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._myLastRequestedLayouts={};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;h.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),h.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new oi,p.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Mn))}static current(){return W._current}static hangupAfterInit(){W._activationMutex&&!W._current&&(W._delayedHangup=!0)}static id(){var e,t;return((t=(e=W._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,s=!1,d){return o(this,null,function*(){if(W._activationMutex)throw h.log(E.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new L(D.FAILED);W._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let l=this._mediaSource.getMediaSettings();t===qe.CHAT||e.length>1?this._logWithMediaSettings(E.OUTGOING_MULTIPARTY_CALL,l):this._logWithMediaSettings(E.OUTGOING_CALL,l);let u=yield this._startConversation(e,t,Qe.OUTGOING,i,r,n,s,d);if(!this._conversation)throw new L(D.UNKNOWN_ERROR);if(this._participantState=j.ACCEPTED,this._signaling.changeMediaSettings(l),yield this._processConnection(u),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),W._delayedHangup)throw new L(D.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let I=Object.values(this._participants),R;return p.batchParticipantsOnStart&&(R=S.mapSharedParticipants(I)),g.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,R),this._onConversationParticipantListChunk(u),g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),W._current=this,this._conversation.concurrent?yield this._acceptConcurrent():p.batchParticipantsOnStart||this._setParticipantsStatus(I,J.WAITING),this._conversation}catch(l){throw this._close(l,"Unable to start conversation"),l}finally{W._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){var t;if(W._activationMutex)throw h.log(E.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new L(D.FAILED);W._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(E.JOIN_CONVERSATION,r);let n=yield this._joinConversation(e);if(!this._conversation)throw new L(D.UNKNOWN_ERROR);return this._conversation.observer=i,g.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(c.log("In waiting hall"),W._current=this,W._activationMutex=!1,this._signaling.readyToSend(),g.onLocalStatus(J.WAITING_HALL),this._conversation):this._onJoinPart2(n)}catch(i){throw W._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return o(this,null,function*(){var t,i,r,n;c.debug("Join conversation part 2"),W._activationMutex=!0;try{if(this._participantState=j.ACCEPTED,!this._conversation||!this._mediaSource)throw new L(D.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._processConnection(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),W._delayedHangup)throw new L(D.CANCELED);let s=Object.values(this._participants),d;p.batchParticipantsOnStart&&(d=S.mapSharedParticipants(s));let l=[];if((i=(t=e==null?void 0:e.rooms)==null?void 0:t.rooms)==null?void 0:i.length)for(let u of e.rooms.rooms)l.push({id:u.id,name:u.name,participantCount:u.participantCount,participantIds:yield Promise.all(((n=(r=u==null?void 0:u.participantIds)==null?void 0:r.map)==null?void 0:n.call(r,this._getExternalIdByParticipantId.bind(this)))||[]),participants:u==null?void 0:u.participants,active:u.active});return g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,d,l),this._onConversationParticipantListChunk(e),g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),W._current=this,p.batchParticipantsOnStart||this._setParticipantsStatus(s,J.WAITING),this._openTransport(s,!1),this._conversation}catch(s){throw this._close(s,"Unable to join conversation"),s}finally{W._activationMutex=!1}})}onPush(r){return o(this,arguments,function*(e,t=Z.USER,i){if(W._activationMutex)throw c.warn("Conversation: there is already running activation"),new L(D.REJECTED);W._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new L(D.UNKNOWN_ERROR);if(!n.conversation.participants.find(d=>{var l;return d.state===j.CALLED&&d.id===((l=this._conversation)==null?void 0:l.userId)}))throw c.log("Push rejected (there is an active call)"),h.log(E.PUSH,"rejected"),new L(D.REJECTED);if(yield this._processConnection(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),h.log(E.PUSH,"accepted"),W._current=this,W._delayedHangup)throw new L(D.CANCELED);W._activationMutex=!1}catch(n){throw W._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Ci.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>S.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return o(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new L(D.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(E.ACCEPT_CONCURRENT,e),c.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),g.onCallAccepted(),this._state="ACTIVE",this._participantState=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*(){var t;if(this._state!=="IDLE")throw h.log(E.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 L(D.UNKNOWN_ERROR);this._state="PROCESSING",c.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let i=this._mediaSource.getMediaSettings();this._logWithMediaSettings(E.ACCEPT_INCOMING,i),this._signaling.changeMediaSettings(i),yield this._signaling.acceptCall(i),this._participantState=j.ACCEPTED;let r=Object.values(this._participants),n;if(p.batchParticipantsOnStart&&(n=S.mapSharedParticipants(r)),g.onCallAccepted(),g.onLocalStream(this._mediaSource.getStream(),i),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,n),p.useParticipantListChunk){let l=yield this._getInitialParticiapntListChunk();(t=l==null?void 0:l.participants)==null||t.forEach(u=>{let I=S.composeId(u),R=this._participants[I];R&&(R.movieShareInfos=u.movieShareInfos)}),this._onConversationParticipantListChunk({participants:l})}g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let s=Tt(this._conversation.muteStates,Ne.MUTE),d=Tt(this._conversation.muteStates,Ne.MUTE_PERMANENT);for(let l of[s,d])l.length&&(yield this._processMuteState({mediaOptions:l,stateUpdated:!0}));return this._state="ACTIVE",this._changeFeatureSet(),p.batchParticipantsOnStart||this._setParticipantsStatus(r,J.WAITING),this._openTransport(r,!0),this._conversation}catch(i){throw this._close(i,"Unable to accept call"),i}})}decline(){return o(this,null,function*(){var e;if(this._state!=="IDLE")throw h.log(E.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(E.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=j.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(D.REJECTED)),this._close(new L(D.REJECTED))})}hangup(){return o(this,null,function*(){c.debug("Hangup");let e=this._state==="ACTIVE"?D.HUNGUP:D.CANCELED;h.log(E.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new L(e))):g.onHangup(new L(D.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new L(D.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=D.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(S.composeId(n),n,r)})}removeParticipant(e,t=!1){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let n of e)(n.state===j.CALLED||n.state===j.ACCEPTED)&&(this._transport.isAllocated(n.id)||this._transport.allocate(n.id,t)),n.state===j.ACCEPTED&&i.push(n.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&c.error(t,e),c.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(D.FAILED):h.log(E.ERROR,e.hangup),W._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([D.CANCELED,D.NOT_FRIENDS,D.CALLEE_IS_OFFLINE,D.CALLER_IS_BLOCKED,D.CALLER_IS_REJECTED].indexOf(e.hangup)!==-1||e.hangup===D.REJECTED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===D.HUNGUP&&(!e.remote||this._participantState===j.CALLED)){g.onHangup(e,i),this.destroy();return}if(e.hangup===D.MISSED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===D.SOCKET_CLOSED&&W._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===D.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=j.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),h.destroy(),this._conversation=null,this._myLastRequestedLayouts={},W._current=null,W._delayedHangup=!1,g.onHangup(e||new L(D.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(),h.destroy(),this._conversation=null,this._myLastRequestedLayouts={},W._current=null,W._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return o(this,null,function*(){let t=yield this._api.getConversationParams(e);c.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let s=r.urls.filter((d,l,u)=>u.indexOf(d)===l);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return p.iceServers=i,p.wssBase=t.endpoint,p.wssToken=t.token,t.client_type&&(p.clientType=t.client_type),p.externalUserType=t.external_user_type,t})}_addGeoParamsToEndpoint(e,t){return t.isp_as_no&&(e+=`&ispAsNo=${t.isp_as_no}`),t.isp_as_org&&(e+=`&ispAsOrg=${t.isp_as_org}`),t.loc_cc&&(e+=`&locCc=${t.loc_cc}`),t.loc_reg&&(e+=`&locReg=${t.loc_reg}`),e}_startConversation(e,t,i,r,n="",s=!1,d=!1,l){return o(this,null,function*(){let u=S.uuid();c.debug("Conversation: start",{conversationId:u,opponentIds:e,opponentType:t,direction:i});let I=r.includes(ge.VIDEO),R=yield this._api.startConversation(u,e,t,I,n,s,d,{onlyAdminCanShareMovie:l});c.debug("Api.startConversation",R);let A=yield this._getConversationParams(R.id);R.endpoint=this._addGeoParamsToEndpoint(R.endpoint,A);let w=yield this._connectSignaling($e.START,R);return yield this._setConversation(R,w,i),w})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n,observedIds:s}=e;c.debug("Conversation: join",{conversationId:t,joinLink:n,observedIds:s});let d=i.includes(ge.VIDEO),l;if(t)l=yield this._api.joinConversation(t,d,r);else if(n)l=yield this._api.joinConversationByLink(n,d,s);else throw new L(D.UNKNOWN_ERROR);c.debug("Api.joinConversation",l),yield this._getConversationParams(l.id);let u=yield this._connectSignaling($e.JOIN,l);return yield this._setConversation(l,u,Qe.JOINING),u})}_prepareConversation(r){return o(this,arguments,function*(e,t=Z.USER,i){c.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let n=this._api.getUserId();if(!n)throw new L(D.UNKNOWN_ERROR);let s=yield this._getConversationParams(e),d=s.device_idx||0,l=`${p.wssBase}?userId=${n}&entityType=${t}&deviceIdx=${d}&conversationId=${e}&token=${p.wssToken}`;l=this._addGeoParamsToEndpoint(l,s);let u={id:e,peerId:i,endpoint:l,is_concurrent:!1,p2p_forbidden:!1,device_idx:d},I=yield this._connectSignaling($e.ACCEPT,u);return W._current&&(W._current._participantState===j.ACCEPTED||W._current._participantState===j.CALLED)?(c.log("Push rejected (busy)"),h.log(E.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(D.BUSY),Promise.reject({hangup:D.BUSY})):(W._current&&(W._current.destroy(),W._current=null),yield this._setConversation(u,I,Qe.INCOMING,t),I)})}_createParticipant(e){return o(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:Se(),participantState:{},state:j.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[]},e);if(e.externalId){let r=S.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(r,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return((i=t.observedIds)==null?void 0:i.length)&&(t.externalId.observer=!0),this._setParticipantMarkers(t,t.markers),t})}_getParticipantId(e){return o(this,null,function*(){try{let t=S.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new L(D.NETWORK_ERROR),t),t}})}_setConversation(n,s,d){return o(this,arguments,function*(e,t,i,r=Z.USER){yield this._prepareParticipants(t.conversation.participants);let l=this._api.getUserId(),u=e.device_idx||0;if(!l){let A=(t.conversation.participants||[]).find(w=>S.comparePeerId(w.peerId,t.peerId));if(!A)throw new L(D.UNKNOWN_ERROR);l=Number(A.id),A.idType&&(r=A.idType),A.deviceIdx&&(u=A.deviceIdx),this._api.setUserId(l)}let I=S.composeParticipantId(l,r,u),R=yield this._getParticipantId(I);this._conversation={userId:l,compositeUserId:I,externalId:R,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],featuresPerRole:t.conversation.featuresPerRole,id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||se.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(p.forceRelayPolicy=e.p2p_forbidden),h.log(E.RELAY_POLICY,p.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new L(D.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.featuresPerRole=e.conversation.featuresPerRole,this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||se.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new xi;return this.subscribe(e,De.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,De.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new Ht(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,Te.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,Te.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_processConnection(e){return o(this,null,function*(){yield this._registerConnectionParticipants(e),this._processConnectionData(e)})}_prepareParticipants(e){return o(this,null,function*(){let t=e.map(i=>i.id);t.length&&(yield this._api.prepareUserIds(t))})}_onConversationParticipantListChunk(e){let t=e.participants;t&&g.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(this._createParticipantListChunk(t)))}_createParticipantListChunk(e){return ze(ze({},{participants:[],countBefore:0,countAfter:0,markerFound:!1}),e)}_participantListChunkToExternalChunk(e){let t=S.mapSharedParticipants(e.participants.map(i=>{let r=S.composeId(i);return this._participants[r]}));return Ii(ze({},e),{participants:t})}_registerConnectionParticipants(e){return o(this,null,function*(){var t,i;yield this._registerParticipants(e.conversation.participants),((t=e.participants)==null?void 0:t.participants)&&(yield this._registerParticipants((i=e.participants)==null?void 0:i.participants))})}_registerParticipants(e){return o(this,null,function*(){if(!!this._conversation)for(let t of e){let i=S.composeId(t);if(this._isMe(i)){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(c.debug(`Local roles changed: ${t.roles}`),g.onLocalRolesChanged(this._conversation.roles)),yield this._registerParticipantLocalMuteState(t);continue}if(t.state===j.HUNGUP||t.state===j.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],D.HUNGUP);continue}this._registerParticipantInCache(yield this._createParticipant({id:i,externalId:t.externalId&&fe.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:Se(t.mediaSettings),participantState:S.mapParticipantState(t),state:t.state,roles:t.roles||[],status:p.batchParticipantsOnStart?J.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[],markers:this._denormalizeMarkers(i,t.markers),movieShareInfos:t.movieShareInfos})),t.roles&&t.roles.length&&(c.debug(`Roles for participant [${i}] changed: ${t.roles}`),g.onRolesChanged(this._participants[i].externalId,t.roles))}})}_registerParticipantLocalMuteState(e){return o(this,null,function*(){if(!e.muteStates)return Promise.resolve();let t=Tt(e.muteStates,Ne.MUTE),i=Tt(e.muteStates,Ne.MUTE_PERMANENT);for(let r of[t,i])!r.length||(yield this._onMuteParticipant({muteStates:e.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:r,stateUpdated:!0}))})}_getStatusByTransportState(e){let t;return e===V.CONNECTED?t=J.CONNECTED:e===V.CONNECTING||e===V.OPENED?t=J.CONNECTING:e===V.RECONNECTING&&(t=J.RECONNECT),t}_registerParticipantInCache(e){return this._participants[e.id]=e}_getExistedParticipantByIdOrCreate(e){return o(this,null,function*(){return this._participants[e]||this._createParticipant({id:e})})}_getExternalIdByParticipantId(e){return o(this,null,function*(){var t;return this._isMe(e)?this._conversation.externalId:p.useParticipantListChunk?(yield this._getExistedParticipantByIdOrCreate(e)).externalId:(t=this._participants[e])==null?void 0:t.externalId})}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){return o(this,null,function*(){if(p.useParticipantListChunk){let i=this._registerParticipantInCache(yield this._getExistedParticipantByIdOrCreate(e));return this._setParticipantMarkers(i,t),i}return this._participants[e]})}_warnParticipantNotInConversation(e){c.warn(`Participant [${e}] isn't in conversation`)}_setParticipantMarkers(e,t){return e.markers=this._denormalizeMarkers(e.id,t),e}_denormalizeMarkers(e,t){if(!t)return null;let i=Object.values(t).find(r=>"ts"in r&&"rank"in r);return Object.entries(t).reduce((r,[n,s])=>(r[n]=Ii(ze(ze({},i),s),{id:e}),r),{})}_processConnectionData(e){return o(this,null,function*(){S.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0,stateUpdated:!0}),e.conversation.pinnedParticipantId&&(yield this._onPinParticipant(e.conversation.pinnedParticipantId)),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Ti.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 ci,this.subscribe(this._transport,F.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,F.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,F.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,F.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,F.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,F.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,F.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,F.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,F.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,F.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,F.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Qe.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,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new rr(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,ir.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new di(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new ui(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=b.getCameras().length,t=b.getMicrophones().length;c.debug("Cameras: "+e+(b.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(b.hasMicrophonePermission()?"✔":"✖")),h.log(E.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){h.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===j.CALLED||e.state===j.ACCEPTED||this._state==="CLOSE"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),!!this._participants[e.id]&&(t===D.HUNGUP?this._setParticipantsStatus([e],J.HANGUP):this._setParticipantsStatus([e],J.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Pe.CAMERA,stopStream:!0}]),delete this._participants[e.id],g.onRemoteRemoved(e.externalId,e.markers)))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){c.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return o(this,null,function*(){c.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===j.ACCEPTED||r.state===j.CALLED)){c.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(r=this._registerParticipantInCache(yield this._createParticipant({id:e,externalId:t.externalId&&fe.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:Se(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}))),this._setParticipantsStatus([r],J.WAITING),i?(r.state=j.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=j.CALLED,this._transport.allocate(r.id,!0),h.log(E.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){c.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=An;i++){let r=S.compose(e,i),n=this._participants[r];n&&t.push(n)}if(!t.length){this._warnParticipantNotInConversation(e);return}if(this._transport)for(let i of t)this._transport.close(i.id);h.log(E.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new Ht(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 h.log(E.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return h.log(E.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return o(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let n=typeof r.uid=="object"?r.uid:fe.fromId(r.uid),s=fe.toString(n);i[s]=r.priority}for(let r of Object.values(this._participants)){let n=fe.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return o(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return o(this,null,function*(){let t={};return t[He(e)]={keyFrameRequested:!0},this._signaling.updateDisplayLayout(t)})}requestTestMode(e,t){return o(this,null,function*(){return this._signaling.requestTestMode(e,t)})}updateDisplayLayout(e){return o(this,null,function*(){if(e.length<1||!this._signaling.ready)return;c.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:fe.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(n);if(!s){let I=fe.toString(n);c.log(`Unknown participant external ID ${I}`);continue}let d=S.compose(s,n.deviceIdx),l=He({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),u=this._participants[d];u?u.lastRequestedLayouts[l]=r:this._isMe(d)&&(this._myLastRequestedLayouts[l]=r),Vt(r)?(this._isMe(d)&&delete this._myLastRequestedLayouts[l],this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now())):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&p.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=r)}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>p.videoTracksCount;){let r=i.next();if(r.done){c.error("Cannot accommodate all streaming requests: tracks available "+p.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]={stopStream:!0}}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(c.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Ft(e),r=this._participants[i.participantId],{externalId:n}=this._conversation,s=this._isMe(i.participantId);if(r){if(i.streamName&&(i.mediaType===Pe.STREAM||i.mediaType===Pe.MOVIE)){let d={stream:null,streamName:i.streamName,mediaType:i.mediaType};s?g.onLocalLive(n,d):g.onRemoteLive(r.externalId,d)}else s||g.onRemoteStream(r.externalId,null);h.log(E.PAT_DEALLOCATED)}else c.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return o(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,n]of Object.entries(t.errorCodeByParticipantId||{})){let s=Ft(r),d=this._participants[s.participantId];if(d){let l;typeof n!="number"?(c.warn(`Unexpected error code ${n} received for participant ${s.participantId}`),l=Lr.UNKNOWN_ERROR):l=Nr(n),i.push({externalId:d.externalId,errorReason:l})}}if(i&&i.length)throw new mi("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]+Dn>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e)}_onParticipantSourcesUpdate(e){if(this._conversation){c.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){c.log("Promoted in waiting hall",!e.demote),e.demote?(c.log("Kicked from waiting hall"),this._close(new L(D.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return o(this,arguments,function*(e,t=0,i=[]){c.log(`Chat room updated: ${e}`);let n=[],s=[];i.length&&(i.forEach(d=>{if(d.externalId){let l=Ee.fromSignaling(d.externalId);n.push(l),this._api.cacheExternalId(d.id.id,l)}else s.push(S.decomposeId(d.id.id).id)}),s.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(s))),g.onChatRoomUpdated(e,t,n)})}_onSharedMovieUpdate(e){return o(this,null,function*(){c.log(`Shared movie updated: ${e.notification}`);let{externalId:t}=this._conversation,{data:i}=e;for(let r of i)if(this._isMe(r.participantId))g.onLocalLiveUpdate(t,r);else{let s=yield this._getExternalIdByParticipantId(r.participantId);s&&g.onRemoteLiveUpdate(s,r)}})}_onSharedMovieInfoStarted(e){return o(this,null,function*(){var n;c.log(`Shared movie started data received: ${e.notification}`);let{externalId:t}=this._conversation,{movieShareInfo:i}=e;if(this._isMe(i.initiatorId))g.onLocalSharedMovieInfo(t,i);else{let s=yield this._getExternalIdByParticipantId(i.initiatorId);s&&g.onRemoteSharedMovieInfo(s,i)}i&&this._transport.getTopology()===se.SERVER&&this._transport.getState()===V.IDLE&&this._participantState!==j.CALLED&&this._transport.open(this._transport.allocated(),null,!!((n=this._conversation)==null?void 0:n.observer),!0)})}_onSharedMovieInfoStopped(e){return o(this,null,function*(){c.log(`Shared movie stopped data received: ${e.notification}`);let{externalId:t}=this._conversation,{initiatorId:i,movieId:r,source:n}=e,s={initiatorId:i,movieId:r,source:n};if(this._isMe(i))g.onLocalSharedMovieStoppedInfo(t,s);else{let l=yield this._getExternalIdByParticipantId(i);l&&g.onRemoteSharedMovieStoppedInfo(l,s)}})}_waitForStreamIfNeeded(e){var d,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||p.producerScreenDataChannel&&t.mediaType===Pe.SCREEN)return;let i=He(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){c.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),h.log(E.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let u=t.participantId,I=this._participants[u],{externalId:R}=this._conversation,A=this._isMe(u);if(!I&&!A){h.log(E.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${u}`);return}let w=A?R:I.externalId,H=this._streamByStreamId.get(n);if(!H){h.log(E.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${n}`);return}h.log(E.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let re=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(re===Pe.STREAM||re===Pe.MOVIE){if((l=e.participantStreamDescription)==null?void 0:l.streamName){let ve={streamName:e.participantStreamDescription.streamName,stream:H,mediaType:re};A?g.onLocalLive(w,ve):g.onRemoteLive(w,ve)}}else if(p.producerScreenTrack&&re===Pe.SCREEN)g.onRemoteScreenStream(I.externalId,H);else if(!A){let ve=(p.producerScreenTrack?null:I.secondStream)||H;g.onRemoteStream(I.externalId,ve)}}else{c.debug(`Waiting for ${s} until stream ${n} 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(He(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(He(i)))return i}else{let i={participantId:t,mediaType:Pe.CAMERA};if(this._streamIdByStreamDescription.has(He(i)))return i;let r={participantId:t,mediaType:Pe.SCREEN};if(this._streamIdByStreamDescription.has(He(r)))return r}return c.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?S.includesOneOf(this._conversation.roles,[lt.ADMIN,lt.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!S.includesOneOf(this._conversation.roles,[lt.ADMIN,lt.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)})}enableFeatureForRoles(e,t){return o(this,null,function*(){yield this._signaling.enableFeatureForRoles(e,t)})}pinParticipant(e,t){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return o(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return o(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Tr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return o(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=_a(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let s=n.participants||[],d=[],l=[],u=null;return s.length&&(s.forEach(I=>{if(I.externalId){let R=Ee.fromSignaling(I.externalId);d.push(R),this._api.cacheExternalId(I.id.id,R)}else l.push(S.decomposeId(I.id.id).id)}),l.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(l)),n.hasMore&&(u=ha(s[s.length-1].id))),{participants:d,pageMarker:u,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return o(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return o(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return o(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return o(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(r){return o(this,arguments,function*({movieId:e,gain:t,metadata:i}){let n={movieId:e};(t||t===0)&&(n.gain=t),i&&(n.metadata=i);let s=yield this._signaling.addMovie(n);if(s.error)throw new Error(s.error);return{movieId:s.movieId,streamType:s.streamType}})}updateMovie(e,t,i,r){return o(this,null,function*(){let n={movieId:e};(t||t===0)&&(n.gain=t),(i||i===0)&&(n.offset=i),typeof r!==void 0&&(n.pause=r);let s=yield this._signaling.updateMovie(n);if(s.error)throw new Error(s.error)})}removeMovie(e){return o(this,null,function*(){let t={movieId:e},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}updateRooms(e,t){return o(this,null,function*(){c.debug("Rooms: update",{rooms:e,assignRandomly:t});let i=yield this._signaling.updateRooms(e,t);if(i.error)throw new Error(i.error)})}activateRooms(e,t){return o(this,null,function*(){c.debug("Rooms: activate",{roomIds:e,deactivate:t});let i=yield this._signaling.activateRooms(e,t);if(i.error)throw new Error(i.error)})}switchRoom(e,t){return o(this,null,function*(){c.debug("Room: switch",{toRoomId:e,participantId:t});let i=yield this._signaling.switchRoom(e,t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",n=null){return o(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},d=yield this._signaling.startStream(s);return d.error?Promise.reject(d.message):d})}stopStream(){return o(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return o(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return o(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return o(this,null,function*(){var r;if(e<p.videoMinWidth||t<p.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<p.videoMinWidth||i.effect.height<p.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");p.videoEffectMaxHeight=i.effect.height,p.videoEffectMaxWidth=i.effect.width}return p.videoMaxWidth=e,p.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return o(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}getParticipants(e){return o(this,null,function*(){let t=e.externalIds.map(s=>({id:s.id,type:p.externalUserType})),i=yield this._signaling.getParticipants(t);if(i.error)throw new Error(i.error);let r=i.participants,n=this._transport.getState();return Promise.all(r.map(s=>o(this,null,function*(){var l;let d=S.composeId(s);return this._createParticipant({id:d,externalId:s.externalId&&fe.fromSignaling(s.externalId,s.deviceIdx||0),mediaSettings:Se(s.mediaSettings),participantState:S.mapParticipantState(s),state:s.state,roles:s.roles||[],status:(l=this._getStatusByTransportState(n))!=null?l:J.WAITING,muteStates:s.muteStates||{},unmuteOptions:s.unmuteOptions||[],observedIds:s.observedIds||[],markers:this._denormalizeMarkers(d,s.markers)})}))).then(S.mapSharedParticipants)})}getParticipantListChunk(e){return o(this,null,function*(){var d;c.log("Request participant list chunk",e);let t=yield this._signaling.getParticipantListChunk(e);if(t.error)throw new Error(t.error);let i=this._createParticipantListChunk(t.chunk),r=i.participants.filter(l=>{let u=S.composeId(l);return!this._participants[u]});yield this._registerParticipants(r);let n=(d=this._transport)==null?void 0:d.getState();return i.participants.forEach(l=>{var R;let u=S.composeId(l),I=this._participants[u];I.status=(R=this._getStatusByTransportState(n))!=null?R:J.WAITING,Object.assign(I.muteStates,l.muteStates),Object.assign(I.unmuteOptions,l.unmuteOptions)}),this._participantListChunkToExternalChunk(i)})}_getInitialParticiapntListChunk(){return o(this,null,function*(){let e=p.participantListChunkInitIndex,t=p.participantListChunkInitCount,i="GRID",r=yield this._signaling.getParticipantListChunk({listType:i,fromIdx:e,count:t});return c.debug("Get initial participant list chunk",r.chunk),r.chunk})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t,i;!this._conversation||(c.debug("Local media stream changed",e.mediaSettings),g.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return o(this,null,function*(){var t,i;if(c.log("Screen sharing changed",e.track,e.mediaSettings),p.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;g.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){c.debug(`Remote media settings changed [${e}]`,t);let{externalId:i}=this._conversation;if(this._isMe(e)){g.onLocalMediaSettings(i,t);return}let n=this._participants[e];if(!n){this._warnParticipantNotInConversation(e);return}n.mediaSettings=t,this._state==="ACTIVE"&&g.onRemoteMediaSettings(n.externalId,t,n.markers),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t)}_changeRemoteParticipantState(e,t){c.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];if(!i){this._warnParticipantNotInConversation(e);return}i.participantState=t||{},this._state==="ACTIVE"&&g.onRemoteParticipantState(i.externalId,i.participantState,i.markers)}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(c.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),g.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case 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,e.markers);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);case O.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e);case O.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e);case O.MOVIE_SHARE_STARTED:return this._onSharedMovieInfoStarted(e);case O.MOVIE_SHARE_STOPPED:return this._onSharedMovieInfoStopped(e);case O.ROOMS_UPDATED:return this._onRoomsUpdated(e);case O.ROOM_UPDATED:return this._onRoomUpdated(e);case O.ROOM_PARTICIPANTS_UPDATED:return this._onRoomParticipantsUpdated(e)}}_onSignalingReconnect(e){return o(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._conversation.featuresPerRole=e.conversation.featuresPerRole,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?yield this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&(yield this._onPinParticipant(this._conversation.pinnedParticipantId,!0))),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let s=S.composeId(n),d=n.roles||[];if(this._isMe(s)){t=Se(n.mediaSettings),Ot(this._conversation.roles,d)||this._onRolesChanged(s,d);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let u=Se(n.mediaSettings);qr(u,l.mediaSettings)||this._changeRemoteMediaSettings(s,u);let I=S.mapParticipantState(n),R=l.participantState;S.isEqualParticipantState(I,R)||this._changeRemoteParticipantState(s,I),Ot(d,l.roles)||this._onRolesChanged(l.id,d)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],D.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){c.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return o(this,null,function*(){let t=S.composeMessageId(e),i=S.getPeerIdString(e.peerId);if(c.debug(`Participant accepted call [${t}]`),this._conversation&&this._isMe(t)){this._close(new L(D.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(r=this._registerParticipantInCache(yield this._createParticipant({id:t,mediaSettings:Se(e.mediaSettings)}))),r.state=j.ACCEPTED,r.mediaSettings=Se(e.mediaSettings),this._logWithMediaSettings(E.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Qe.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){return o(this,null,function*(){c.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=S.composeMessageId(e);if(this._conversation&&this._isMe(t)){this._close(new L(e.reason,{remote:!0}));return}yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers);let i=this._participants[t];if(!i){this._warnParticipantNotInConversation(t);return}this._transport&&this._transport.close(t),i.state=e.reason===D.REJECTED?j.REJECTED:j.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,D.HUNGUP)})}_onAddedParticipant(e){return o(this,null,function*(){var r,n;c.debug(`Participant added [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state!==j.HUNGUP&&i.state!==j.REJECTED){c.debug(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&fe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:Se(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}))),i.state=j.CALLED,i.mediaSettings=Se((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=S.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),g.onParticipantAdded(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return o(this,null,function*(){var r,n;c.debug(`Participant joined [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state===j.ACCEPTED){c.warn(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&fe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:Se(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[],markers:this._denormalizeMarkers(t,e.participant.markers)}))),this._conversation&&this._conversation.direction===Qe.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=j.ACCEPTED,i.mediaSettings=Se(e.mediaSettings),i.participantState=S.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],J.CONNECTED):this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((n=this._conversation)==null?void 0:n.observer))),g.onParticipantJoined(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i),g.onMuteStates(i.muteStates,i.unmuteOptions,Object.keys(i.muteStates),!1,!1,i.externalId,void 0,!0)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new L(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){return o(this,null,function*(){let t=S.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,Se(e.mediaSettings))})}_onParticipantStateChanged(e){return o(this,null,function*(){let t=S.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteParticipantState(t,S.mapParticipantState(e))})}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._conversation.featuresPerRole=e.featuresPerRole,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),g.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=Se(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),p.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){c.debug("Got settings update notification",e);let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Qi(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){c.debug("Got video quality update notification",e);let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=Qi(this._serverSettings,r),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=S.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return o(this,null,function*(){g.onDeviceSwitched(ge.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return o(this,null,function*(){let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),g.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return o(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),g.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return o(this,null,function*(){var i;if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let r=yield this._getParticipantId(e.initiator);g.onRecordStarted(r,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else g.onRecordStopped();this._conversation.recordInfo=e,e&&this._transport.getTopology()===se.SERVER&&this._participantState!==j.CALLED&&this._transport.open(this._transport.allocated(),null,!!((i=this._conversation)==null?void 0:i.observer),!0)})}_onRolesChanged(e,t){if(this._conversation&&this._isMe(e)&&!Ot(this._conversation.roles,t)){c.debug(`Local roles changed: ${t}`),this._conversation.roles=t,g.onLocalRolesChanged(t),this._processMuteState({mediaOptions:Tt(this._conversation.muteStates,Ne.MUTE_PERMANENT),stateUpdated:!0});return}let i=this._participants[e];i&&!Ot(i.roles,t)&&(c.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,g.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&!this._isMe(e.participantId)){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),g.onMuteStates(i,r,n,e.muteAll,e.unmute,d.externalId,s==null?void 0:s.externalId,e.stateUpdated,e.requestedMedia));return}if(!(S.isObjectsEquals(this._conversation.muteStates,i)&&S.isArraysEquals(this._conversation.unmuteOptions,r)&&!n.length)){if(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,this._isMe(e.adminId)){e.muteAll&&g.onMuteStates(i,r,n,e.muteAll,e.unmute,null,this._conversation.externalId,e.stateUpdated,e.requestedMedia);return}yield this._processMuteState({mediaOptions:n,muteAll:e.muteAll,unmute:e.unmute,serverSettings:t,admin:s,stateUpdated:e.stateUpdated,requestedMedia:e.requestedMedia})}})}_processMuteState(l){return o(this,arguments,function*({mediaOptions:e=[],muteAll:t=!1,unmute:i=!1,serverSettings:r=null,admin:n=null,stateUpdated:s,requestedMedia:d}){if(!this._conversation||!this._mediaSource||this._participantState!==j.ACCEPTED)return;let u=Object.assign({},this._conversation.muteStates),I=this._conversation.unmuteOptions,R=this._mediaSource.getMediaSettings(),A=Object.entries(u);for(let[w,H]of A)if(!(H!==Ne.MUTE&&H!==Ne.MUTE_PERMANENT)&&(this._isCallAdmin()&&H===Ne.MUTE_PERMANENT&&!t&&(u[w]=Ne.MUTE),!(!e.includes(w)||i)))switch(w){case ge.VIDEO:R.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(g.onDeviceSwitched(ge.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case ge.AUDIO:R.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(g.onDeviceSwitched(ge.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case ge.SCREEN_SHARING:R.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(g.onDeviceSwitched(ge.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}g.onMuteStates(u,I,e,t,i,null,n==null?void 0:n.externalId,s,d)})}_onPinParticipant(e,t=!1,i){return o(this,null,function*(){if(!this._conversation)return;let r=this._conversation.pinnedParticipantId;if(r&&r!==e)if(this._isMe(r))g.onLocalPin(!0);else{let n=yield this._getExternalIdByParticipantId(r);n&&g.onPinnedParticipant(n,!0,this._denormalizeMarkers(e,i))}if(this._isMe(e))g.onLocalPin(t);else{let n=yield this._getExternalIdByParticipantId(e);n&&g.onPinnedParticipant(n,t,this._denormalizeMarkers(e,i))}this._conversation.pinnedParticipantId=t?null:e})}_onOptionsChanged(e){this._conversation&&!Ir(this._conversation.options,e)&&(this._conversation.options=e,g.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let n;if(this._isMe(i)||i==="")n=this._conversation.networkRating;else if(this._participants[i])n=this._participants[i].networkRating;else continue;if(n!==r)if(this._isMe(i)||i==="")this._conversation.networkRating=r,g.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;c.log("Received network status update: ",e),g.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(p.producerScreenTrack){g.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,p.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){c.error("Received remote stream notification for a participant that has no track associated with it",r);return}let n=this._streamIdByStreamDescription.get(r);if(!n||this._streamWaitTimerByStreamDescription.has(r)){c.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(n);if(!s){h.log(E.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${n}`);return}g.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&g.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===se.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(vr.ADD_PARTICIPANT);g.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&g.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}g.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){c.debug(`Transport state has changed: ${t}`,e);let i=this._getStatusByTransportState(t);if(!i)return;let r=e.reduce((n,s)=>{if(s in this._participants){let d=this._participants[s];n.push(d),t===V.CONNECTED&&(d.remoteStream||(d.mediaSettings&&this._changeRemoteMediaSettings(s,d.mediaSettings),this._changeRemoteParticipantState(s,d.participantState)),this._updateDisplayLayoutFromCache(s))}else this._warnParticipantNotInConversation(s);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){var t;if(c.debug(`Local transport state has changed: ${e}`),e===V.CONNECTED&&(g.onLocalStatus(J.CONNECTED),((t=this._transport)==null?void 0:t.getTopology())===se.SERVER)){let i=Object.values(this._myLastRequestedLayouts);yield this.updateDisplayLayout(i)}e===V.CONNECTING&&g.onLocalStatus(J.CONNECTING),e===V.RECONNECTING&&g.onLocalStatus(J.RECONNECT),e===V.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(D.FAILED)),this._close(new L(D.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(Ue.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i),g.onRemoteMixedAudioStream(t);else if(e.startsWith(Ue.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))c.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{c.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(c.warn(`Conversation: track added before participant [${e}]`),r=this._registerParticipantInCache(yield this._createParticipant({id:e})),this._setParticipantsStatus([r],J.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===me.audio&&(this._audioOutput.add(i),p.preserveAudioTracks||t.removeTrack(i)),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;g.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),p.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(c.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case me.audio:this._removeAudioTrack(e,t,i);break;case me.video:case me.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Ue.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e===se.DIRECT&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let n=this._participants[r];e||this._lastStalled[r]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,J.RECONNECT),i.length&&this._setParticipantsStatus(i,J.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let s=this._participants[n];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let s=this._participants[n];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,J.RECONNECT),r.length&&this._setParticipantsStatus(r,J.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!b.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(c.debug("Toggle join availability",{available:t,chatId:e}),g.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==se.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,s)=>(s.status!==t&&(s.status=t,p.batchParticipantsOnStart?n.push(s.externalId):g.onParticipantStatus(s.externalId,t,i)),n),[]);!r.length||p.batchParticipantsOnStart&&g.onRemoteStatus(r,t,i)}_onJoinLinkChanged(e){g.onJoinLinkChanged(e.joinLink)}_onRoomsUpdated(e){return o(this,null,function*(){var i,r;let t={};for(let n in Ri){if(e.updates[n]===void 0)continue;let s=e.updates[n];!s||(t[n]={rooms:yield Promise.all(((r=(i=s==null?void 0:s.rooms)==null?void 0:i.map)==null?void 0:r.call(i,this._convertRoomToExternal))||[]),roomIds:s==null?void 0:s.roomIds})}g.onRoomsUpdated(t)})}_onRoomUpdated(e){return o(this,null,function*(){let t=null;e.room&&(t=yield this._convertRoomToExternal(e.room)),g.onRoomUpdated(e.events,e.roomId,t)})}_convertRoomToExternal(e){return o(this,null,function*(){var n,s,d,l,u,I;let[t,i,r]=yield Promise.all([Promise.all(((s=(n=e==null?void 0:e.participantIds)==null?void 0:n.map)==null?void 0:s.call(n,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((l=(d=e==null?void 0:e.addParticipantIds)==null?void 0:d.map)==null?void 0:l.call(d,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((I=(u=e==null?void 0:e.removeParticipantIds)==null?void 0:u.map)==null?void 0:I.call(u,this._getExternalIdByParticipantId.bind(this)))||[])]);return{id:e.id,name:e.name,participantCount:e.participantCount,participantIds:t,addParticipantIds:i,removeParticipantIds:r,participants:e.participants,active:e.active}})}_onRoomParticipantsUpdated(e){return o(this,null,function*(){var s,d,l,u;let t=yield Promise.all(((d=(s=e.addedParticipantIds)==null?void 0:s.map)==null?void 0:d.call(s,this._getExternalIdByParticipantId.bind(this)))||[]),i=this._transport.getState(),r=yield Promise.all(((u=(l=e==null?void 0:e.addedParticipants)==null?void 0:l.map)==null?void 0:u.call(l,I=>o(this,null,function*(){var A;let R=S.composeId(I);return this._createParticipant({id:R,externalId:I.externalId&&fe.fromSignaling(I.externalId,I.deviceIdx||0),mediaSettings:Se(I.mediaSettings),participantState:S.mapParticipantState(I),state:I.state,roles:I.roles||[],status:(A=this._getStatusByTransportState(i))!=null?A:J.WAITING,muteStates:I.muteStates||{},unmuteOptions:I.unmuteOptions||[],observedIds:I.observedIds||[],markers:this._denormalizeMarkers(R,I.markers)})})))||[]),n={roomId:e.roomId,participantCount:e.participantCount,addedParticipantIds:t,addedParticipants:r,removedParticipantMarkers:e==null?void 0:e.removedParticipantMarkers};g.onRoomParticipantsUpdated(n)})}_isMe(e){var t;return e===((t=this._conversation)==null?void 0:t.compositeUserId)}},N=W;N._delayedHangup=!1;var mi=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,mi.prototype),this.participantErrors=t}};var Kt,hi=null;function On(){return o(this,null,function*(){var a;if(p.apiEnv!=="AUTO")return p.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(a=i==null?void 0:i.Answer[0])==null?void 0:a.data;if(!r)throw new Error("Wrong DNS response");return c.debug("Resolved API endpoint",r),r}catch(e){return c.warn("Failed to resolve API endpoint using DNS, default is used",e),p.apiEndpoint}})}function va(){return Kt?Promise.resolve(Kt):hi||(hi=On().then(a=>Kt=a).finally(()=>hi=null))}function Ea(){if(!p.apiKey)throw new L(ne.API,{message:"Required argument apiAppKey not passed"})}function ar(i){return o(this,arguments,function*(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;yield va();let r=Ta(a,e,t),n=new window.Blob([r],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${Kt}/fb.do`,n)})}function Ia(i){return o(this,arguments,function*(a,e={},t=!1){yield va();let r=Ta(a,e,t);return kn(r)})}function kn(a){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${Kt}/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 Ta(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=p.apiKey),t||(te.sessionKey?e.session_key=te.sessionKey:te.accessToken&&(e.access_token=te.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 xn=10,Ln=700,Nn=3e3,_i=class extends Mt{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return o(this,arguments,function*(e,t={},i=!1){let n=s=>o(this,null,function*(){try{return yield Ia(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<xn))return yield S.delay(Math.min(s*Ln,Nn)),n(s);throw c.warn(e,"error",d),d}});return n(0)})}_call(r){return o(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){c.warn("Api call error",n);let s=ne.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=D.SERVICE_DISABLED;break;case 1102:s=D.CALLEE_IS_OFFLINE;break;case 1103:s=D.NOT_FRIENDS;break;case 1104:case 1106:s=D.EXTERNAL_API_ERROR;break;case 1113:s=D.CALLER_IS_REJECTED;break}throw new L(s,{message:n.error_msg,code:n.error_code})}})}userId(e){return o(this,null,function*(){let t=S.decomposeId(e).id;return te.isEmpty()?Ee.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),Ee.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return o(this,null,function*(){te.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return o(this,null,function*(){if(!this._uuid){let t=Xe.get("uuid");t||(t=S.uuid(),Xe.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:p.appVersion,client_type:"SDK_JS"}};return p.authToken&&(e.session_data.auth_token=p.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),te.sessionKey=t.session_key,te.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&g.onTokenExpired(),new L(ne.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${p.appName}:${p.sdkVersion}`,platform:p.platform,items:e})};ar("log.externalLog",t)}init(){Ea()}joinConversation(e,t=!1,i){return o(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:p.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(n){return o(this,arguments,function*(e,t="",i=!1,{onlyAdminCanShareMovie:r}={}){let s=this._preareStartConversationData({conversationId:e,isVideo:!1,joiningAllowed:!0,payload:t,requireAuthToJoin:i,onlyAdminCanShareMovie:r});return this._startConversation(s)})}startConversation(u,I,R){return o(this,arguments,function*(e,t,i,r=!1,n="",s=!1,d=!1,{onlyAdminCanShareMovie:l}={}){let A=this._preareStartConversationData({conversationId:e,isVideo:r,joiningAllowed:s,payload:n,requireAuthToJoin:d,onlyAdminCanShareMovie:l});if(t&&t.length)switch(i){case qe.USER:A.uids=t.join(",");break;case qe.GROUP:A.gid=t[0];break;case qe.CHAT:A.chatId=t[0];break}return this._startConversation(A)})}_preareStartConversationData({conversationId:e,isVideo:t,payload:i="",joiningAllowed:r=!1,requireAuthToJoin:n=!1,onlyAdminCanShareMovie:s}){let d={conversationId:e,isVideo:t,protocolVersion:p.protocolVersion};return r&&(d.createJoinLink=!0),i&&(d.payload=i),p.domain&&(d.domainId=p.domain),p.externalDomain&&(d.externalDomain=p.externalDomain),n&&(d.requireAuthToJoin=!0),s!==void 0&&(d.onlyAdminCanShareMovie=s),d}_startConversation(e){return o(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return o(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return o(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return o(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i){return o(this,null,function*(){let r={joinLink:e,isVideo:t,protocolVersion:p.protocolVersion};return(i==null?void 0:i.length)&&(r.observedIds=i.join(",")),p.anonymToken&&(r.anonymToken=p.anonymToken),this._call("vchat.joinConversationByLink",r)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=Ee.fromIds(e),i=[],r={methods:[]},n=[],s=Object.keys(this._externalUidsCache),d=Object.values(this._externalUidsCache);for(let u of t){let I=Ee.toString(u),R=d.indexOf(I);R>-1?i.push(Number(s[R])):(n.push(I),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:u.id,anonym:u.type===It.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((u,I)=>{if(u.ok){let R=Number(u.ok.ok_id);this._externalUidsCache[R]=n[I],i.push(R)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(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.composeUserId(t[n],Z.USER):null}cacheExternalId(e,t){let i=S.decomposeId(e).id;this._externalUidsCache[i]=Ee.toString(t)}getConversationParams(e){return o(this,null,function*(){let t={};return p.anonymToken&&(t.anonymToken=p.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:D.HUNGUP};p.anonymToken&&(t.anonymToken=p.anonymToken),ar("vchat.hangupConversation",t)}removeHistoryRecords(e){return o(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return o(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,n]of Object.entries(i.external_ids))t[r]=Ee.fromIdToString(n,It.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=Ee.fromIdToString(n,It.ANONYM);return t}catch(i){return t}})}};import{Any as Bn,Arr as Ra,Int as ie,Nil as dt,Str as Vn}from"messagepack";var Ca=(x=>(x.RECOVER="recover",x.ACCEPT_CALL="accept-call",x.ADD_PARTICIPANT="add-participant",x.REMOVE_PARTICIPANT="remove-participant",x.HANGUP="hangup",x.TRANSMIT_DATA="transmit-data",x.ACCEPT_PRODUCER="accept-producer",x.ALLOCATE_CONSUMER="allocate-consumer",x.CHANGE_MEDIA_SETTINGS="change-media-settings",x.CHANGE_PARTICIPANT_STATE="change-participant-state",x.CHANGE_STREAM_PRIORITIES="change-streams-priorities",x.UPDATE_DISPLAY_LAYOUT="update-display-layout",x.REPORT_PERF_STAT="report-perf-stat",x.RECORD_START="record-start",x.RECORD_STOP="record-stop",x.RECORD_SET_ROLE="record-set-role",x.RECORD_GET_STATUS="record-get-status",x.SWITCH_MICRO="switch-micro",x.SWITCH_TOPOLOGY="switch-topology",x.REQUEST_REALLOC="request-realloc",x.CHAT_MESSAGE="chat-message",x.CHAT_HISTORY="chat-history",x.CUSTOM_DATA="custom-data",x.GRANT_ROLES="grant-roles",x.MUTE_PARTICIPANT="mute-participant",x.ENABLE_FEATURE_FOR_ROLES="enable-feature-for-roles",x.PIN_PARTICIPANT="pin-participant",x.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",x.CHANGE_OPTIONS="change-options",x.GET_WAITING_HALL="get-waiting-hall",x.GET_PARTICIPANT_LIST_CHUNK="get-participant-list-chunk",x.GET_PARTICIPANTS="get-participants",x.PROMOTE_PARTICIPANT="promote-participant",x.REQUEST_TEST_MODE="request-test-mode",x.ADD_MOVIE="add-movie",x.UPDATE_MOVIE="update-movie",x.REMOVE_MOVIE="remove-movie",x.GET_ROOMS="get_rooms",x.GET_ROOM="get_room",x.UPDATE_ROOMS="update-rooms",x.ACTIVATE_ROOMS="activate-rooms",x.REMOVE_ROOMS="remove-rooms",x.SWITCH_ROOM="switch-room",x))(Ca||{}),U=Ca;function gi(){let a=new DataView(new ArrayBuffer(64)),e=0;function t(i){if(e+i>a.byteLength){let r=new Uint8Array(Math.max(e+i,a.byteLength+64));r.set(new Uint8Array(a.buffer.slice(0,e))),a=new DataView(r.buffer)}}return{put(i){if(t(i.byteLength),Un(i)){let r=i.buffer;new Uint8Array(a.buffer).set(new Uint8Array(r),e)}else new Uint8Array(a.buffer).set(new Uint8Array(i),e);e+=i.byteLength},putI8(i){t(1),a.setInt8(e,i),++e},putI16(i){t(2),a.setInt16(e,i),e+=2},putI32(i){t(4),a.setInt32(e,i),e+=4},putI64(i){t(8);let r=i<0;r&&(i=-i);let n=i/4294967296|0,s=i%4294967296|0;r&&(s=~s+1|0,n=s===0?~n+1|0:~n),a.setUint32(e,n),a.setUint32(e+4,s),e+=8},putUi8(i){t(1),a.setUint8(e,i),++e},putUi16(i){t(2),a.setUint16(e,i),e+=2},putUi32(i){t(4),a.setUint32(e,i),e+=4},putUi64(i){t(8),a.setUint32(e,i/4294967296|0),a.setUint32(e+4,i%4294967296),e+=8},putF(i){t(8),a.setFloat64(e,i),e+=8},ui8array(){return new Uint8Array(a.buffer.slice(0,e))}}}function Un(a){return a.buffer!==void 0}function fi(a){let e=ArrayBuffer.isView(a)?new DataView(a.buffer,a.byteOffset,a.byteLength):new DataView(a),t=0;return{peek(){return e.getUint8(t)},get(i){t+=i;let r=e.byteOffset;return e.buffer.slice(r+t-i,r+t)},getI8(){return e.getInt8(t++)},getI16(){return t+=2,e.getInt16(t-2)},getI32(){return t+=4,e.getInt32(t-4)},getI64(){t+=8;let i=e.getInt32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getUi8(){return e.getUint8(t++)},getUi16(){return t+=2,e.getUint16(t-2)},getUi32(){return t+=4,e.getUint32(t-4)},getUi64(){t+=8;let i=e.getUint32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getF32(){return t+=4,e.getFloat32(t-4)},getF64(){return t+=8,e.getFloat64(t-8)}}}var ya=0,Pa=1,Fn=0,Hn=1,Gn=2,nr=0,Wn=0,jn=0,Kn=1,sr=class{constructor(){this.participantIdRegistry=null}setParticipantIdRegistry(e){this.participantIdRegistry=e}serializeUpdateDisplayLayout(e,t){let i=gi();ie.enc(i,ya),ie.enc(i,nr),ie.enc(i,e),dt.enc(i,null);let r=[];for(let n in t)t.hasOwnProperty(n)&&this.writeLayout(t,n,r);return Ra.enc(i,r),dt.enc(i,null),i.ui8array()}writeLayout(e,t,i){let r=e[t],n=gi();if(this.writeStreamDesc(t,n),Vt(r))ie.enc(n,Hn);else if(Yi(r))ie.enc(n,Gn);else if(ie.enc(n,Fn),r.priority!==void 0?ie.enc(n,r.priority):dt.enc(n,null),r.width!==void 0&&r.height!==void 0?(ie.enc(n,Math.round(r.width)),ie.enc(n,Math.round(r.height))):(dt.enc(n,null),dt.enc(n,null)),r.fit!==void 0)switch(r.fit){case"cv":ie.enc(n,jn);break;case"cn":ie.enc(n,Kn);break;default:dt.enc(n,null)}else dt.enc(n,null);i.push(n.ui8array())}writeStreamDesc(e,t){if(this.participantIdRegistry){let i=this.participantIdRegistry.getCompactId(e);if(i!==void 0){ie.enc(t,i);return}}Vn.enc(t,e)}serializePerfStatReport(e,t){let i=gi();return ie.enc(i,Pa),ie.enc(i,nr),ie.enc(i,e),ie.enc(i,t.framesDecoded),ie.enc(i,t.framesReceived),i.ui8array()}deserializeCommandResponse(e){return o(this,null,function*(){let t;if(e instanceof Blob){let s=yield e.arrayBuffer();t=fi(s)}else t=fi(e);let i=ie.dec(t),r=ie.dec(t);if(r!==nr){c.warn("Unsupported version for command type: "+i+", version "+r);return}if(ie.dec(t)!==Wn){c.warn("Error code: "+i+"received for command type: "+i+", version "+r);return}switch(i){case ya:return this.deserializeUpdateDisplayLayoutResponse(t);case Pa:return this.deserializeReportPerfStatResponse(t);default:return c.warn("unsupported command response commandType: "+i),null}})}deserializeUpdateDisplayLayoutResponse(e){let t=ie.dec(e),i=Ra.dec(e),r={};return i.forEach(n=>{let s=fi(n),d=Bn.dec(s);if(typeof d=="string")r[d]=ie.dec(s);else{let l=d,u=He(this.participantIdRegistry.getStreamDescription(l));r[u]=ie.dec(s)}}),{type:"response",sequence:t,response:U.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:r}}deserializeReportPerfStatResponse(e){let t=ie.dec(e),i=ie.dec(e);return{type:"response",sequence:t,response:U.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:i}}};var ba="open",Ma=[()=>p.producerScreenTrack,()=>p.videoTracksCount>0,()=>!0,()=>p.filteredMessages,()=>p.consumerScreenTrack,()=>!0,()=>p.movieShare,()=>p.useParticipantListChunk],qn=10,ke=class extends At{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+p.platform+"&appVersion="+p.appVersion+"&version="+p.protocolVersion+"&device="+p.device+"&capabilities="+ke._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null;this.producerCommandDataChannelEnabled=!1;this.producerCommandSerializationService=new sr}static _getCapabilityFlags(){let e=0;for(let t=0;t<Ma.length;t++)Ma[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e,this.producerCommandSerializationService.setParticipantIdRegistry(e)}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=t=>{this.producerCommandSerializationService.deserializeCommandResponse(t.data).then(i=>{i&&this._handleMessage(i)}).catch(i=>{c.warn("Cannot parse message at producerCommandDataChannel",i)})},this._handleCommandsQueue(this.datachannelCommandsQueue)}useCommandDataChannel(e){this.producerCommandDataChannelEnabled=e}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return o(this,null,function*(){return this.postfix+=`&clientType=${p.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){h.log(E.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return o(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=S.decomposeParticipantId(t.participantId),s=S.decomposeId(n.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),n.deviceIdx&&(t.deviceIdx=n.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return o(this,arguments,function*(e,t={},i=0){let n=s=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===ba&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){h.log(E.SOCKET_ACTION,"not_opened"),c.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(h.log(E.SOCKET_ACTION,"invalid_state"),c.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,d)=>{let l=(I,R=!1)=>{!i||R?d(I):(c.debug("Resending a signaling message",e,u.sequence),i--,n(u))},u={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};n(u)})})}_isDataChannelCommand(e){return this.producerCommandDataChannelEnabled?e===U.UPDATE_DISPLAY_LAYOUT||e===U.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===U.UPDATE_DISPLAY_LAYOUT||e===U.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(U.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(U.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e,t){return o(this,null,function*(){return this._send(U.REQUEST_TEST_MODE,{consumer:e,producer:t})})}sendSdp(e,t){return o(this,null,function*(){return this._send(U.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(U.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(U.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},qn)})}changeParticipantState(e){return o(this,null,function*(){return this._send(U.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(U.ADD_PARTICIPANT,ze({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(U.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return o(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(U.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(U.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(U.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(U.UPDATE_DISPLAY_LAYOUT,e)})}addMovie(e){return o(this,null,function*(){return this._send(U.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(U.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(U.REMOVE_MOVIE,e)})}updateRooms(e,t){return o(this,null,function*(){return this._send(U.UPDATE_ROOMS,{rooms:e,assignRandomly:t})})}activateRooms(e,t){return o(this,null,function*(){return this._send(U.ACTIVATE_ROOMS,{roomIds:e,deactivate:t})})}switchRoom(e,t){return o(this,null,function*(){return this._send(U.SWITCH_ROOM,{toRoomId:e,participantId:t})})}startStream(e){return o(this,null,function*(){return this._send(U.RECORD_START,e)})}stopStream(){return o(this,null,function*(){return this._send(U.RECORD_STOP)})}recordSetRole(e,t){return o(this,null,function*(){return this._send(U.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return o(this,null,function*(){return this._send(U.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(U.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(U.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(U.REPORT_PERF_STAT,e)})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(U.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(U.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(U.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return o(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(U.GRANT_ROLES,r)})}muteParticipant(e,t,i){return o(this,null,function*(){return this._sendRaw(U.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}enableFeatureForRoles(e,t){return o(this,null,function*(){return this._sendRaw(U.ENABLE_FEATURE_FOR_ROLES,{feature:e,roles:t})})}pinParticipant(e,t){return o(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(U.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(U.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(U.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return o(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(U.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(U.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}getParticipantListChunk(e){return o(this,null,function*(){return this._send(U.GET_PARTICIPANT_LIST_CHUNK,e)})}getParticipants(e){return o(this,null,function*(){return this._send(U.GET_PARTICIPANTS,{externalIds:e})})}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===$e.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),t=i(t),c.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor();function i(r){if(!p.useParticipantListChunk)return r;r+=`&partIdx=${p.participantListChunkInitIndex}`;let s=p.participantListChunkInitCount;return s!==null&&(r+=`&partCount=${s}`),r}}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){c.debug("Socket opened"),h.log(E.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){h.log(E.SOCKET_ACTION,"parse_error"),c.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(c.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(Te.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Te.NOTIFICATION,{type:"notification",notification: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(Te.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(h.log(E.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(h.log(E.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new L(D.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(Te.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 L(ne.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(h.log(E.SOCKET_ACTION,"unknown_message"),c.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(Te.FAILED,e)}_onError(e){h.log(E.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){h.log(E.SOCKET_ACTION,"closed"),c.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<ke.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(ke.RECONNECT_MAX_DELAY,ke.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),h.log(E.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,$e.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],h.log(E.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),ke.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift();if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==ba){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}ke._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:r.name,sequence:r.sequence}),ke.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r);let s=this._serializeBinary(r);s!==null&&this.producerCommandDataChannel.send(s)}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:r.name,sequence:r.sequence}),ke.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(this._serializeJson(r))}}}_serializeBinary(e){switch(e.name){case U.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case U.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params)}return c.warn("cannot get binary data for data channel command: "+e.name),null}_serializeJson(e){let t;e.name===U.UPDATE_DISPLAY_LAYOUT?t=this._convertDisplayLayout(e.params):t=e.params;let i=Object.assign({command:e.name,sequence:e.sequence},t);return JSON.stringify(i)}_convertDisplayLayout(e){let t=e,i={};for(let r in t)t.hasOwnProperty(r)&&(i[r]=la(t[r]));return{layouts:i}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new L(ne.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},ke.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($e.RETRY)},ke.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Ge=ke;Ge.RECONNECT_DELAY=p.signalingReconnectDelay,Ge.RECONNECT_MAX_DELAY=p.signalingReconnectMaxDelay,Ge.RECONNECT_MAX_COUNT=p.signalingReconnectMaxCount,Ge.WAIT_CONNECTION_DELAY=p.waitConnectionDelay,Ge.WAIT_RESPONSE_DELAY=p.waitResponseDelay,Ge.WAIT_MESSAGE_DELAY=p.waitMessageDelay;var Da=(t=>(t.KING="KING",t.PAWN="PAWN",t))(Da||{}),$n=Da;var Ct,le,qt=null,lh={getCameras:b.getCameras,getMicrophones:b.getMicrophones,getOutput:b.getOutput,hasCamera:b.hasCamera,hasMicrophone:b.hasMicrophone,getSavedCamera:b.getSavedCamera,getSavedMicrophone:b.getSavedMicrophone,getSavedOutput:b.getSavedOutput,hasCameraPermission:b.hasCameraPermission,hasMicrophonePermission:b.hasMicrophonePermission,hasPermissions:b.hasPermissions,getUserMedia:b.getUserMedia,getUserVideo:b.getUserVideo,getUserAudio:b.getUserAudio,saveDeviceId:b.saveDeviceId,isBrowserSupported:b.isBrowserSupported,isScreenCapturingSupported:b.isScreenCapturingSupported,os:b.os,isMobile:b.isMobile,browserName:b.browserName,browserVersion:b.browserVersion,baseChromeVersion:b.baseChromeVersion,getAudioContext:b.getAudioContext};function Jn(a){le=a}function Yn(a){Ct=a}function uh(a){qt=a}function mh(a){p.videoEffects=a}function hh(a){return o(this,null,function*(){if(p.set(a),b.browserName()==="Sferum"&&(p.platform=`SFERUM:${b.browserVersion()}`),le||Jn(new _i),Ct||Yn(()=>new Ge),p.debug&&(Aa.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${p.sdkVersion}`,a),yield b.init(),!b.isBrowserSupported())throw new L(ne.UNSUPPORTED);le.init()})}function _h(s){return o(this,arguments,function*(a,e=[ge.AUDIO],t="",i=!1,r=!1,n){let d=[],l=[];if(Array.isArray(a)?d=a.length?a:[]:a&&(d=[a]),d.length&&(l=yield le.getOkIdsByExternalIds(d),!l.length))throw new L(D.CALLEE_IS_OFFLINE);return zn(l,qe.USER,e,t,i,r,n)})}function zn(d){return o(this,arguments,function*(a,e=qe.USER,t,i="",r=!1,n=!1,s){if(N.current())throw c.error("There is already active call"),new L(D.FAILED);return new N(le,Ct(),qt).onStart(a,e,t,i,r,n,s)})}function gh(a){return o(this,null,function*(){return Qn(a)})}function Qn(i){return o(this,arguments,function*(a,e=Z.USER,t){if(a===N.id())throw new Error("Push has already been processed");return new N(le,Ct(),qt).onPush(a,e,t)})}function fh(a){return o(this,null,function*(){return a&&(p.authToken=a),le.authorize()})}function Sh(){return o(this,arguments,function*(a=[ge.AUDIO]){return Rt().accept(a)})}function vh(){return o(this,null,function*(){let a=N.current();if(a)return a.decline()})}function Eh(t){return o(this,arguments,function*(a,e=[ge.AUDIO]){return Xn(a,e)})}function Xn(a,e,t){return o(this,null,function*(){if(N.current())throw c.error("There is already active call"),new L(D.FAILED);return new N(le,Ct(),qt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function Ih(r){return o(this,arguments,function*(a,e=[ge.AUDIO],t,i){if(N.current())throw c.error("There is already active call"),new L(D.FAILED);return t&&(p.anonymToken=t),new N(le,Ct(),qt).onJoin({joinLink:a,mediaOptions:e,observedIds:i})})}function Th(){return o(this,null,function*(){let a=N.current();if(a)return a.hangup();N.hangupAfterInit()})}function Ch(a,e){return o(this,null,function*(){let t=yield le.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return Zn(t[0],e)})}function Zn(a,e){return o(this,null,function*(){let t=N.current();t&&(yield t.addParticipant(S.composeUserId(a,Z.USER),e))})}function Rh(a,e=!1){return o(this,null,function*(){let t=yield le.getOkIdsByExternalIds([a]);return es(t[0],e)})}function es(a,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.removeParticipant(S.composeUserId(a,Z.USER),e))})}function yh(a,e){return o(this,null,function*(){let t=yield b.saveDeviceId(a,e),i=N.current();return t&&i?i.changeDevice(a):Promise.reject()})}function Ph(a){return o(this,null,function*(){let e=N.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function bh(a,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.setVideoStream(a,e))})}function Mh(a){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalVideo(a))})}function Dh(a){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalAudio(a))})}function Ah(a,e,t){return o(this,null,function*(){let i=N.current();if(i)return i.setLocalResolution(a,e,t)})}function Oh(a){return o(this,null,function*(){let e=N.current();e&&(yield e.changePriorities(a))})}function kh(a){return o(this,null,function*(){let e=N.current();e&&(yield e.changeParticipantState(a))})}function wh(a){return o(this,null,function*(){let e=N.current();e&&(yield e.updateDisplayLayout(a))})}function xh(a,e,t=!1){return o(this,null,function*(){let i=yield le.getOkIdsByExternalIds([a]);return ts(i[0],e,t)})}function ts(a,e,t=!1){return o(this,null,function*(){let i=N.current();i&&(yield i.grantRoles(S.composeUserId(a,Z.USER),e,t))})}function Lh(){return o(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield le.getOkIdsByExternalIds([a]))[0]),is(i,e,t,fe.getDeviceIdx(a))})}function is(){return o(this,arguments,function*(a=null,e,t=[],i=0){let r=N.current();if(r){let n=a?S.composeParticipantId(a,Z.USER,i):null;yield r.muteParticipant(n,e,t)}})}function Nh(a,e=!1){return o(this,null,function*(){let t=yield le.getOkIdsByExternalIds([a]);return rs(t[0],e,fe.getDeviceIdx(a))})}function rs(a,e=!1,t=0){return o(this,null,function*(){let i=N.current();i&&(yield i.pinParticipant(S.composeParticipantId(a,Z.USER,t),e))})}function Uh(a){return o(this,null,function*(){let e=N.current();e&&(yield e.updateMediaModifiers(a))})}function Bh(a){return o(this,null,function*(){let e=N.current();e&&(yield e.changeOptions(a))})}function Vh(a,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield le.getOkIdsByExternalIds([e]))[0]),as(a,t)})}function as(a,e=null){return o(this,null,function*(){let t=N.current();if(t){let i=e?S.composeUserId(e,Z.USER):null;yield t.chatMessage(a,i)}})}function Fh(a=10){return o(this,null,function*(){let e=N.current();if(e)return e.chatHistory(a)})}function Hh(a,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield le.getOkIdsByExternalIds([e]))[0]),ns(a,t,fe.getDeviceIdx(e))})}function ns(a,e=null,t=0){return o(this,null,function*(){let i=N.current();if(i){let r=e?S.composeParticipantId(e,Z.USER,t):null;yield i.customData(a,r)}})}function Gh(){return o(this,arguments,function*(a="",e=!1,{onlyAdminCanShareMovie:t=!1}={}){return(yield le.createConversation(S.uuid(),a,e,{onlyAdminCanShareMovie:t})).join_link})}function Wh(){return o(this,null,function*(){let a=N.current();return a?a.createJoinLink():Promise.reject()})}function jh(){return o(this,null,function*(){let a=N.current();return a?a.removeJoinLink():Promise.reject()})}function Kh(a,e){return o(this,null,function*(){return le.getAnonymTokenByLink(a,e)})}function qh(a){let e=N.current();e&&e.setVolume(a)}function $h(a){p.forceRelayPolicy=a}function Jh(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return o(this,null,function*(){let n=N.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function Yh(){return o(this,null,function*(){let a=N.current();return a?a.stopStream():Promise.reject()})}function zh(a,e){return o(this,null,function*(){let t=N.current();if(t){let i=yield le.getOkIdsByExternalIds([a]),r=fe.getDeviceIdx(a);return t.recordSetRole(S.composeParticipantId(i[0],Z.USER,r),e)}return Promise.reject()})}function Qh(){return o(this,null,function*(){let a=N.current();return a?a.getStreamInfo():Promise.reject()})}function Xh(a){return o(this,null,function*(){let e=N.current();return e?e.addMovie(a):Promise.reject()})}function Zh(a,e,t,i){return o(this,null,function*(){let r=N.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function e_(a){return o(this,null,function*(){let e=N.current();return e?e.removeMovie(a):Promise.reject()})}function t_(a,e){return o(this,null,function*(){let t=N.current();return t?t.updateRooms(a,e):Promise.reject()})}function i_(a,e){return o(this,null,function*(){let t=N.current();return t?t.activateRooms(a,e):Promise.reject()})}function r_(a,e){return o(this,null,function*(){let t=N.current();return t?t.switchRoom(a,e):Promise.reject()})}function a_(a){p.statisticsInterval=a;let e=N.current();if(e)return e.updateStatisticsInterval()}function n_(a){Aa.disableLog(!a),c.toggle(a)}function s_(a,...e){!p.debugLog||c.send(a,"[external]",...e)}function o_(a){return o(this,null,function*(){let e=N.current();if(e)return e.videoEffect(a)})}function c_(a){return o(this,null,function*(){let e=N.current();e&&(yield e.setAudioStream(a))})}function d_(a=null,e,t=!1){return o(this,null,function*(){return Rt().getWaitingHall(a,e,t)})}function p_(a,e=!1){return o(this,null,function*(){let t=Rt(),i=yield le.getOkIdsByExternalIds([a]);return t.promoteParticipant(S.composeUserId(i[0],Z.USER),e)})}function l_(a){return o(this,null,function*(){return Rt().getParticipantListChunk(a)})}function u_(a){return o(this,null,function*(){return Rt().getParticipants(a)})}function m_(a,e){return o(this,null,function*(){return Rt().enableFeatureForRoles(a,e)})}function Rt(){let a=N.current();if(!a)throw new Error("Conversation not found");return a}function h_(a){return o(this,null,function*(){yield le.removeHistoryRecords(a)})}function __(){return p.sdkVersion}export{_i as Api,Mt as BaseApi,Dt as BaseLogger,At as BaseSignaling,Qe as CallDirection,qe as CallType,Ti as ChatRoomEventType,Ci as ConversationOption,pa as DebugMessageType,It as ExternalIdType,Zr as FacingMode,ne as FatalError,L as HangupReason,D as HangupType,ge as MediaOption,me as MediaTrackKind,Pe as MediaType,Ne as MuteState,j as ParticipantState,J as ParticipantStatus,$n as RecordRole,Ri as RoomsEventType,Ge as Signaling,U as SignalingCommandType,$e as SignalingConnectionType,O as SignalingNotification,se as TransportTopology,lt as UserRole,Z as UserType,S as Utils,Sh as acceptCall,i_ as activateRooms,Xh as addMovie,Ch as addParticipant,Zn as addParticipantInternal,fh as authorize,lh as browser,zn as callInternal,_h as callTo,Ph as captureScreen,Bh as changeConversationOptions,yh as changeDevice,kh as changeParticipantState,Oh as changePriorities,o_ as changeVideoEffect,Fh as chatHistory,Vh as chatMessage,as as chatMessageInternal,Wh as createJoinLink,Hh as customData,ns as customDataInternal,n_ as debug,s_ as debugMessage,vh as declineCall,m_ as enableFeatureForRoles,$h as forceRelayPolicy,Kh as getAnonymTokenByLink,l_ as getParticipantListChunk,u_ as getParticipants,Qh as getStreamInfo,d_ as getWaitingHall,xh as grantRoles,ts as grantRolesInternal,Th as hangup,hh as init,Eh as joinCall,Ih as joinCallByLink,Xn as joinCallInternal,Lh as muteParticipant,is as muteParticipantInternal,Nh as pinParticipant,rs as pinParticipantInternal,gh as processPush,Qn as processPushInternal,p_ as promoteParticipant,zh as recordSetRole,h_ as removeHistoryRecords,jh as removeJoinLink,e_ as removeMovie,Rh as removeParticipant,es as removeParticipantInternal,Jn as setApi,c_ as setAudioStream,Ah as setLocalResolution,uh as setLogger,Uh as setMediaModifiers,Yn as setSignalingFactory,a_ as setStatisticsInterval,mh as setVideoEffects,bh as setVideoStream,qh as setVolume,Gh as startConversation,Jh as startStream,Yh as stopStream,r_ as switchRoom,Dh as toggleLocalAudio,Mh as toggleLocalVideo,wh as updateDisplayLayout,Zh as updateMovie,t_ as updateRooms,__ as version};
7
+ var Ga=Object.defineProperty,Wa=Object.defineProperties;var ja=Object.getOwnPropertyDescriptors;var Sr=Object.getOwnPropertySymbols;var Ka=Object.prototype.hasOwnProperty,$a=Object.prototype.propertyIsEnumerable;var vr=Math.pow,Er=(n,e,t)=>e in n?Ga(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ve=(n,e)=>{for(var t in e||(e={}))Ka.call(e,t)&&Er(n,t,e[t]);if(Sr)for(var t of Sr(e))$a.call(e,t)&&Er(n,t,e[t]);return n},ht=(n,e)=>Wa(n,ja(e));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())});import Ba from"webrtc-adapter";var Dt=class{createJoinLink(e){return o(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return o(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return o(this,null,function*(){return""})}log(e){}prepareUserIds(e){return o(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return o(this,null,function*(){})}cleanup(){}};var kt=class{log(e,t,i=!1){}destroy(){}};var ae=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 Ot=class extends ae{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e,t){}getNextCommandSequenceNumber(){return 0}};var Ir=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(Ir||{}),Ze=Ir;var Tr=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(Tr||{}),ze=Tr;var Cr=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(Cr||{}),Mi=Cr;var yr=(i=>(i.ADD_PARTICIPANT="ADD_PARTICIPANT",i.RECORD="RECORD",i.MOVIE_SHARE="MOVIE_SHARE",i))(yr||{}),Ai=yr;var Rr=(a=>(a.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",a.AUDIENCE_MODE="AUDIENCE_MODE",a.WAITING_HALL="WAITING_HALL",a.ASR="ASR",a.FEEDBACK="FEEDBACK",a))(Rr||{}),Di=Rr;function Pr(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}function br(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 Mr=(V=>(V.CAMERA_PERMISSION="camera",V.MIC_PERMISSION="mic",V.CAMERA_ACCESS="cameralock",V.MIC_ACCESS="miclock",V.MIC_NOT_FOUND="nomic",V.SCREEN_PERMISSION="screenpermission",V.SCREEN_ACCESS="screenlock",V.CONNECTION="connection",V.NETWORK="network",V.UNKNOWN="unknown",V.UNSUPPORTED="unsupported",V.SIGNALING_FAILED="signalingfailed",V.API="api",V.AUTH="auth",V))(Mr||{}),ce=Mr;var Ar=(ie=>(ie.CANCELED="CANCELED",ie.REJECTED="REJECTED",ie.REMOVED="REMOVED",ie.HUNGUP="HUNGUP",ie.MISSED="MISSED",ie.BUSY="BUSY",ie.FAILED="FAILED",ie.NETWORK_ERROR="NETWORK_ERROR",ie.KILLED="KILLED",ie.BANNED="BANNED",ie.HAS_ACTIVE_CALL="HAS_ACTIVE_CALL",ie.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",ie.NOT_FRIENDS="NOT_FRIENDS",ie.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",ie.CALLER_IS_REJECTED="CALLER_IS_REJECTED",ie.UNKNOWN_ERROR="UNKNOWN_ERROR",ie.UNSUPPORTED="UNSUPPORTED",ie.OLD_VERSION="OLD_VERSION",ie.SERVICE_DISABLED="SERVICE_DISABLED",ie.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",ie.SOCKET_CLOSED="SOCKET_CLOSED",ie.ENDED="ENDED",ie.KILLED_WITHOUT_DELETE="KILLED_WITHOUT_DELETE",ie.ANOTHER_DEVICE="ANOTHER_DEVICE",ie))(Ar||{}),k=Ar;var Dr=(a=>(a.AUDIO="AUDIO",a.VIDEO="VIDEO",a.SCREEN_SHARING="SCREEN_SHARING",a.MOVIE_SHARING="MOVIE_SHARING",a.AUDIO_SHARING="AUDIO_SHARING",a))(Dr||{}),ue=Dr;var kr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(kr||{}),Fe=kr;var Or=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(Or||{}),j=Or;var wr=(i=>(i.UPDATE="UPDATE",i.REMOVE="REMOVE",i.ACTIVATE="ACTIVATE",i))(wr||{}),ki=wr;var xr=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(xr||{}),Ye=xr;var Lr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(Lr||{}),ye=Lr;var Nr=(L=>(L.TRANSMITTED_DATA="transmitted-data",L.ACCEPTED_CALL="accepted-call",L.HUNGUP="hungup",L.PARTICIPANT_ADDED="participant-added",L.PARTICIPANT_JOINED="participant-joined",L.CLOSED_CONVERSATION="closed-conversation",L.MEDIA_SETTINGS_CHANGED="media-settings-changed",L.PARTICIPANT_STATE_CHANGED="participant-state-changed",L.RATE_CALL_DATA="rate-call-data",L.FEATURE_SET_CHANGED="feature-set-changed",L.TOPOLOGY_CHANGED="topology-changed",L.PRODUCER_UPDATED="producer-updated",L.CONSUMER_ANSWERED="consumer-answered",L.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",L.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",L.SETTINGS_UPDATE="settings-update",L.VIDEO_QUALITY_UPDATE="video-quality-update",L.REGISTERED_PEER="registered-peer",L.SWITCH_MICRO="switch-micro",L.RECORD_STARTED="record-started",L.RECORD_STOPPED="record-stopped",L.REALLOC_CON="realloc-con",L.AUDIO_ACTIVITY="audio-activity",L.SPEAKER_CHANGED="speaker-changed",L.STALLED_ACTIVITY="stalled-activity",L.CHAT_MESSAGE="chat-message",L.CUSTOM_DATA="custom-data",L.ROLES_CHANGED="roles-changed",L.MUTE_PARTICIPANT="mute-participant",L.PIN_PARTICIPANT="pin-participant",L.OPTIONS_CHANGED="options-changed",L.NETWORK_STATUS="network-status",L.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",L.PROMOTE_PARTICIPANT="promote-participant",L.CHAT_ROOM_UPDATED="chat-room-updated",L.PROMOTION_APPROVED="promotion-approved",L.JOIN_LINK_CHANGED="join-link-changed",L.FEEDBACK="feedback",L.MOVIE_UPDATE_NOTIFICATION="movie-update-notification",L.MOVIE_SHARE_INFO="movie-share-info",L.MOVIE_SHARE_STARTED="movie-share-started",L.MOVIE_SHARE_STOPPED="movie-share-stopped",L.ROOM_UPDATED="room-updated",L.ROOMS_UPDATED="rooms-updated",L.ROOM_PARTICIPANTS_UPDATED="room-participants-updated",L.FEATURES_PER_ROLE_CHANGED="features-per-role-changed",L.ASR_STARTED="asr-started",L.ASR_STOPPED="asr-stopped",L))(Nr||{}),O=Nr;var Ur=(q=>(q.ERROR="callError",q.DEVICES="callDevices",q.CALL_SPEC_ERROR="callSpecError",q.ICE_CONNECTION_STATE="callIceConnectionState",q.ICE_CONNECTION_TYPE="callIceConnectionType",q.ICE_RESTART="callIceRestart",q.PUSH="callPush",q.OUTGOING_CALL="callStart",q.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",q.JOIN_CONVERSATION="callJoinConversation",q.ACCEPTED_OUTGOING="callAcceptedOutgoing",q.ACCEPT_INCOMING="callAcceptIncoming",q.DECLINE_INCOMING="callDeclineIncoming",q.ACCEPT_CONCURRENT="callAcceptConcurrent",q.HANGUP="callHangup",q.MEDIA_STATUS="callMediaStatus",q.DEVICE_CHANGED="callDeviceChanged",q.SOCKET_ACTION="callSocketAction",q.ADD_PARTICIPANT="callAddParticipant",q.REMOVE_PARTICIPANT="callRemoveParticipant",q.POOR_CONNECTION="callPoorConnection",q.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",q.RELAY_POLICY="callForceRelay",q.PAT_ALLOCATED="patAllocate",q.PAT_DEALLOCATED="patDeallocate",q.PAT_ERROR="patError",q.PAT_WAITING_TIME_ERROR="patWaitingTimeError",q.PAT_OUTDATED_RESPONSE="patOutdatedResponse",q))(Ur||{}),T=Ur;var Br=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(Br||{}),He=Br;var Vr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(Vr||{}),Fr=Vr;function Hr(n){switch(n){case 1:return"no-available-tracks";default:return"unknown-error"}}var Gr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(Gr||{}),_t=Gr;function wt(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}var Wr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(Wr||{}),te=Wr;var Oi=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 jr=2*1024*1024,qa=512*1024,xt=100*1024,Ja=5,wi="_okcls_logs_session_",za=3e4,Kr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=jr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(wi)!==0)continue;let i=e.getItem(t);if(!i){Jr(t);continue}let r=qr(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(xt)}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(wi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Jr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>jr||this.length>Ja-1||this.size+e>this.available);)this.deleteOldestItem()}};function $r(){return`${wi}${Date.now()}`}function qr(n){return new Blob([n]).size}function Jr(n){try{window.localStorage.removeItem(n)}catch(e){console.error("Failed to remove log from storage",e)}}function xi(){let n=at.toString();if(!Pe.available||!n)return;let e=qr(n);Pe.cleanup(e);try{window.localStorage.setItem(Qt,n)}catch(t){if(console.warn("Failed to write log to storage",t),Pe.storageSize=Pe.size+e,Pe.cleanup(xt+e),Pe.available>=xt+e){xi();return}if(e>xt){at.bisect(),xi();return}Pe.storageSize=0;return}e>qa&&(Pe.add(Qt,e),Qt=$r(),at.clear(),Pe.cleanup(xt))}function Li(){!Pe.available||!at.length||xi()}function Ya(n=!1){let e=[];try{let r=window.localStorage;for(let s of Pe.items){let d=r.getItem(s.key);e.push(d)}let a=at.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 Qa(t,i),i}function Qa(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 zr(n,e){if(!Pe.available)return;let t=new Date;at.push({t:t.getTime(),l:n,d:e,h:t.toLocaleString("ru-RU",{dateStyle:"short",timeStyle:"long"})}),Ui||(Ui=window.setTimeout(()=>{Ui=null,Li()},za))}function Ni(){Pe||(Pe=new Kr,at=new Oi,Qt=$r(),window.addEventListener("beforeunload",Li))}var Pe,at,Qt,Ui=null;window.__VKCallsSDKLogs__=(n=!1)=>(Pe||Ni(),Li(),Ya(n));import Yr from"@vkontakte/libvpx";var Ie=(d=>(d.INIT="init",d.READY="ready",d.FRAME="frame",d.SET_BITRATE="set_bitrate",d.ERROR="error",d.DEBUG="debug",d.LOG_ERROR="log_error",d))(Ie||{});var _=class extends kt{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){_._instance||(_._instance=new _(e,t))}static log(e,t,i=!1){_._instance&&_._instance.log(e,t,i)}static logCustom(e,t,i=!1){_._instance&&_._instance.logCustom(e,t,i)}static destroy(){_._instance&&_._instance.destroy(),_._instance=null}};var Ke=class{constructor(){this._worker=null}_createWorker(s,d){return o(this,arguments,function*(e,t,i=[],r={},a=[]){return new Promise((p,u)=>{let E=i.join(","),I=new Blob([e,`exports.default(${E});`],{type:"application/javascript; charset=utf-8"}),R=window.URL.createObjectURL(I);this._worker=new Worker(R),this._worker.onmessage=b=>{switch(b.data.type){case Ie.READY:p();break;case Ie.ERROR:u(b.data.error);break;case Ie.FRAME:t(b.data);break;case Ie.DEBUG:c.debug(b.data.message);break;case Ie.LOG_ERROR:_.log(T.ERROR,b.data.message);break}},this._sendToWorker(Ie.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 gt=class extends Ke{init(e){return o(this,null,function*(){c.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var m=Object.defineProperty;var x=a=>m(a,"__esModule",{value:!0});var M=(a,l)=>{x(a);for(var t in l)m(a,t,{get:l[t],enumerable:!0})};var D={};M(D,{default:()=>h});var r=(e=>(e.INIT="init",e.READY="ready",e.FRAME="frame",e.SET_BITRATE="set_bitrate",e.ERROR="error",e.DEBUG="debug",e.LOG_ERROR="log_error",e))(r||{});var h=(a,l)=>{let t=null,o=null,u=!0;function b(){return a({locateFile:l}).then(e=>o=e)}function y(e,g,n,E,R){if(!o){self.postMessage({type:r.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:r.FRAME,error:"Fatal initialization error"});return}if(u!==n&&(u=n,t&&(t=null,self.postMessage({type:r.DEBUG,message:`LibVPxDecoder codec changed to ${n?"VP9":"VP8"} - reinitialize`}))),!t&&(self.postMessage({type:r.DEBUG,message:`LibVPxDecoder codec ${n?"VP9":"VP8"}`}),t=new o.VpxDecoder,t.debug(R),!t.init(n?o.VpxType.VP9:o.VpxType.VP8))){t=null,self.postMessage({type:r.FRAME,error:"Decoder failed to create"});return}try{t.allocateBuffer(g.byteLength).set(new Uint8Array(g))}catch(s){self.postMessage({type:r.DEBUG,message:s}),t=null,self.postMessage({type:r.FRAME,error:String(s)});return}if(!(t.decode()&&t.nextImage())){self.postMessage({type:r.FRAME,error:"Decode failed"});return}let p=t.getImageBuffer();if(!p){self.postMessage({type:r.FRAME,error:"No decoded data"});return}let d=t.getImageWidth(),c=t.getImageHeight();t.nextImage()&&(self.postMessage({type:r.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:r.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(p.byteLength);if(i.set(p),E){let s=new ImageData(i,d,c);createImageBitmap(s,0,0,d,c).then(f=>{self.postMessage({type:r.FRAME,data:f},[f]),f.close()})}else self.postMessage({type:r.FRAME,data:i.buffer,width:d,height:c},[i.buffer])}b().then(()=>{self.onmessage=e=>{switch(e.data.type){case r.FRAME:y(e.data.timestamp,e.data.data,e.data.isVP9,e.data.useImageBitmap,e.data.debug);break}},self.postMessage({type:r.READY})}).catch(e=>{self.postMessage({type:r.ERROR,error:String(e)})})};return D;})();\n',t=>{if(t.error)c.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i)}else e(t.data)},[Yr,Yr.getUrl])})}decodeFrame(e,t,i,r){let a="ImageBitmap"in window;this._sendToWorker(Ie.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:a,debug:c.enabled()},[t.buffer])}destroy(){this._removeWorker(),c.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var Bi="_okcls_",ft=(()=>{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 Za(n){let e=ft?ft.getItem(Bi+n):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function en(n,e){try{ft&&ft.setItem(Bi+n,JSON.stringify(e))}catch(t){}}function tn(n){ft&&ft.removeItem(Bi+n)}var Vi;(i=>{function n(r){return Za(r)||null}i.get=n;function e(r,a){en(r,a)}i.set=e;function t(r){tn(r)}i.remove=t})(Vi||(Vi={}));var et=Vi;function Qr(n,e){if(n.isAudioEnabled!==e.isAudioEnabled||n.isVideoEnabled!==e.isVideoEnabled||n.isScreenSharingEnabled!==e.isScreenSharingEnabled||n.isAudioSharingEnabled!==e.isAudioSharingEnabled||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 Se(n){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,isAudioSharingEnabled:!1,videoStreams:[]},n||{})}var Xr=n=>n.stop(),Zr=n=>n.getTracks().forEach(Xr),Fi=n=>n.getVideoTracks().forEach(Xr),ea=n=>n.getVideoTracks()[0].clone();var B=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(k).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,B)}};var ke=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(ke||{}),me=(r=>(r.audio="audio",r.video="video",r.screen="screen",r.audioshare="audioshare",r))(me||{}),Hi=class extends ae{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._audioShareTrack=null;this._sendVideoTrack=null;this._mediaSettings=Se();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener(),l.audioShareCapabilityEnabled&&(this._audioShareTrack=this.getSilentAudioShareTrack())}request(){return o(this,arguments,function*(e=[ue.AUDIO],t=!0){if(this._stream)return;let i=e.includes(ue.VIDEO),r=e.includes(ue.AUDIO);if(!P.isBrowserSupported())throw new B(ce.UNSUPPORTED);try{this._stream=yield P.getUserMedia(i,r,t),this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(a=>a.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=r&&this._stream.getAudioTracks().filter(a=>a.enabled).length>0||!1}catch(a){throw new B(a)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t,i,r){let a=this.getStream(),s=this._getSendAudioTrack(),d=this.getSendVideoTrack(i);if(!a||!s&&!d&&!t)throw new Error("No local stream found");if(s&&!t){if(r){let{codecs:p}=RTCRtpSender.getCapabilities("audio"),u="audio/red",E=48e3,I=p.findIndex(R=>R.mimeType===u&&R.clockRate===E);if(I>=0){let R=[];R.push(p[I]);for(let b=0;b<p.length;b++)b!==I&&R.push(p[b]);e.getTransceivers().forEach(b=>b.setCodecPreferences(R))}}e.addTrack(s,a)}d&&!t&&e.addTrack(d,a)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return o(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return o(this,null,function*(){return t?this._changeScreen(!1,e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=v.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);this._onDeviceChange=()=>o(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],a=r&&r.enabled&&r.getSettings(),s=a&&a.deviceId,d=this._stream.getVideoTracks()[0],p=d&&d.enabled&&d.getSettings(),u=p&&p.deviceId;if(!s&&!u)return;let E=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!E.find(I=>I.deviceId===s)),!t&&u&&(t=!E.find(I=>I.deviceId===u)),i()}),navigator.mediaDevices.addEventListener("devicechange",this._onDeviceChange)}_destroyDeviceChangeListener(){this._onDeviceChange&&navigator.mediaDevices.removeEventListener("devicechange",this._onDeviceChange)}_changeVideoInput(e=null){return o(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield P.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{l.consumerScreenTrack||(yield this._disableScreenCapture());let r=this._getVideoEffectTrack(i),a=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),_.log(T.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 _.log(T.ERROR,"change_video"),c.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=ea(e)),t=this._trackVideoStreamBackup.clone(),Fi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),Fi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return o(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return o(this,null,function*(){try{if(e=e||(yield P.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),_.log(T.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 _.log(T.ERROR,"change_audio"),c.error("Microphone change failed",t),t}})}_changeScreen(e,t){return o(this,null,function*(){try{if(t=t||(yield P.getScreenMedia(e)),t.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1,!1)},!1),!this._stream)t.getTracks().forEach(i=>i.stop());else{let i=t.getVideoTracks()[0],r=l.consumerScreenTrack?i:yield this._videoEffect(null,i);if(_.log(T.DEVICE_CHANGED,"screen"),c.log("Screen capturing started"),this._screenTrack=r,this._mediaSettings.isScreenSharingEnabled=!0,l.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=l.consumerScreenDataChannel?P.getBlackMediaTrack(l.videoMinWidth,l.videoMinHeight):r,yield this._replaceLocalTrack(r,this._sendVideoTrack)),t.getAudioTracks().length>0){let a=t.getAudioTracks()[0];a.contentHint="music",this._audioShareTrack=a,this._stopLocalTrack("audioshare"),yield this._replaceLocalTrack(a),this._mediaSettings.isAudioSharingEnabled=!0}this._triggerEvent("SCREEN_STATUS",{track:r,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(i){throw _.log(T.ERROR,"screen"),c.warn("Screen capturing failed",i),i}})}_disableScreenCapture(){return o(this,null,function*(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),yield this.disableAudioShare(),(this._mediaSettings.isScreenSharingEnabled||this._mediaSettings.isAudioSharingEnabled)&&(this._mediaSettings.isScreenSharingEnabled=!1,this._mediaSettings.isAudioSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))})}disableAudioShare(){return o(this,null,function*(){if(this._audioShareTrack){this._audioShareTrack.stop();let e=this.getSilentAudioShareTrack();this._stopLocalTrack("audioshare"),yield this._replaceLocalTrack(e),this._mediaSettings.isAudioSharingEnabled&&(this._mediaSettings.isAudioSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"audioshare",mediaSettings:this._mediaSettings}))}})}getSilentAudioShareTrack(){let e=P.getSilentMediaTrack();return e.contentHint="music",e.stop(),e}_replaceLocalTrack(e,t){return o(this,null,function*(){if(!this._stream)return;let i=!1;this._stream.getTracks().forEach(r=>{var a,s;r.kind===e.kind&&r.contentHint===e.contentHint&&((a=this._stream)==null||a.removeTrack(r),(s=this._stream)==null||s.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t),i=!0)}),i||(this._stream.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.contentHint==="music"&&t.kind==="audio"?e==="audioshare"&&t.stop():t.kind===e&&t.stop()})}_videoEffect(e,t){return o(this,null,function*(){if(!l.videoEffects)return t;try{return _.log(T.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(){this._destroyDeviceChangeListener(),l.videoEffects&&(this._effect=null,l.videoEffects.destroy()),this._stream&&(Zr(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e,t){return o(this,null,function*(){if(e){yield this._changeScreen(t),t||(yield this.disableAudioShare());return}return l.consumerScreenTrack?this._disableScreenCapture():(t||(yield this.disableAudioShare()),this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1))})}toggleVideo(e){return o(this,null,function*(){if(!this._stream)return;l.consumerScreenTrack||(yield this._disableScreenCapture());let t;if(e){let i=yield P.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=P.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 P.getUserAudio()).getAudioTracks()[0]:t=P.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)})}getAudioShareTrack(){return this._audioShareTrack}};var ta=typeof Object.fromEntries=="function"?Object.fromEntries:function(n){if(!n||!n[Symbol.iterator])throw new Error("Object.fromEntries() requires a single iterable argument");let e={};for(let[t,i]of n)e[t]=i;return e};var St=":",Xt="d",rn=533,Gi="a=fmtp:",an="sps-pps-idr-in-keyframe=1",Wi;(Pi=>{function n(f,C,M,D,h,x=!1,J=!1){let Y=/[\r\n]+/,Ee=`\r
8
+ `;if(!C&&!M&&!D&&!J&&!x&&!h)return f;function ge(K){let fe=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],Ce="a=rtcp-fb:111",ee=K.findIndex(X=>X.startsWith(Ce));return~ee&&(K[ee]=K[ee]+Ee+fe.join(Ee)),K}function We(K,fe,Ce){let ee=K.split(" "),X=ee.slice(0,3),oe;for(oe=3;oe<ee.length;oe++)Ce.includes(ee[oe])&&X.push(ee[oe]);for(oe=3;oe<ee.length;oe++)!Ce.includes(ee[oe])&&!fe.includes(ee[oe])&&X.push(ee[oe]);return X.join(" ")}function Le(K,fe){let Ce=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),ee,X=[];for(ee=0;ee<K.length;++ee){let oe=K[ee].match(Ce);oe&&oe.length===3&&oe[2]===fe&&X.push(oe[1])}return X}function Ne(K,fe,Ce,ee){let X,oe="m="+fe;for(X=0;X<K.length;++X)if(K[X].startsWith(oe)){K[X]=We(K[X],Ce,ee);break}}function Ue(K,fe){let Ce=new RegExp(Gi+"(\\d+)");for(let ee=0;ee<K.length;++ee){let X=K[ee].match(Ce);if(X&&X.length===2&&fe.includes(X[1])){let oe=K[ee].trim()===Gi+X[1]?" ":";";K[ee]+=oe+an}}}function je(K){let fe=Le(K,"H264");if(M){let Ce=fe.slice(0),ee=new RegExp(Gi+"(\\d+) apt=(\\d+)"),X;for(X=0;X<K.length;++X){let Je=K[X].match(ee);Je&&Je.length===3&&Ce.includes(Je[2])&&Ce.push(Je[1])}let oe=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(X=K.length;X--;){let Je=K[X].match(oe);Je&&Je.length===3&&Ce.includes(Je[2])&&K.splice(X,1)}Ne(K,"video",Ce,[])}else C&&Ne(K,"video",[],fe),h&&Ue(K,fe)}function Be(K){let fe=Le(K,"VP9");D&&Ne(K,"video",[],fe)}function U(K){let fe=Le(K,"red");fe.length>0&&Ne(K,"audio",[],fe)}let L=f.split(Y);return(M||C||h)&&je(L),D&&Be(L),J&&U(L),x&&ge(L),L.join(Ee)}Pi.patchSDP=n;function e(f){return f?`${f.type||"WEB_SOCKET"}_${f.id}`:"_"}Pi.getPeerIdString=e;function t(f,C){return f&&f.id===C.id&&(f.type||"WEB_SOCKET")===(C.type||"WEB_SOCKET")}Pi.comparePeerId=t;function i(f){return o(this,null,function*(){return!f||!f.getStats?Promise.resolve(null):f.getStats(null).then(C=>{let M=null,D=null;if(C.forEach(h=>{h.type==="transport"&&h.selectedCandidatePairId?D=C.get(h.selectedCandidatePairId):h.type==="candidate-pair"&&h.state==="succeeded"&&!D&&(!h.hasOwnProperty("selected")||h.selected)&&(D=h)}),D&&D.localCandidateId){let h=C.get(D.localCandidateId);h&&(M={type:h.candidateType,ip:h.ip||h.ipAddress,port:h.port||h.portNumber})}return M}).catch(()=>null)})}Pi.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,a=/^([gu])([0-9]+)$/;function s(f,C){let M=String(f);return a.test(M)?(c.warn(`Already composite id [${f}] type supplied [${C}]`),M):C===te.GROUP?"g"+M:C===te.USER?"u"+M:(c.warn(`Unknown type [${C}] for id [${f}]`),M.match(r)?"u"+M:M)}Pi.composeUserId=s;function d(f,C,M){let D=s(f,C);return p(D,M)}Pi.composeParticipantId=d;function p(f,C){return C?f+St+Xt+C:f}Pi.compose=p;function u(f){return d(f.id,f.idType||te.USER,f.deviceIdx||0)}Pi.composeId=u;function E(f){return f.participant?u(f.participant):d(f.participantId,f.participantType||te.USER,f.deviceIdx||0)}Pi.composeMessageId=E;function I(f){let C=String(f),M=C.match(a);return M?{id:Number(M[2]),type:M[1]==="g"?te.GROUP:te.USER}:(c.warn(`Unsupported compositeId [${f}]`),{id:Number(C),type:te.USER})}Pi.decomposeId=I;function R(f){let C=f.split(St+Xt);return{compositeUserId:C[0],deviceIdx:C.length>1?parseInt(C[1],10):0}}Pi.decomposeParticipantId=R;function b(){var J,Y;let f=(Y=(J=window.crypto)==null?void 0:J.randomUUID)==null?void 0:Y.call(J);if(f)return f;let C="0123456789abcdefghijklmnopqrstuvwxyz".split(""),M=new Array(36),D=0,h,x;for(x=0;x<36;x++)x===8||x===13||x===18||x===23?M[x]="-":x===14?M[x]="4":(D<=2&&(D=33554432+Math.random()*16777216|0),h=D&15,D=D>>4,M[x]=C[x===19?h&3|8:h]);return M.join("")}Pi.uuid=b;function V(f,C){let M;function D(){let h=this,x=arguments;M&&window.clearTimeout(M),M=window.setTimeout(()=>{f.apply(h,x)},C)}return D}Pi.throttle=V;function Z(f){if(!window.BigInt)return null;let C="",M=f.split(`
9
+ `);for(let x of M)if(x.startsWith("a=fingerprint")){let J=x.split(" ");if(J.length===2){C=J[1];break}}if(!C)return BigInt(-1);let D=C.split(":"),h=BigInt(0);for(let x=Math.min(7,D.length-1);x>=0;x--){let J=BigInt(parseInt(D[x],16));h<<=BigInt(8),h|=J}return BigInt.asIntN(64,h)}Pi.sdpFingerprint=Z;function _e(f){return o(this,null,function*(){return new Promise(C=>window.setTimeout(C,f))})}Pi.delay=_e;function $(f,C,M){let D=[];return f.getSenders().forEach(h=>Ae(C,h,h.track,M,D)),D}Pi.applySettings=$;function Ae(f,C,M,D,h){var x;if(f&&M&&M.kind===me.video){let J=M.getSettings();if(J){let Y=f.maxBitrateK?f.maxBitrateK*1024:null,Ee=J.width,ge=J.height,We=Ee&&ge&&f.maxDimension?Math.max(1,Math.max(Ee,ge)/f.maxDimension):null,Le=f.maxFramerate?f.maxFramerate:null;if(Ee&&ge&&f.maxDimension&&f.maxDimension>Math.max(Ee,ge)){let Be=Math.round(Ee*ge/256),U=(Math.round(Be*rn/1e4)+1)*1e4;Y=Y===null?U:Math.min(U,Y)}let Ne=f.degradationPreference?f.degradationPreference:"balanced",Ue=D[M.id];if(Ue&&Ue.bitrate===Y&&Ue.scaleResolutionDownBy===We&&Ue.maxFramerate===Le&&Ue.degradationPreference===Ne){h[M.id]=Ue;return}h[M.id]={bitrate:Y,scaleResolutionDownBy:We,maxFramerate:Le,degradationPreference:Ne};let je=C.getParameters();je.encodings||(je.encodings=[{}]),je.encodings.forEach(Be=>{Y?Be.maxBitrate=Y:delete Be.maxBitrate,We?Be.scaleResolutionDownBy=We:delete Be.scaleResolutionDownBy,Le?Be.maxFramerate=Le:delete Be.maxFramerate}),je.degradationPreference=Ne,(x=C.setParameters)==null||x.call(C,je)}}}Pi.applyVideoTrackSettings=Ae;function ne(f,C){Array.isArray(C)||(C=[C]);for(let M of C)if(f.includes(M))return!0;return!1}Pi.includesOneOf=ne;function Re(f){var C;return Object.entries(((C=f.participantState)==null?void 0:C.state)||{}).reduce((M,[D,h])=>(f.participantState&&(M[D]={ts:f.participantState.stateUpdateTs[D],state:h}),M),{})}Pi.mapParticipantState=Re;function De(f){let C=f.map(M=>({uid:M.externalId,mediaSettings:M.mediaSettings,status:M.status,muteStates:M.muteStates,unmuteOptions:M.unmuteOptions,participantState:M.participantState,markers:M.markers,movieShareInfos:M.movieShareInfos}));return l.filterObservers?C.filter(M=>!M.uid.observer):C}Pi.mapSharedParticipants=De;function it(f,C){let M=Object.keys(f),D=Object.keys(C);if(M.length!==D.length)return!1;for(let h of M)if(!D.hasOwnProperty(h)||f[h].state!==C[h].state||f[h].ts!==C[h].ts)return!1;return!0}Pi.isEqualParticipantState=it;function Mt(f,C){let M=Object.keys(f),D=Object.keys(C);if(M.length!==D.length)return!1;for(let h of M)if(!C.hasOwnProperty(h)||f[h]!==C[h])return!1;return!0}Pi.isObjectsEquals=Mt;function ie(f,C){if(f.length!==C.length)return!1;for(let M of f)if(C.indexOf(M)<0)return!1;return!0}Pi.isArraysEquals=ie;function hr(f){return!Object.keys(f).length}Pi.isEmptyObject=hr;function _r(f,C){if(!f&&!C)return 0;if(!f||!C)return f?-1:1;return D(C.rank,f.rank)||D(f.ts,C.ts)||M(f,C);function M(h,x){let J={[te.USER]:0,[te.GROUP]:1},{compositeUserId:Y,deviceIdx:Ee}=R(h.id),{compositeUserId:ge,deviceIdx:We}=R(x.id),{id:Le,type:Ne}=I(Y),{id:Ue,type:je}=I(ge);return D(J[Ne],J[je])||D(Le,Ue)||D(Ee,We)}function D(h,x){return h<x?-1:h===x?0:1}}Pi.participantMarkerCompare=_r;function gr(f,C){let M=Object.entries(f).filter(([,D])=>Array.isArray(C)?!C.includes(D):D!==C);return ta(M)}Pi.objectFilterOutValues=gr;function q(f,C,M){let D=M;for(let h in f)!f.hasOwnProperty(h)||(D=C(D,f[h],h));return D}Pi.objectReduce=q,Pi.setImmediate=(()=>{let f=1,C={},M=null;return typeof MessageChannel!="undefined"&&(M=new MessageChannel,M.port1.onmessage=D=>{let h=D.data;C[h]&&(C[h](),delete C[h])}),function(D){if(M&&document.visibilityState==="hidden"){let x=f;return f=f>=Number.MAX_SAFE_INTEGER?1:f+1,C[x]=D,M.port2.postMessage(x),()=>{C[x]&&delete C[x]}}let h=setTimeout(D,0);return()=>clearTimeout(h)}})()})(Wi||(Wi={}));var v=Wi;var nt=null,ji=null,Zt=[],ei=[],Ki=[],Lt=null,Nt=null,$i=null,qi=!1,Ji=!1,ti,vt,ii,ia=!1,ra=!1,zi=null,Yi="",ri=[],Qi=null,aa=navigator.appVersion,nn=navigator.appName,Oe=navigator.userAgent,na=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(na||{}),Ut=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;Nt&&(d=Nt.deviceId),typeof e=="string"&&(d=e),d&&(a.deviceId={ideal: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;Lt&&(d=Lt.deviceId),typeof t=="string"&&(d=t),d&&(s.deviceId={ideal:d}),l.videoFacingMode&&(s.facingMode={ideal: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}},sa=class extends Ut{constructor(e,t,i){super(i,!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,Qe.browserName()==="Safari"&&Number(Qe.browserVersion())===16&&(delete this.video.width,delete this.video.height)}};function sn(){return o(this,null,function*(){nt=null,yield ai()})}function on(){nt=null,ai().then(()=>g.onDeviceChange())}function ai(){return o(this,null,function*(){return nt||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!ji&&navigator.mediaDevices.addEventListener&&(ji=v.throttle(on,1e3),navigator.mediaDevices.addEventListener("devicechange",ji)),nt=navigator.mediaDevices.enumerateDevices().then(n=>{Zt=n.filter(r=>r.kind==="videoinput"?(r.label&&(qi=!0),!0):!1),ei=n.filter(r=>r.kind==="audioinput"?(r.label?Ji=!0:Qe.isMobile()&&Qe.browserName()==="Firefox"&&(Ji=qi),!0):!1),Ki=n.filter(r=>r.kind==="audiooutput");let e=et.get("videoinput"),t=et.get("audioinput"),i=et.get("audiooutput");return Lt=Zt.find(r=>r.deviceId===e)||null,Nt=ei.find(r=>r.deviceId===t)||null,$i=Ki.find(r=>r.deviceId===i)||null,nt=Promise.resolve(n),n}).catch(()=>(nt=null,[]))))})}function cn(){return o(this,null,function*(){return Qe.isBrowserSupported()?new Promise(n=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(ia=!0),/^a=mid:0$/m.test(t.sdp)&&(ra=!0),n()}).catch(n)}):Promise.resolve()})}function ni(n,e){return o(this,null,function*(){c.debug("Try to get media",n.getNative());let t=Qe.hasPermissions(n.isVideo());!t&&!e&&g.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(n.getNative());return t||(yield sn()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=n.isVideo()?ce.CAMERA_PERMISSION:ce.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=n.isVideo()?ce.CAMERA_ACCESS:ce.MIC_ACCESS;break}if(n.canSimplify())return ni(n.simplify(),e);let r=e||ce.UNKNOWN;throw g.onPermissionsError(r),r}})}function dn(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 ce.SCREEN_PERMISSION;default:throw ce.SCREEN_ACCESS}}})}function si(){return ri.length||(ri=(()=>{let n,e=!1,t=0,i="0",r=Oe.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return n=/\brv[ :]+(\d+)/g.exec(Oe),["IE",n&&n[1]||"Unknown",e,t,i];if(r[1]==="Safari"){if(n=Oe.match(/\bEdge\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t,i];if(n=Oe.match(/\bCriOS\/(\d+)/),n)return["Chrome",n[1],!0,Number(n[1]),i];if(n=Oe.match(/\bFxiOS\/(\d+)/),n)return["Firefox",n[1],!1,t,i];if(n=Oe.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1],!1,t,i];if(n=Oe.match(/\bOPT\/(\d+)/),n)return["Opera",n[1],!1,t,i]}if(r[1]==="Chrome"){if(e=!0,t=Number(r[2]),n=Oe.match(/\bOPR\/(\d+)/),n)return["Opera",n[1]||"Unknown",e,t,i];if(n=Oe.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1]||"Unknown",e,t,i];if(n=Oe.match(/\bSferum\/((\d+)(?:\.\d+)*)/),n)return["Sferum",n[1]||"Unknown",e,t,i];if(n=Oe.match(/\bEdge?\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t,i];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t,i]}return n=Oe.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),n&&n[2]!==void 0&&(i=n[2]),[r[2]?r[1]:nn,n&&n[1]||r[2]||aa,e,t,i]})()),ri}var Qe;(D=>{function n(){return o(this,null,function*(){let h=()=>{$(),document.removeEventListener("click",h),document.removeEventListener("touchstart",h)};return document.addEventListener("click",h),document.addEventListener("touchstart",h),yield cn(),ai()})}D.init=n;function e(){return Zt}D.getCameras=e;function t(){return ei}D.getMicrophones=t;function i(){return Ki}D.getOutput=i;function r(){return Zt.length>0}D.hasCamera=r;function a(){return ei.length>0}D.hasMicrophone=a;function s(){return Lt}D.getSavedCamera=s;function d(){return Nt}D.getSavedMicrophone=d;function p(){return $i}D.getSavedOutput=p;function u(){return qi}D.hasCameraPermission=u;function E(){return Ji}D.hasMicrophonePermission=E;function I(h=!1){return E()?r()&&h?u():!0:!1}D.hasPermissions=I;function R(h=!1,x=!0,J=!0){return o(this,null,function*(){let Y=a()&&x,Ee=r()&&h,ge;if(!Y&&!Ee)ge=new MediaStream;else try{ge=yield ni(new Ut(Y,Ee))}catch(We){ge=new MediaStream}return!ge.getVideoTracks().length&&J&&ge.addTrack(Ae()),!ge.getAudioTracks().length&&J&&ge.addTrack($()),ge})}D.getUserMedia=R;function b(h){return o(this,null,function*(){return dn(new sa(window.screen.width,window.screen.height,h))})}D.getScreenMedia=b;function V(h,x=!1){return o(this,null,function*(){let J=x?l.videoEffectMaxWidth:l.videoMaxWidth,Y=x?l.videoEffectMaxHeight:l.videoMaxHeight;return ni(new Ut(!1,h||!0,J,Y))})}D.getUserVideo=V;function Z(h){return o(this,null,function*(){return ni(new Ut(h||!0,!1))})}D.getUserAudio=Z;function _e(h,x){return o(this,null,function*(){let Y=(yield ai()).find(Ee=>Ee.kind===h&&Ee.deviceId===x);return Y?(h==="videoinput"?Lt=Y:h==="audioinput"?Nt=Y:h==="audiooutput"&&($i=Y),et.set(h,x),Y):null})}D.saveDeviceId=_e;function $(){if(!ii||ii.readyState==="ended"){let h=f(),x=h.createMediaStreamDestination(),J=h.createGain();J.gain.value=1e-5,J.connect(x),J.connect(h.destination);let Y=h.createOscillator();Y.type="sine",Y.frequency.value=0,Y.connect(J),Y.start(),ii=x.stream.getAudioTracks()[0]}return Object.assign(ii.clone(),{enabled:!1})}D.getSilentMediaTrack=$;function Ae(h=l.videoMinWidth,x=l.videoMinHeight){return vt||(vt=document.createElement("canvas"),vt.getContext("2d")),vt.width=h,vt.height=x,(!ti||ti.readyState==="ended")&&(ti=vt.captureStream(l.videoFrameRate).getVideoTracks()[0]),Object.assign(ti.clone(),{enabled:!1})}D.getBlackMediaTrack=Ae;function ne(){if(q()==="Edge"&&Number(Ri())<70)return!1;try{let h=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&h.RTCPeerConnection&&h.RTCIceCandidate&&h.RTCSessionDescription&&h.HTMLCanvasElement&&h.HTMLCanvasElement.prototype.captureStream&&h.RTCRtpSender&&h.RTCRtpSender.prototype.replaceTrack&&h.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(h){return!1}}D.isBrowserSupported=ne;function Re(){return!!navigator.mediaDevices.getDisplayMedia}D.isScreenCapturingSupported=Re;function De(){return ia}D.canVP8=De;function it(){return ra}D.isUnifiedPlan=it;function Mt(){let h=D.browserName()==="Safari"&&D.browserVersion()==="15"&&D.browserSubVersion()==="1",x=D.browserName()==="Opera"&&D.os()==="Windows";return h||x}D.isBrokenH264=Mt;function ie(){return!(D.baseChromeVersion()&&D.isMobile())}D.canPreferH264=ie;function hr(){var h;return((h=window.RTCRtpTransceiver)==null?void 0:h.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}D.canPreferRed=hr;function _r(){return Yi||(Yi=(()=>{let h={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let x in h)if(h.hasOwnProperty(x)&&h[x].test(Oe))return x;return"Unknown"})()),Yi}D.os=_r;function gr(){return zi===null&&(zi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(aa)),zi}D.isMobile=gr;function q(){return si()[0]}D.browserName=q;function Ri(){return si()[1]}D.browserVersion=Ri;function Pi(){return si()[3]}D.baseChromeVersion=Pi;function f(){return Qi||(Qi=new(window.AudioContext||window.webkitAudioContext)),Qi}D.getAudioContext=f;function C(){return si()[4]}D.browserSubVersion=C;function M(){return D.baseChromeVersion()>0&&!D.isMobile()}D.isAudioShareSupported=M})(Qe||(Qe={}));var P=Qe;var Xe=class extends Ke{init(e){return o(this,null,function*(){c.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var i=Object.defineProperty;var b=a=>i(a,"__esModule",{value:!0});var E=(a,o)=>{b(a);for(var r in o)i(a,r,{get:o[r],enumerable:!0})};var D={};E(D,{default:()=>g});var s=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(s||{}),t=(e=>(e.INIT="init",e.READY="ready",e.FRAME="frame",e.SET_BITRATE="set_bitrate",e.ERROR="error",e.DEBUG="debug",e.LOG_ERROR="log_error",e))(t||{});var g=a=>{let o=null,r=!0;function l(){self.postMessage({type:t.READY})}function p(d,u,e,c=!1){if(!o||r!==e){if(!c){self.postMessage({type:t.DEBUG,message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}r=e,o?self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec changed to ${e?"VP9":"VP8"}`}):(self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec ${e?"VP9":"VP8"}`}),o=new VideoDecoder({output:n=>{let m=a?[n]:[];self.postMessage({type:t.FRAME,data:n},m),n.close()},error:n=>{o&&o.state!=="closed"&&o.close(),o=null,self.postMessage({type:t.FRAME,error:"WebCodecsDecoder failed, reinitialize: "+String(n)})}})),o.configure({codec:e?s.VP9:s.VP8})}let f=new EncodedVideoChunk({type:c?"key":"delta",timestamp:d,data:u});o.decode(f)}self.onmessage=d=>{switch(d.data.type){case t.INIT:l();break;case t.FRAME:p(d.data.timestamp,d.data.data,d.data.isVP9,d.data.keyFrame);break}}};return D;})();\n',t=>{t.error?c.warn("WebCodecsDecoder",t.error):e(t.data)},[P.baseChromeVersion()>=92])})}decodeFrame(e,t,i,r=!1){this._sendToWorker(Ie.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),c.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window}};import{BitStream as pn}from"bit-buffer";var ln=65536,st=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)%ln!==e.sequence){c.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:a}=st.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:a})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((a,s)=>a+s.data.byteLength,0),i=new Uint8Array(t),r=0;for(let a of e)i.set(new Uint8Array(a.data),r),r+=a.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new pn(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 Et=class{constructor(e){this._onStream=e}drawFrame(e){return o(this,null,function*(){throw new Error("Method `drawFrame` is not supported by this implementation")})}drawImage(e){throw new Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Bt=class extends Et{constructor(e){super(e);this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;c.debug("CanvasRenderer started"),this._useImageBitmap="ImageBitmap"in window}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}drawFrame(e){return o(this,null,function*(){let t="createImageBitmap"in e?yield e.createImageBitmap():yield createImageBitmap(e);this.drawImage(t),t.close()})}drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}destroy(){this._removeStream(),c.debug("CanvasRenderer destroyed")}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(P.browserName()==="Safari"&&Number(P.browserVersion())===15)}};var It=class extends Et{constructor(e){super(e);c.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:me.video}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}drawFrame(e){return o(this,null,function*(){yield this._writer.write(e)})}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),c.debug("TrackGeneratorRenderer destroyed")}static isBrowserSupported(){return"VideoFrame"in window&&"MediaStreamTrackGenerator"in window&&Xe.isBrowserSupported()}};var Vt=class extends st{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];c.debug(`StreamBuilder started for participant [${e}]`),It.isBrowserSupported()?this._renderer=new It(t):this._renderer=new Bt(t),Xe.isBrowserSupported()?this._decoder=new Xe:this._decoder=new gt;let i=r=>o(this,null,function*(){"VideoFrame"in window&&r instanceof VideoFrame?yield this._renderer.drawFrame(r):this._renderer.drawImage(r)});this._decoder.init(i).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._renderer.destroy(),c.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return Bt.isBrowserSupported()||It.isBrowserSupported()}};var Ft=1,un=1,mn=2,Xi=0,oi=11,oa=1,ca=2,da=4,pa=8;function la(n,e,t,i,r,a,s){let d=0;e&&(d|=oa),t&&(d|=ca),i&&(d|=da),s||(d|=pa);let p=new ArrayBuffer(oi),u=new DataView(p);if(u.setUint8(0,Ft),u.setUint16(1,r),u.setUint32(3,n),u.setUint8(7,a?1:0),u.setUint16(8,Xi),u.setUint8(10,d),!s)return p;let E=new Uint8Array(p.byteLength+s.byteLength);return E.set(new Uint8Array(p),0),E.set(new Uint8Array(s),p.byteLength),E.buffer}function ua(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&oa),u=!!(d&ca),E=!!(d&da),I=!!(d&pa);if(t!==Ft)throw new Error(`Unexpected protocol version. Got ${t}, expected ${Ft}`);return{timestamp:r,start:p,end:u,keyframe:E,sequence:i,isVP9:a,ssrc:s,eos:I,data:n.slice(oi)}}function ma(n){if(!n||!n.byteLength||n.byteLength!==4)return!1;let e=new DataView(n);return!(e.getUint8(0)!==Ft||e.getUint8(1)!==un||e.getUint16(2)!==Xi)}function ha(n){if(!n||!n.byteLength||n.byteLength!==10)return null;let e=new DataView(n);if(e.getUint8(0)!==Ft||e.getUint8(1)!==mn||e.getUint16(2)!==Xi)return null;let a=e.getUint16(4),s=e.getUint32(6);return{seq:a,ts2:s}}import*as y from"simple-ebml-builder";var hn=vr(2,15)-1,Zi=1,_n=5,gn=5;var ci=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=ci._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return y.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=y.build(a);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var a,s,d;((a=this._mediaSource)==null?void 0:a.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let e=(d=this._sourceBuffer)==null?void 0:d.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-_n);r-i>gn&&(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}},Ge=class extends st{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 y.element(y.ID.EBML,[y.element(y.ID.EBMLVersion,y.number(1)),y.element(y.ID.EBMLReadVersion,y.number(1)),y.element(y.ID.EBMLMaxIDLength,y.number(4)),y.element(y.ID.EBMLMaxSizeLength,y.number(8)),y.element(y.ID.DocType,y.string("webm")),y.element(y.ID.DocTypeVersion,y.number(2)),y.element(y.ID.DocTypeReadVersion,y.number(2))])}static _genSegmentHeader(e,t,i){let r=y.element(y.ID.Info,[y.element(y.ID.TimecodeScale,y.number(1e6)),y.element(y.ID.MuxingApp,y.string("vk-webm-builder")),y.element(y.ID.WritingApp,y.string("vk-webm-builder"))]),a=[y.element(y.ID.PixelWidth,y.number(e)),y.element(y.ID.PixelHeight,y.number(t))],s=y.element(y.ID.Tracks,y.element(y.ID.TrackEntry,[y.element(y.ID.TrackNumber,y.number(Zi)),y.element(y.ID.TrackUID,y.number(Zi)),y.element(y.ID.TrackType,y.number(1)),y.element(y.ID.FlagLacing,y.number(0)),y.element(y.ID.DefaultDuration,y.number(1e9)),y.element(y.ID.CodecID,y.string(`V_${i.toUpperCase()}`)),y.element(y.ID.Video,a)]));return y.unknownSizeElement(y.ID.Segment,[r,s])}static _genClusterHeader(e){return y.unknownSizeElement(y.ID.Cluster,[y.element(y.ID.Timecode,y.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new ci(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){c.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>c.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,c.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),c.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=Ge._genWebmHeader();this._mediaBuffer.append(s);let d=Ge._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(d)}let r=Math.round(i-this._clusterStartTime);if(r>hn&&(this._clusterStartTime=i,r=0),r===0){c.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=Ge._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let a=y.element(y.ID.SimpleBlock,[y.vintEncodedNumber(Zi),y.bytes(Ge._intToU16BE(r)),y.number((e.keyframe?1:0)<<7),y.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=()=>{};c.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=a=>this._onDataChannelMessage(a.data)}_onDataChannelMessage(e){var a,s;let t=ua(e),i=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){c.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];if(!r){let d=p=>this._onStream(i,p);l.screenShareWebmBuilder&&Ge.isBrowserSupported()?r=new Ge(i,d):r=new Vt(i,d),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,c.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(Xe.isBrowserSupported()||gt.isBrowserSupported())&&(Vt.isBrowserSupported()||Ge.isBrowserSupported())}};import _a from"@vkontakte/libvpx";var fn=1e3,Ht=class extends Ke{constructor(e,t,i,r){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useCongestionControl=i,this._maxBitrate=r,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");this._video.paused&&this._video.play();let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return o(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return o(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;c.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var m=Object.defineProperty;var y=s=>m(s,"__esModule",{value:!0});var x=(s,i)=>{y(s);for(var d in i)m(s,d,{get:i[d],enumerable:!0})};var h={};x(h,{default:()=>V});var t=(a=>(a.INIT="init",a.READY="ready",a.FRAME="frame",a.SET_BITRATE="set_bitrate",a.ERROR="error",a.DEBUG="debug",a.LOG_ERROR="log_error",a))(t||{});var V=(s,i,d,E)=>{let r;function g(e,o){return s({locateFile:i}).then(n=>{if(r=new n.VpxEncoder,r.debug(o),!r.init(e?n.VpxType.VP9:n.VpxType.VP8))throw self.postMessage({type:t.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");if(d){let p=Math.round(E/1e3);r.setTargetBitrate(p)}else r.setMaxQuantizer(10),r.setTargetBitrate(1024)})}function R(e,o,n,c){let p=r.allocateImage(e,o);if(!p){self.postMessage({type:t.FRAME,error:"No buffer data"});return}p.set(new Uint8Array(n));let f=Math.round(performance.now()),u=150;if(!r.encode(f,u,c)){self.postMessage({type:t.FRAME,error:"Encode failed"});return}let l=r.readFrame();if(!l){self.postMessage({type:t.FRAME,error:"No encoded data"});return}r.readFrame()&&(self.postMessage({type:t.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxEncoder-drop"}));let b=new Uint8Array(l.byteLength);b.set(l),self.postMessage({type:t.FRAME,frameType:c?"key":"delta",timestamp:f,duration:u,width:e,height:o,data:b.buffer},[b.buffer])}function a(e,o){let n=Math.round(e/1e3);r.setTargetBitrate(n)}self.onmessage=e=>{switch(e.data.type){case t.INIT:g(e.data.isVP9,e.data.debug).then(()=>self.postMessage({type:t.READY})).catch(o=>self.postMessage({type:t.ERROR,error:String(o)}));break;case t.FRAME:R(e.data.width,e.data.height,e.data.imageData,e.data.keyFrame);break;case t.SET_BITRATE:a(e.data.bitrate,e.data.useCbr);break}}};return h;})();
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,width:i.width,height:i.height})},[_a,_a.getUrl,this._useCongestionControl,this._maxBitrate],{isVP9:this.isVP9(),debug:c.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(Ie.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)},fn),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)}setBitrate(e,t=!1){this._sendToWorker(Ie.SET_BITRATE,{bitrate:e,useCbr:t})}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 Ct=class extends Ke{constructor(e,t,i,r){super();this._sourceTrack=e,this._onFrame=t,this._useCongestionControl=i,this._maxBitrate=r,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 A=Object.defineProperty;var B=n=>A(n,"__esModule",{value:!0});var x=(n,i)=>{B(n);for(var o in i)A(n,o,{get:i[o],enumerable:!0})};var P={};x(P,{default:()=>I});var c=(o=>(o.VP9="vp09.00.50.08",o.VP8="vp8",o))(c||{}),a=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.SET_BITRATE="set_bitrate",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(a||{});var I=()=>{let n=1e3,i,o,l,d,R,p,t=null,E=0,u=!1,s=0,g,V,y=!1;function F(e){i=e.readable,o=i.getReader(),l=e.width,d=e.height,R=e.isVP9,p=e.framerate,g=e.useCongestionControl,V=e.maxBitrate,g&&(s=V),f(),self.postMessage({type:a.READY})}function C(e){E=self.setTimeout(()=>{t&&h(t,e)},n),!u&&(u=!0,o.read().finally(()=>{u=!1,self.clearTimeout(E)}).then(({done:r,value:b})=>{if(t==null||t.close(),t=null,!(r||!b)){if(!m){o.releaseLock(),i.cancel();return}t=b,h(b,e)}}))}function h(e,r){(e.codedWidth!==l||e.codedHeight!==d)&&(l=e.codedWidth,d=e.codedHeight,f()),m.encode(e,{keyFrame:r})}function f(){let e={framerate:p,codec:R?c.VP9:c.VP8,width:l,height:d,latencyMode:"realtime",bitrateMode:y?"constant":"variable"};s>0&&(e.bitrate=s),m.configure(e)}function T(e,r=!1){s=e,y=r,f()}let m=new VideoEncoder({output:e=>{let r;e.data?r=e.data:(r=new ArrayBuffer(e.byteLength),e.copyTo(r)),self.postMessage({type:a.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,width:l,height:d,data:r},[r])},error:e=>{self.postMessage({type:a.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case a.INIT:F(e.data);break;case a.FRAME:C(e.data.keyFrame);break;case a.SET_BITRATE:T(e.data.bitrate,e.data.useCbr);break}}};return P;})();
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,width:r.width,height:r.height})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:l.screenFrameRate,useCongestionControl:this._useCongestionControl,maxBitrate:this._maxBitrate},[i])})}requestFrame(e=!1){this._sendToWorker(Ie.FRAME,{keyFrame:e})}setBitrate(e,t){this._sendToWorker(Ie.SET_BITRATE,{bitrate:e,useCbr:t})}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 Sn=1.2,ga=.8,vn=2e3,En=8e3,er=8e3,In=16e3,Tn=4,Cn=2e3,di=(i=>(i[i.NONE=0]="NONE",i[i.UP=1]="UP",i[i.DOWN=2]="DOWN",i))(di||{}),pi=class{constructor(e,t,i,r){this._upPenalty=0;this._delayAvgShort=-1;this._delayAvgLong=-1;this._minDelay=Number.MAX_VALUE;this._maxDelay=0;this._largeDelayDuration=0;this._onCongestion=e,this._ccEnabled=r,this._minBitrate=t,this._maxBitrate=i,this._targetBitrate=this._maxBitrate,this._probing=!1;let a=Date.now();this._lastDown=0,this._lastUp=a,this._lastProbing=a,this._lastCheckDelay=0}checkDelay(e,t,i){let r=Date.now();if(this._calcDelay(t,r),this._delayAvgShort<=0||this._delayAvgLong<=0||!this._ccEnabled)return;let a=0,s=this._delayAvgShort-this._delayAvgLong,d=Math.round(Math.abs(s)*100/this._delayAvgLong),p=s>40&&d>30&&this._delayAvgShort>700,u=this._delayAvgShort>2e3;p||u?a=2:Math.abs(s)<40&&d<10&&this._delayAvgShort<2e3&&(a=1);let E=Math.round(this._targetBitrate/1e3),I=i;e%100==0&&c.debug(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${di[a]} tr=${E} br=${i}`);let R=r-this._lastDown;if(a===2&&R>vn){this._probing&&(this._upPenalty=Math.min(++this._upPenalty,Tn),this._probing=!1);let $=ga*I*1e3;if($>=this._targetBitrate&&($=this._targetBitrate*ga),$=Math.max($,this._minBitrate),$<this._targetBitrate){let Ae=Math.round($/1e3),ne=Math.round(this._upPenalty*er/1e3);c.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${di[a]}`),c.log(`#${e}: cc: DOWN delay=${t} bitrate=${I} target=${E} -> newBitrate=${Ae} penalty=${ne}s`),this._onCongestion($,!0),this._targetBitrate=$}this._lastDown=r}let b=r-this._lastUp,V=En+this._upPenalty*er;if(a===1&&b>V&&R>V){let $=Math.min(this._targetBitrate*Sn,this._maxBitrate);if($>this._targetBitrate){let Ae=Math.round($/1e3),ne=Math.round(this._targetBitrate/1e3),Re=Math.round(this._upPenalty*er/1e3);c.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${di[a]}`),c.log(`#${e}: cc: UP bitrate=${I} target=${ne} -> newBitrate=${Ae} penalty=${Re}s`),this._onCongestion($,!1),this._targetBitrate=$,this._probing=!0,this._lastProbing=r,this._lastUp=r}}let Z=r-this._lastProbing;this._probing&&Z>In&&(this._probing=!1);let _e=r-this._lastDown;this._upPenalty>0&&_e>3*V&&(c.log(`#${e}: cc: UP reset penalty: oldPenalty=${this._upPenalty}`),this._upPenalty=0)}_calcDelay(e,t){if(!(e<=0)){if(this._delayAvgShort===-1&&(this._delayAvgShort=e,this._delayAvgLong=e),this._delayAvgShort=Math.round((this._delayAvgShort*3+e)/4),this._delayAvgLong=Math.round((this._delayAvgLong*23+e)/24),e>0&&e<this._minDelay?this._minDelay=e:e>this._maxDelay&&(this._maxDelay=e),this._lastCheckDelay===0&&(this._lastCheckDelay=t),e>Cn){let i=t-this._lastCheckDelay;this._largeDelayDuration+=i}this._lastCheckDelay=t}}reconfigure(e,t){this._minBitrate=e,this._maxBitrate=t}getStat(){if(this._minDelay===Number.MAX_VALUE||this._maxDelay===0||this._delayAvgLong<=0)return null;let e={minDelay:this._minDelay,maxDelay:this._maxDelay,avgDelay:this._delayAvgLong,largeDelayDuration:this._largeDelayDuration};return this._minDelay=Number.MAX_VALUE,this._maxDelay=0,this._largeDelayDuration=0,e}};var li=class{constructor(e){this._size=0;this._head=0;this._tail=0;this._maxSize=e,this._buffer=new Array(e)}add(e,t,i,r,a){this._tail===this._head&&this._size>0&&(this._head=++this._head%this._maxSize);let s=this._tail;return this._buffer[this._tail]={seq:e,ts:t,size:i,sent:Date.now(),start:r,end:a,ts2:-1,recv:-1},this._tail=++this._tail%this._maxSize,this._size++,s}update(e,t){let i=this.get(e);return i===null?null:(i.ts2=t,i.recv=Date.now(),i)}get(e){let t=this._head;for(let i=0;i<this._maxSize;i++){if(e===this._buffer[t].seq)return this._buffer[t];if(t=++t%this._maxSize,t===this._tail)break}return null}getServerBitrateK(e){let t=0,i=0,r=-1,a=-1,s=this._tail;for(let d=0;d<this._maxSize;d++){s>0?--s:s=this._maxSize-1;let p=this._buffer[s];if(p===null||(a===-1&&(a=p.ts2,i=0),a>=0&&(i+=p.size),r=p.ts2,a-r>=e)||s===this._head)break}if(r>=0&&a>=0){let d=a-r;t=Math.round(d>0?i*8/d:0)}return t}getCurrentDelay(){let e=this._tail;for(let t=0;t<this._maxSize;t++){e>0?--e:e=this._maxSize-1;let i=this._buffer[e];if(i===null)break;if(i.recv>=0&&i.sent>=0)return i.recv-i.sent;if(e===this._head)break}return 0}getMaxBandwidth(){let e=0,t=0,i=-1,r=-1,a=this._tail;for(let s=0;s<this._maxSize;s++){if(a>0?--a:a=this._maxSize-1,r===-1&&this._buffer[a].end&&!this._buffer[a].start&&(r=this._buffer[a].ts2,t=0),i===-1&&r>=0&&this._buffer[a].start&&!this._buffer[a].end&&(i=this._buffer[a].ts2),i>=0&&r>=0){let d=r-i;e=d>0?t*8/d:0;break}if(r>=0&&(t+=this._buffer[a].size),a===this._head)break}return Math.round(e)}};var yn=65536,Rn=50,Pn=400,bn=1e6,Mn=3e4,ui=0,yt=class{constructor(e,t,i){this._destroyed=!1;this._needKeyframe=!0;this._frameNum=0;this._feedback=new li(1024);this._lastSharingStat=Date.now();this._congestionControlEnabled=!1;c.debug("ScreenCaptureSender started"),this.DATA_SIZE=l.consumerScreenDataChannelPacketSize-oi,this._datachannel=t,this._signaling=i,this._congestionControlEnabled=l.screenShareCongestionControl,this._width=e.getSettings().width,this._height=e.getSettings().height;let{minBitrate:r,maxBitrate:a}=this._calcMinMaxBitrate(this._width,this._height),s=this._onCongestionCallback.bind(this);c.log(`ScreenCaptureSender: CongestionControl: enabled=${this._congestionControlEnabled} minBitrate=${Math.round(r/1e3)}k maxBitrate=${Math.round(a/1e3)}k`),this._congestionControl=new pi(s,r,a,this._congestionControlEnabled);let d=(p,u)=>{if(!this._destroyed){if(!p){c.warn("requestFrame failed, keyFrame: "+this._needKeyframe,u),this._needKeyframe=!0,this._requestFrame();return}(p.width!==this._width||p.height!==this._height)&&(this._width=p.width,this._height=p.height,this._onResize(this._width,this._height)),this._send(p).catch(E=>{c.warn("sendFrame failed",E),this._needKeyframe=!0}).finally(()=>{this._frameNum++,p.type==="key";let E=this._feedback.getCurrentDelay(),I=this._feedback.getServerBitrateK(2e3);E>0&&this._congestionControl.checkDelay(this._frameNum,E,I),this._requestFrame()}),this._sendSharingStat()}};Ct.isBrowserSupported()?this._encoder=new Ct(e,d,l.screenShareCongestionControl,a):this._encoder=new Ht(e,d,l.screenShareCongestionControl,a),this._datachannel.onmessage=p=>{ma(p.data)&&(c.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0);let u=ha(p.data);u!==null&&this._checkCcFeedback(u)},this._encoder.init().then(()=>this._requestFrame()).catch(p=>c.warn("ScreenCaptureSender init failed",p))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,a){let s=la(e,t,i,r,ui,this._encoder.isVP9(),a);return ui=(ui+1)%yn,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+this.DATA_SIZE),s=e.data.byteLength<=t+a.byteLength;this._feedback.add(ui,e.timestamp,a.byteLength,!t,s);let 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||v.setImmediate(()=>this._sendChunk(e,t+this.DATA_SIZE,i,r))}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 Ct.isBrowserSupported()||Ht.isBrowserSupported()}_onCongestionCallback(e,t){this._encoder.setBitrate(e,t)}_onResize(e,t){let{minBitrate:i,maxBitrate:r}=this._calcMinMaxBitrate(e,t),a=Math.round(i/1e3),s=Math.round(r/1e3);c.log(`cc: resize to ${e}x${t}, minBitrate=${a} maxBitrate=${s}`),this._congestionControl.reconfigure(i,r)}_calcMinMaxBitrate(e,t){(e===void 0||e<640)&&(e=640),(t===void 0||t<360)&&(t=360);let i=e*t/256,r=Math.min(bn,Math.round(i*Rn)),a=Math.round(i*Pn);return{minBitrate:r,maxBitrate:a}}_checkCcFeedback(e){this._feedback.update(e.seq,e.ts2)===null&&c.debug(`cc: update failed, seq=${e.seq}`)}_sendSharingStat(){let e=Date.now();if(e-this._lastSharingStat>Mn){let i=this._congestionControl.getStat();i!==null&&(c.debug(`cc: send stats: ${JSON.stringify(i)}`),this._signaling.reportSharingStat(i)),this._lastSharingStat=e}}};var se=class{static get sessionKey(){return se._sessionKey}static set sessionKey(e){se._sessionKey=e}static get sessionSecretKey(){return se._sessionSecretKey}static set sessionSecretKey(e){se._sessionSecretKey=e}static get accessToken(){return se._accessToken}static set accessToken(e){se._accessToken=e}static isEmpty(){return!se._sessionKey||!se._sessionSecretKey}};var S=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(S._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(S._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(S._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(se.accessToken=e.apiAuth.accessToken,se.sessionKey=e.apiAuth.sessionKey,se.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(S._params,v.objectFilterOutValues(e,void 0))}static get(e){return S._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.6.2-dev.30ea81e.0"}static get debug(){return undefined}static get protocolVersion(){return S._params.joinFromMultipleDevices?6:5}static get platform(){return S._params.platform}static set platform(e){S._params.platform=e}static get clientType(){return S._params.clientType}static set clientType(e){S._params.clientType=e}static get externalUserType(){return S._params.externalUserType}static set externalUserType(e){S._params.externalUserType=e}static get device(){return S._params.device}static get apiKey(){return S._params.apiKey}static get apiEnv(){return S._params.apiEnv}static get apiEndpoint(){switch(S.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return S._params.apiEnv}}static get authToken(){return S._params.authToken}static set authToken(e){S._params.authToken=e}static get anonymToken(){return S._params.anonymToken}static set anonymToken(e){S._params.anonymToken=e}static get domain(){return S._params.domain}static get externalDomain(){return S._params.externalDomain}static get iceServers(){return S._params.iceServers}static set iceServers(e){S._params.iceServers=e}static get wssBase(){return S._params.wssBase}static set wssBase(e){S._params.wssBase=e}static get wssToken(){return S._params.wssToken}static set wssToken(e){S._params.wssToken=e}static get signalingReconnectDelay(){return S._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return S._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return S._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return S._params.waitConnectionDelay}static get waitResponseDelay(){return S._params.waitResponseDelay}static get waitMessageDelay(){return S._params.waitMessageDelay}static get waitAnotherTabDelay(){return S._params.waitAnotherTabDelay}static get debugLog(){return S._params.debugLog}static get forceRelayPolicy(){return S._params.forceRelayPolicy}static set forceRelayPolicy(e){S._params.forceRelayPolicy=e}static get videoMinWidth(){return S._params.videoMinWidth}static get videoMaxWidth(){return S._params.videoMaxWidth}static set videoMaxWidth(e){S._params.videoMaxWidth=e}static get videoMinHeight(){return S._params.videoMinHeight}static get videoMaxHeight(){return S._params.videoMaxHeight}static set videoMaxHeight(e){S._params.videoMaxHeight=e}static get videoAspectRatio(){return S._params.videoAspectRatio}static get videoFrameRate(){return S._params.videoFrameRate}static get videoFacingMode(){return S._params.videoFacingMode}static get screenFrameRate(){return S._params.screenFrameRate}static get videoEffects(){return S._params.videoEffects}static set videoEffects(e){S._params.videoEffects=e}static get videoEffectMaxWidth(){return S._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){S._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return S._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){S._params.videoEffectMaxHeight=e}static get voiceParams(){return S._params.voiceParams}static get specListenerParams(){return S._params.specListenerParams}static get iceRestartWaitTime(){return S._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return S._params.transportConnectionWaitTime}static get statisticsInterval(){return S._params.statisticsInterval}static set statisticsInterval(e){S._params.statisticsInterval=e}static get networkStatisticsInterval(){return S._params.networkStatisticsInterval}static get perfStatReportEnabled(){return S._params.perfStatReportEnabled}static get callStatReportEnabled(){return S._params.callStatReportEnabled}static get producerNotificationDataChannel(){return S._params.producerNotificationDataChannel}static get producerCommandDataChannel(){return S._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return S._params.consumerScreenDataChannel&&yt.isBrowserSupported()}static get producerScreenDataChannel(){return S._params.producerScreenDataChannel&&S.producerNotificationDataChannel&&Tt.isBrowserSupported()}static get consumerScreenDataChannelPacketSize(){return S._params.consumerScreenDataChannelPacketSize}static get screenShareWebmBuilder(){return S._params.screenShareWebmBuilder}static get noiseSuppression(){return S._params.noiseSuppression}static set noiseSuppression(e){S._params.noiseSuppression=e}static get preferH264(){return S._params.preferH264}static get preferVP9(){return S._params.preferVP9}static get audioNack(){return S._params.audioNack}static get consumerScreenTrack(){return S._params.consumerScreenTrack&&S.consumerScreenDataChannel}static get producerScreenTrack(){return S._params.producerScreenTrack}static isUnifiedPlanSupported(e,t){let i=S._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return S._params.movieShare&&S.videoTracksCount>0}static get videoTracksCount(){return S.producerNotificationDataChannel?S._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return S._params.breakVideoPayloadTypes}static get filteredMessages(){return S._params.filteredMessages}static get useParticipantListChunk(){return S._params.useParticipantListChunk&&S._params.videoTracksCount>0}static get useRooms(){return S._params.useRooms}static get participantListChunkInitIndex(){var e;return(e=S._params.participantListChunkInitIndex)!=null?e:0}static get participantListChunkInitCount(){var e;return(e=S._params.participantListChunkInitCount)!=null?e:null}static get serverAudioRed(){return S._params.serverAudioRed&&P.canPreferRed()}static get p2pAudioRed(){return S._params.p2pAudioRed&&P.canPreferRed()}static get h264spsPpsIdrInKeyframe(){return S._params.h264spsPpsIdrInKeyframe}static get batchParticipantsOnStart(){return S._params.batchParticipantsOnStart}static get filterObservers(){return S._params.filterObservers}static get muteMode(){return S._params.muteMode}static get preserveAudioTracks(){return S._params.preserveAudioTracks}static get audioShareCapabilityEnabled(){return P.isAudioShareSupported()&&S._params.audioShareCapabilityEnabled}static get screenShareCongestionControl(){return S._params.screenShareCongestionControl}},l=S;l._params={platform:"WEB",clientType:"PORTAL",externalUserType:"",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",externalDomain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,consumerScreenDataChannelPacketSize:16*1024,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,useParticipantListChunk:!1,useRooms:!1,participantListChunkInitIndex:0,participantListChunkInitCount:null,serverAudioRed:!1,p2pAudioRed:!1,h264spsPpsIdrInKeyframe:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1,audioShareCapabilityEnabled:!1,screenShareCongestionControl:!1};var Q=(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))(Q||{});function G(n,...e){let t=l.get(n);t&&setTimeout(t,0,...e)}function pe(n,e,...t){if(l.filterObservers){if(Array.isArray(e)){if(e=e.filter(i=>!i.observer),!e.length)return}else if(e.observer)return}G(n,e,...t)}function be(n){return Object.assign({},n)}function ot(n){return n.slice()}var tr;(Ls=>{function n(m,A){G("onLocalStream",m,be(A))}Ls.onLocalStream=n;function e(m,A){G("onScreenStream",m,be(A))}Ls.onScreenStream=e;function t(m,A){G("onLocalStreamUpdate",be(m),A)}Ls.onLocalStreamUpdate=t;function i(m){G("onLocalStatus",m)}Ls.onLocalStatus=i;function r(m,A){pe("onRemoteStream",m,A)}Ls.onRemoteStream=r;function a(m,A){pe("onRemoteLive",m,A)}Ls.onRemoteLive=a;function s(m,A){pe("onLocalLive",m,A)}Ls.onLocalLive=s;function d(m,A){pe("onRemoteLiveUpdate",m,A)}Ls.onRemoteLiveUpdate=d;function p(m,A){pe("onLocalLiveUpdate",m,A)}Ls.onLocalLiveUpdate=p;function u(m,A){pe("onRemoteScreenStream",m,A)}Ls.onRemoteScreenStream=u;function E(m,A,re,rt,At){pe("onConversation",m,be(A),be(re),rt,At)}Ls.onConversation=E;function I(m){m&&G("onConversationParticipantListChunk",m)}Ls.onConversationParticipantListChunk=I;function R(m,A,re){pe("onRemoteMediaSettings",m,be(A),re)}Ls.onRemoteMediaSettings=R;function b(m,A){pe("onLocalMediaSettings",m,be(A))}Ls.onLocalMediaSettings=b;function V(m,A){pe("onRemoteSharedMovieInfo",m,be(A))}Ls.onRemoteSharedMovieInfo=V;function Z(m,A){pe("onRemoteSharedMovieStoppedInfo",m,be(A))}Ls.onRemoteSharedMovieStoppedInfo=Z;function _e(m,A){pe("onLocalSharedMovieInfo",m,be(A))}Ls.onLocalSharedMovieInfo=_e;function $(m,A){pe("onLocalSharedMovieStoppedInfo",m,be(A))}Ls.onLocalSharedMovieStoppedInfo=$;function Ae(m,A){pe("onParticipantAdded",m,A)}Ls.onParticipantAdded=Ae;function ne(m,A){pe("onParticipantJoined",m,A)}Ls.onParticipantJoined=ne;function Re(m,A,re){pe("onRemoteParticipantState",m,be(A),re)}Ls.onRemoteParticipantState=Re;function De(m,A,re=null){pe("onRemoteStatus",m,A,re)}Ls.onRemoteStatus=De;function it(m,A,re=null){pe("onParticipantStatus",m,A,re)}Ls.onParticipantStatus=it;function Mt(){G("onPermissionsRequested")}Ls.onPermissionsRequested=Mt;function ie(m){G("onPermissionsError",m)}Ls.onPermissionsError=ie;function hr(m,A){pe("onRemoteRemoved",m,A)}Ls.onRemoteRemoved=hr;function _r(m,A,re){G("onCallState",m,A,be(re))}Ls.onCallState=_r;function gr(m,A){G("onDeviceSwitched",m,A)}Ls.onDeviceSwitched=gr;function q(m,A,re,rt=!1,At=!1,bi=null,Va=null,Fa,fr){let Ha=fr?ot(fr):void 0;G("onMuteStates",be(m),ot(A),ot(re),rt,At,bi,Va,Fa,Ha)}Ls.onMuteStates=q;function Ri(m,A){pe("onRolesChanged",m,ot(A))}Ls.onRolesChanged=Ri;function Pi(m){G("onLocalRolesChanged",ot(m))}Ls.onLocalRolesChanged=Pi;function f(m,A,re){pe("onPinnedParticipant",m,A,re)}Ls.onPinnedParticipant=f;function C(m){G("onLocalPin",m)}Ls.onLocalPin=C;function M(m){G("onOptionsChanged",ot(m))}Ls.onOptionsChanged=M;function D(){G("onCallAccepted")}Ls.onCallAccepted=D;function h(){G("onRateNeeded")}Ls.onRateNeeded=h;function x(m){pe("onSpeakerChanged",m)}Ls.onSpeakerChanged=x;function J(m){G("onVolumesDetected",ot(m))}Ls.onVolumesDetected=J;function Y(m,A){G("onLocalVolume",m,A)}Ls.onLocalVolume=Y;function Ee(m,A){G("onJoinStatus",m,A)}Ls.onJoinStatus=Ee;function ge(m,A){G("onHangup",m,A)}Ls.onHangup=ge;function We(m){G("onMultipartyChatCreated",be(m))}Ls.onMultipartyChatCreated=We;function Le(){G("onDeviceChange")}Ls.onDeviceChange=Le;function Ne(m){G("onFingerprintChange",m)}Ls.onFingerprintChange=Ne;function Ue(){G("onTokenExpired")}Ls.onTokenExpired=Ue;function je(m,A,re=!1){G("onChatMessage",m,A,re)}Ls.onChatMessage=je;function Be(m,A,re=!1){G("onCustomData",m,A,re)}Ls.onCustomData=Be;function U(m,A,re,rt,At,bi){G("onRecordStarted",m,A,re,rt,At,bi)}Ls.onRecordStarted=U;function L(){G("onRecordStopped")}Ls.onRecordStopped=L;function K(m){G("onLocalNetworkStatusChanged",m)}Ls.onLocalNetworkStatusChanged=K;function fe(m){G("onNetworkStatusChanged",m)}Ls.onNetworkStatusChanged=fe;function Ce(m,...A){G("onDebugMessage",m,...A)}Ls.onDebugMessage=Ce;function ee(m,A){let re=Object.assign({},m,{memory:A});G("onStatistics",re)}Ls.onStatistics=ee;function X(){G("onAutoplayError")}Ls.onAutoplayError=X;function oe(m,A,re){G("onChatRoomUpdated",m,A,re)}Ls.onChatRoomUpdated=oe;function Je(m){G("onRemoteMixedAudioStream",m)}Ls.onRemoteMixedAudioStream=Je;function bs(m){G("onJoinLinkChanged",m)}Ls.onJoinLinkChanged=bs;function Ms(m){G("onRoomsUpdated",m)}Ls.onRoomsUpdated=Ms;function As(m,A,re,rt){G("onRoomUpdated",m,A,re,rt)}Ls.onRoomUpdated=As;function Ds(m){G("onRoomParticipantsUpdated",m)}Ls.onRoomParticipantsUpdated=Ds;function ks(m){G("onFeedback",m)}Ls.onFeedback=ks;function Os(m){G("onFeaturesPerRoleChanged",m)}Ls.onFeaturesPerRoleChanged=Os;function ws(m,A){G("onAsrStarted",m,A)}Ls.onAsrStarted=ws;function xs(){G("onAsrStopped")}Ls.onAsrStopped=xs})(tr||(tr={}));var g=tr;var fa=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(fa||{}),ir;(ne=>{let n="📞",e=(Re,...De)=>{g.onDebugMessage(Re,...De)},t=!1,i=(Re,De)=>(...it)=>{Re(...it),zr(De,it)},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=e.bind(null,"WARN"),I=e.bind(null,"ERROR");ne.debug=p,ne.log=u,ne.warn=E,ne.error=I;function _e(){return t}ne.enabled=_e;function $(Re){t=Re,l.debugLog&&Ni(),Re?(ne.debug=l.debugLog?i(r,"DEBUG"):r,ne.log=l.debugLog?i(a,"LOG"):a,ne.warn=l.debugLog?i(s,"WARN"):s,ne.error=l.debugLog?i(d,"ERROR"):d):(ne.debug=l.debugLog?i(p,"DEBUG"):p,ne.log=l.debugLog?i(u,"LOG"):u,ne.warn=l.debugLog?i(E,"WARN"):E,ne.error=l.debugLog?i(I,"ERROR"):I)}ne.toggle=$;function Ae(Re,...De){switch(Re){case"DEBUG":ne.debug(...De);break;case"LOG":ne.log(...De);break;case"WARN":ne.warn(...De);break;case"ERROR":ne.error(...De);break}}ne.send=Ae})(ir||(ir={}));var c=ir;var Rt=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(Rt||{}),Te;(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})(Te||(Te={}));var ve;(r=>{function n(a,s="USER",d=0){return{id:a,type:s,deviceIdx:d}}r.fromId=n;function e(a){return`{"id":"${a.id}","type":"${a.type}","deviceIdx":"${a.deviceIdx}"}`}r.toString=e;function t(a,s){return Object.assign({deviceIdx:s},Te.fromSignaling(a))}r.fromSignaling=t;function i(a){return a&&typeof a=="object"?a.deviceIdx:0}r.getDeviceIdx=i})(ve||(ve={}));var An="kf";function Gt(n){return n.stopStream}function rr(n){return n.keyFrameRequested}function Sa(n){if(Gt(n))return"ss";if(rr(n))return An;let e="";return n.priority!==void 0&&(e+="p="+n.priority),n.width!==void 0&&n.height!==void 0&&(e!==""&&(e+=":"),e+="sz="+Math.round(n.width)+"x"+Math.round(n.height)),n.fit!==void 0&&(e!==""&&(e+=":"),e+="fit="+n.fit),e}var Me=(a=>(a.CAMERA="CAMERA",a.SCREEN="SCREEN",a.STREAM="STREAM",a.MOVIE="MOVIE",a.AUDIOSHARE="AUDIOSHARE",a))(Me||{}),va="s",Ea="m";function $e(n){return n.participantId+(n.mediaType?St+va+n.mediaType:"")+(n.streamName?St+Ea+n.streamName:"")}function Wt(n){let e=n.split(St),t=e.shift();if(!t)throw new Error("Illegal stream description: "+n);let i=null,r,a=0;for(let d of e)switch(d.charAt(0)){case va:i=Dn(d.slice(1));break;case Ea:r=d.slice(1);break;case Xt:a=Number.parseInt(d.slice(1),10);break;default:throw new Error("Unexpected parameter type "+d.charAt(0)+" in stream description "+n)}return{participantId:v.compose(t,a),mediaType:i,streamName:r}}function Dn(n){for(let e of Object.keys(Me))if(e===n)return Me[e];return null}function ar(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 mi(n,e){return!(!ar(n.camera,e.camera)||!ar(n.screenSharing,e.screenSharing))}function nr(n,e){return{camera:Object.assign({},n.camera,e.camera),screenSharing:Object.assign({},n.screenSharing,e.screenSharing)}}function Ia(n){try{return btoa(JSON.stringify(n))}catch(e){c.warn("WaitingParticipant: failed convert to string",n,e)}return null}function Ta(n){try{return JSON.parse(atob(n))}catch(e){c.warn("WaitingParticipant: failed convert from string",n,e)}return null}var Pt=(n,e)=>v.objectReduce(n,(t,i,r)=>(i===e&&t.push(r),t),[]);var jt=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,_.log(T.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,_.log(T.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"),_.log(T.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),_.log(T.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===me.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var hi=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(l.muteMode||!((s=this._output)==null?void 0:s.audioTrack))return;let e=P.browserName()!=="Safari"||P.isMobile(),t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{c.warn("Error on play audio"),g.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=P.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw _.log(T.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var kn=90,On=3,_i=class extends ae{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),g.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>kn?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=On)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var wn=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=P.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=wn/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 gi=class extends ae{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&g.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,l.voiceParams.interval)};this._interval=window.setTimeout(t,l.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,ke.SOURCE_CHANGED,r=>{r.kind===me.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new 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 Ca="videochat-epi",xn=5e3,Ln=3e4,ct=class extends ae{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,H.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Ca)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return o(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&l.perfStatReportEnabled&&this._previousTimestamp+xn<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),l.callStatReportEnabled&&this._previousCallStatReportTimestamp+Ln<=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(Ca,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,a)=>(a.kind==="video"?(a.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+a.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+a.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=a.framesDropped,r.nack_sent+=a.nackCount,r.pli_sent+=a.pliCount,r.fir_sent+=a.firCount):(a.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+a.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+a.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=a.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=a.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=a.removedSamplesForAcceleration,r.concealed_audio_samples+=a.concealedSamples,r.silent_concealed_audio_samples+=a.silentConcealedSamples,r.audio_concealment_events+=a.concealmentEvents),r),t),e.outbound.rtps.reduce((r,a)=>(a.kind==="video"&&(r.nack_received+=a.nackCount,r.pli_received+=a.pliCount,r.fir_received+=a.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,a=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,d=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,p=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,u=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=a/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=d/r*1e3,i.concealed_silent_audio_samples=p/r*1e3,i.concealment_audio_avg_size=d/u,i.total_audio_energy=t.total_audio_energy}_.logCustom("callStat",i),c.log("Sent call stats",i),this._previousCallStatReport=t}};var Nn=1e3;function he(n,e,t=0){return e in n&&n[e]?n[e]:t}function ya(...n){return e=>{for(let t of n)if(t(e))return!0;return!1}}function tt(n,e){return t=>t[n]===e}function Un(n){return(e,t)=>e[n]-t[n]}function fi(n,e){return e.reduce((t,i)=>(t[i[n]]=i,t),{})}function Bn(n){let e={},t=[];for(let i of n)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Vn(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function sr(n){return Object.keys(n).filter(e=>n[e]!==void 0).map(e=>[e,n[e]]).reduce((e,t)=>(e[t[0]]=Vn(t[1])?sr(t[1]):t[1],e),{})}function Fn(n){let e=[];for(let t of n)t.forEach(i=>e.push(i));return e}function Hn(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(Fn).then(Bn)})}function Gn(n){let e=n.filter(tt("type","candidate-pair")).sort(Un("priority")).find(ya(tt("nominated",!0),tt("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(tt("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(tt("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}})),sr(t)}function Wn(n,e){let t=fi("id",n),i=n.filter(ya(tt("type","inbound-rtp"),tt("type","outbound-rtp")));P.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(P.browserName()==="Safari"){let a=n.filter(tt("type","track"));r=fi("trackIdentifier",a)}return i.map(a=>{let s=Number(a.ssrc),d=a.mediaType||a.kind,p=a.trackId,u=a.type,E=a.codecId;if(P.browserName()==="Safari"){let R=/^.+_([\d]+)$/.exec(a.id);if(R&&(s=parseInt(R[1],10)),d=a.id.indexOf("Audio")>0?"audio":"video",e[s]){let b=d+"-"+e[s];r[b]&&(p=r[b].id)}}if(!u||!s||!d)return null;let I={ssrc:s,type:u,kind:d,bytesReceived:he(a,"bytesReceived"),bytesSent:he(a,"bytesSent"),jitter:he(a,"jitter"),packetsLost:he(a,"packetsLost"),packetsReceived:he(a,"packetsReceived"),packetsSent:he(a,"packetsSent"),fractionLost:he(a,"fractionLost"),pliCount:he(a,"pliCount"),firCount:he(a,"firCount"),nackCount:he(a,"nackCount"),userId:e[s]};if(d==="video"){let R=he(a,"framesDecoded"),b=he(a,"totalInterFrameDelay"),V=he(a,"totalSquaredInterFrameDelay");I.interframeDelayVariance=(V-b*b/R)/R}if(d==="audio"&&(I.totalSamplesReceived=he(a,"totalSamplesReceived"),I.concealedSamples=he(a,"concealedSamples"),I.insertedSamplesForDeceleration=he(a,"insertedSamplesForDeceleration"),I.removedSamplesForAcceleration=he(a,"removedSamplesForAcceleration"),I.silentConcealedSamples=he(a,"silentConcealedSamples"),I.concealmentEvents=he(a,"concealmentEvents"),I.totalAudioEnergy=he(a,"totalAudioEnergy")),E&&t[E]){let R=t[E];I.clockRate=R.clockRate,I.mimeType=R.mimeType}if(p&&t[p]){let R=t[p];I.frameHeight=R.frameHeight,I.frameWidth=R.frameWidth,I.framesDecoded=R.framesDecoded,I.framesReceived=R.framesReceived,I.framesDropped=R.framesDropped}return sr(I)}).filter(a=>!!a)}function jn(n,e){if(!e||!e.rtps||!n.rtps)return n;let t=fi("ssrc",n.rtps),i=fi("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 $t(i,r){return o(this,arguments,function*(n,e,t={}){let a=yield Hn(n),s={timestamp:Date.now(),transport:Gn(a),rtps:Wn(a,t)};return e?jn(s,e):(yield v.delay(Nn),$t(n,s,t))})}var Si=.8,dt=class extends ae{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._perfStatReporter=new ct(this,i,!0),this.subscribe(this._signaling,ye.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ke.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ke.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,!1,!0,l.p2pAudioRed),this._applySettings()}catch(s){_.log(T.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,!1,!0,l.p2pAudioRed),this._applySettings()}catch(i){_.log(T.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={}})}updateSettings(e){mi(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(H.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(H.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(H.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,a;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=((a=e.data.sdk)==null?void 0:a.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=v.getPeerIdString(e.peerId);v.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){c.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw _.log(T.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 _.log(T.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(H.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(H.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}),_.log(T.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(F.CONNECTED),this._stopReconnection(),v.getPeerConnectionHostInfo(this._pc).then(e=>{e&&_.log(T.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(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(de.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(_.log(T.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}),_.log(T.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}),_.log(T.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=dt._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}),_.log(T.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}),_.log(T.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=dt._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}),_.log(T.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!P.baseChromeVersion();return e.sdp=v.patchSDP(e.sdp,l.preferH264&&P.canPreferH264(),P.isBrokenH264(),l.preferVP9,l.h264spsPpsIdrInKeyframe,t&&l.audioNack,l.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&t.track.contentHint===e.contentHint&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{c.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),_.log(T.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}$t(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:de.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:de.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(H.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=$=>$.rtt<=this._networkLimits.goodNet.rtt&&$.loss<=this._networkLimits.goodNet.loss,i=$=>$.rtt>=this._networkLimits.badNet.rtt||$.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,a=e.inbound.rtps.reduce(($,Ae)=>Math.max($,Ae.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-Si)+r*Si,loss:this._lastNetworkStat.loss*(1-Si)+a*Si},d=i(s),p=t(s),u=i(this._remoteNetworkStat),E=t(this._remoteNetworkStat),I=i(this._lastNetworkStat),R=t(this._lastNetworkStat),Z=d||u?.2:p&&E?1:0,_e=Date.now();if((I!==d||R!==p||_e-this._lastNetworkStat.date>l.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch($=>{c.warn("Unable to send [bad-net]",$)})),Z){let $={};$[this._participantId]=$[""]=Z,this._triggerEvent(H.NETWORK_STATUS,$)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=v.sdpFingerprint(e);if(t===null){c.warn("Fingerprint calculation is unsupported");return}this._fingerprint===null?this._fingerprint=t:(g.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=v.applySettings(this._pc,e,this._prevConsumerSettings))}};var Ra=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Ra||{}),qt=Ra;import{decode as pt}from"messagepack";var or=class{constructor(){this.streamDescriptionByCompactId=new Map;this.compactIdByStreamDescription=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}getCompactId(e){return this.compactIdByStreamDescription.get(e)}handleMessage(e){var a,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let d=pt(r);return Object.entries(d).forEach(([V,Z])=>{let _e=Wt(V);this.streamDescriptionByCompactId.set(Z,_e),this.compactIdByStreamDescription.set(V,Z)}),null;case 2:case 4:let p=pt(r),u=[];for(let V of p){let Z=this.getStreamDescription(V);Z&&u.push(Z.participantId)}return i===2?{type:"notification",notification:O.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:O.STALLED_ACTIVITY,stalledParticipants:u};case 3:let E=pt(r);return{type:"notification",notification:O.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(E))==null?void 0:a.participantId};case 5:let I=pt(r);return{type:"notification",notification:O.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:I[0],maxDimension:I[1]}};case 6:let R=pt(r),b={};for(let[V,Z]of Object.entries(R)){let _e=(s=this.getStreamDescription(Number(V)))==null?void 0:s.participantId;_e&&(b[_e]=Z/100)}return{type:"notification",notification:O.NETWORK_STATUS,statuses:b};case 7:return this._createParticipantSourcesUpdateNotification(r);case 8:{let Z=pt(r).map(_e=>{var Mt;let[$,Ae,ne,Re,De,it]=_e;return{participantId:(Mt=this.getStreamDescription($))==null?void 0:Mt.participantId,gain:Ae,pause:ne,offset:Re,mute:De,liveStatus:it}});return{type:"notification",notification:O.MOVIE_UPDATE_NOTIFICATION,data:Z}}default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=pt(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 E=He.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,I=d?d>>>0:null;i.push({participantStreamDescription:u,streamId:E,rtpTimestamp:I,sequenceNumber:p})}return{type:"notification",notification:O.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Kn=90,$n=4294967295,we=class extends ae{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=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._newAudioShareTrack=null;this._signaling=e,this._mediaSource=t,this._newAudioShareTrack=t.getAudioShareTrack(),this.subscribe(this._signaling,ye.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ke.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ke.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,ke.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new ct(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(e=!1){if(this._isOpen){c.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(c.error("ServerTransport: Closed",e),this._setState(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){mi(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,we._closeDataChannel(this._producerNotification),we._closeDataChannel(this._producerCommand),we._closeDataChannel(this._producerScreen),we._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(H.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let a=r.readyState;a==="open"?(c.debug(`[${t}] data channel opened`),r.onerror=s=>{c.error(`[${t}] data channel error`,s)},i(r)):c.error(`[${t}] data channel open failed, state [${a}]`)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection");let t={};P.baseChromeVersion()&&(t.sdpSemantics=we._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=v.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=we._onSignalingStateChange.bind(this,this._pc),l.producerNotificationDataChannel&&this._createDataChannel(this._pc,qt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new or,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),l.producerCommandDataChannel&&(this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,qt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)})),l.producerScreenDataChannel&&this._createDataChannel(this._pc,qt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,l.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){c.error("ServerTransport: Unable to add media source tracks",i),_.log(T.ERROR,"addTrack-single"),this.close(i);return}l.consumerScreenDataChannel&&this._createDataChannel(this._pc,qt.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(H.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(H.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(H.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(H.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
+ `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${He.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 yt(e,this._consumerScreen,this._signaling))}_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(H.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(H.REMOTE_STREAM_SECOND,e,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!==me.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(P.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)})}v.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(H.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 $t(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(H.REMOTE_DATA_STATS,{inbound:{topology:de.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:de.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=He.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(H.REMOTE_ALL_STALL,a)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:a}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:ct.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:l.producerNotificationDataChannel?7:0,producerCommandDataChannelVersion:l.producerCommandDataChannel?3:0,consumerScreenDataChannelVersion:l.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:l.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:we._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:l.videoTracksCount,red:l.serverAudioRed,audioShare:l.audioShareCapabilityEnabled};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),_.log(T.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.handleTracks(),this._pc.createAnswer()})).catch(i=>{throw c.error("[single] unable to create answer",i),_.log(T.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=v.patchSDP(i.sdp,!1,P.isBrokenH264(),!1,l.h264spsPpsIdrInKeyframe),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),_.log(T.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),_.log(T.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))})}handleTracks(){this._newAudioShareTrack&&(this._pc.getTransceivers().forEach(e=>{e.mid.endsWith("s")&&(e.sender.track!==null&&c.warn("Unexpected track assigned to audioshare"),e.direction="sendonly",e.sender.replaceTrack(this._newAudioShareTrack).catch(t=>{c.error("ServerTransport: Unable to replace track",t),_.log(T.ERROR,"replaceTrack-single")}),this._newAudioShareTrack=null)}),this._newAudioShareTrack&&c.warn("Cannot find audioshare transceiver"))}_onSignalingNotification(e){return o(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 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",null)),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){c.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=a=>{this._triggerEvent(H.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(H.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),_.log(T.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===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),v.getPeerConnectionHostInfo(e).then(r=>{r&&_.log(T.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){if(this._pc){l.consumerScreenDataChannel&&t&&(e=t);let i=!1;this._pc.getSenders().forEach(r=>{r.track&&r.track.kind===e.kind&&!this._disabledSenders.has(r)&&r.track.contentHint===e.contentHint&&(r.track.enabled=e.enabled,r.replaceTrack(e).catch(a=>{c.error("ServerTransport: Unable to replace track",a),_.log(T.ERROR,"replaceTrack-single")}),i=!0)}),!i&&e.kind===me.audio&&e.contentHint==="music"&&(this._newAudioShareTrack=e)}this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=P.baseChromeVersion();return e?l.isUnifiedPlanSupported("Chrome",e):l.isUnifiedPlanSupported(P.browserName(),Number(P.browserVersion()))}getStreamWaitingTimeMs(e,t){if(!this._pc)return _.log(T.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 _.log(T.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 _.log(T.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&$n,p=Math.ceil(d/Kn);return Math.min(100,Math.max(0,p))}};var H=(b=>(b.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",b.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",b.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",b.REMOTE_ALL_STALL="REMOTE_ALL_STALL",b.REMOTE_DATA_STATS="REMOTE_DATA_STATS",b.STATE_CHANGED="STATE_CHANGED",b.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",b.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",b.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",b.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",b.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",b.NETWORK_STATUS="NETWORK_STATUS",b.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",b))(H||{}),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||{}),de=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(de||{}),cr=class extends ae{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,ye.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){c.log("Update transport settings",e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(c.warn(`Trying allocate participant [${e}]`),this._allocated.indexOf(e)!==-1){c.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,i=!1,r=!1){c.warn(`Trying open participant [${JSON.stringify(e)}]`);let a=r;for(let s of e){if(this._opened.indexOf(s)!==-1){c.warn(`The participant [${s}] has already had opened transport`);continue}if(this._allocated.indexOf(s)===-1){c.warn(`The participant [${s}] has no allocated transport`);continue}this._opened.push(s),a=!0}!a||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),c.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&c.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}getState(){var e,t;return this._topology==="SERVER"?(e=this._serverTransport)==null?void 0:e.getState():(t=this._directTransport)==null?void 0:t.getState()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===O.TOPOLOGY_CHANGED)return this._onTopologyChanged(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),_.log(T.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],a=e.offerToDeviceIdxs||[],s=i.length&&r.length?v.composeParticipantId(i[0],r[0],a[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){c.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&c.warn("Topology changed to DIRECT, but the allocated participants count more then one");let d=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let p=s===d;this._directTransport=this._createDirectTransport(d,p)}this._opened.indexOf(d)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_createDirectTransport(e,t=!1){let i=new dt(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._dtListeners&&this._dtListeners.length>0&&c.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new we(this._signaling,this._mediaSource,this._serverSettings);return this._stListeners&&this._stListeners.length>0&&c.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;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))}_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"?(_.log(T.PAT_WAITING_TIME_ERROR,"wrongTopology"),c.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(_.log(T.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var lt=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(lt||{}),dr=class extends ae{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,H.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,H.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,H.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,H.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===me.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===me.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===He.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e===de.DIRECT&&(this._activeParticipants=null)}};var pr=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(pr||{}),lr=class extends ae{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i===de.SERVER,this.subscribe(e,lt.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,H.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,H.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let a=e[r].smoothed;a>t&&a>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._serverSideSpeakerDetection&&this._triggerEvent("SPEAKER_CHANGED",e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e===de.SERVER}};var vi=class extends ae{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,H.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,lt.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"),_.log(T.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==F.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(c.warn("There is not connected transport, send callSpecError"),_.log(T.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),_.log(T.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&c.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var qn=1e3,Jn=1e4;var zn=15,W=class extends ae{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._myLastRequestedLayouts={};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;_.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),_.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new hi,l.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),qn))}static current(){return W._current}static hangupAfterInit(){W._activationMutex&&!W._current&&(W._delayedHangup=!0)}static id(){var e,t;return((t=(e=W._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",a=!1,s=!1,d){return o(this,null,function*(){if(W._activationMutex)throw _.log(T.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new B(k.FAILED);W._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let p=this._mediaSource.getMediaSettings();t===ze.CHAT||e.length>1?this._logWithMediaSettings(T.OUTGOING_MULTIPARTY_CALL,p):this._logWithMediaSettings(T.OUTGOING_CALL,p);let u=yield this._startConversation(e,t,Ze.OUTGOING,i,r,a,s,d);if(!this._conversation)throw new B(k.UNKNOWN_ERROR);if(this._participantState=j.ACCEPTED,this._signaling.changeMediaSettings(p),yield this._processConnection(u),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),W._delayedHangup)throw new B(k.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let E=Object.values(this._participants),I;return l.batchParticipantsOnStart&&(I=v.mapSharedParticipants(E)),yield this._processConnectionSharedMovieInfo(u),g.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,I),this._onConversationParticipantListChunk(u),g.onLocalStatus(Q.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),W._current=this,this._conversation.concurrent?yield this._acceptConcurrent():l.batchParticipantsOnStart||this._setParticipantsStatus(E,Q.WAITING),this._conversation}catch(p){throw this._close(p,"Unable to start conversation"),p}finally{W._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){var t;if(W._activationMutex)throw _.log(T.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new B(k.FAILED);W._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.JOIN_CONVERSATION,r);let a=yield this._joinConversation(e);if(!this._conversation)throw new B(k.UNKNOWN_ERROR);return this._conversation.observer=i,g.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(c.log("In waiting hall"),W._current=this,W._activationMutex=!1,this._signaling.readyToSend(),g.onLocalStatus(Q.WAITING_HALL),this._conversation):this._onJoinPart2(a)}catch(i){throw W._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return o(this,null,function*(){var t,i,r,a,s,d;c.debug("Join conversation part 2"),W._activationMutex=!0;try{if(this._participantState=j.ACCEPTED,!this._conversation||!this._mediaSource)throw new B(k.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._processConnection(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),W._delayedHangup)throw new B(k.CANCELED);let p=Object.values(this._participants),u;l.batchParticipantsOnStart&&(u=v.mapSharedParticipants(p.filter(R=>!R.isInRoom)));let E=[];if((i=(t=e==null?void 0:e.rooms)==null?void 0:t.rooms)==null?void 0:i.length)for(let R of e.rooms.rooms)E.push({id:R.id,name:R.name,participantCount:R.participantCount,participantIds:yield Promise.all(((a=(r=R==null?void 0:R.participantIds)==null?void 0:r.map)==null?void 0:a.call(r,this._getExternalIdByParticipantId.bind(this)))||[]),participants:((s=R==null?void 0:R.participants)==null?void 0:s.participants)?this._participantListChunkToExternalChunk(R.participants):void 0,active:R.active});let I=(d=e==null?void 0:e.rooms)==null?void 0:d.roomId;return yield this._processConnectionSharedMovieInfo(e),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,u,{rooms:E,roomId:I}),this._onConversationParticipantListChunk(e),g.onLocalStatus(Q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),W._current=this,l.batchParticipantsOnStart||this._setParticipantsStatus(p,Q.WAITING),this._openTransport(p,!1),this._conversation}catch(p){throw this._close(p,"Unable to join conversation"),p}finally{W._activationMutex=!1}})}onPush(r){return o(this,arguments,function*(e,t=te.USER,i){if(W._activationMutex)throw c.warn("Conversation: there is already running activation"),new B(k.REJECTED);W._activationMutex=!0;try{let a=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new B(k.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)"),_.log(T.PUSH,"rejected"),new B(k.REJECTED);if(yield this._processConnection(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),_.log(T.PUSH,"accepted"),W._current=this,W._delayedHangup)throw new B(k.CANCELED);W._activationMutex=!1}catch(a){throw W._activationMutex=!1,this._close(a,"Unable to handle inbound call push"),a}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Di.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>v.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return o(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new B(k.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.ACCEPT_CONCURRENT,e),c.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),g.onCallAccepted(),this._state="ACTIVE",this._participantState=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*(){var t;if(this._state!=="IDLE")throw _.log(T.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 B(k.UNKNOWN_ERROR);this._state="PROCESSING",c.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let i=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.ACCEPT_INCOMING,i),this._signaling.changeMediaSettings(i),yield this._signaling.acceptCall(i),this._participantState=j.ACCEPTED;let r=Object.values(this._participants),a;if(l.batchParticipantsOnStart&&(a=v.mapSharedParticipants(r)),g.onCallAccepted(),g.onLocalStream(this._mediaSource.getStream(),i),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,a),l.useParticipantListChunk){let p=yield this._getInitialParticiapntListChunk();(t=p==null?void 0:p.participants)==null||t.forEach(u=>{let E=v.composeId(u),I=this._participants[E];I&&(I.movieShareInfos=u.movieShareInfos)}),this._onConversationParticipantListChunk({participants:p})}g.onLocalStatus(Q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let s=Pt(this._conversation.muteStates,Fe.MUTE),d=Pt(this._conversation.muteStates,Fe.MUTE_PERMANENT);for(let p of[s,d])p.length&&(yield this._processMuteState({mediaOptions:p,stateUpdated:!0}));return this._state="ACTIVE",this._changeFeatureSet(),l.batchParticipantsOnStart||this._setParticipantsStatus(r,Q.WAITING),this._openTransport(r,!0),this._conversation}catch(i){throw this._close(i,"Unable to accept call"),i}})}decline(){return o(this,null,function*(){var e;if(this._state!=="IDLE")throw _.log(T.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(T.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=j.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(k.REJECTED)),this._close(new B(k.REJECTED))})}hangup(){return o(this,null,function*(){c.debug("Hangup");let e=this._state==="ACTIVE"?k.HUNGUP:k.CANCELED;_.log(T.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new B(e))):g.onHangup(new B(k.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new B(k.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=k.UNKNOWN_ERROR);let a=i.participant;yield this._onAddParticipant(v.composeId(a),a,r)})}removeParticipant(e,t=!1){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let a of e)(a.state===j.CALLED||a.state===j.ACCEPTED)&&(this._transport.isAllocated(a.id)||this._transport.allocate(a.id,t)),a.state===j.ACCEPTED&&i.push(a.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&c.error(t,e),c.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(k.FAILED):_.log(T.ERROR,e.hangup),W._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([k.CANCELED,k.NOT_FRIENDS,k.CALLEE_IS_OFFLINE,k.CALLER_IS_BLOCKED,k.CALLER_IS_REJECTED].indexOf(e.hangup)!==-1||e.hangup===k.REJECTED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===k.HUNGUP&&(!e.remote||this._participantState===j.CALLED)){g.onHangup(e,i),this.destroy();return}if(e.hangup===k.MISSED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===k.SOCKET_CLOSED&&W._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===k.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(),_.destroy(),this._conversation=null,this._myLastRequestedLayouts={},W._current=null,W._delayedHangup=!1,g.onHangup(e||new B(k.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(),_.destroy(),this._conversation=null,this._myLastRequestedLayouts={},W._current=null,W._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return o(this,null,function*(){let t=yield this._api.getConversationParams(e);c.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:a}=t;if(a&&i.push(a),r){let s=r.urls.filter((d,p,u)=>u.indexOf(d)===p);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return l.iceServers=i,l.wssBase=t.endpoint,l.wssToken=t.token,t.client_type&&(l.clientType=t.client_type),l.externalUserType=t.external_user_type,t})}_addGeoParamsToEndpoint(e,t){return t.isp_as_no&&(e+=`&ispAsNo=${t.isp_as_no}`),t.isp_as_org&&(e+=`&ispAsOrg=${t.isp_as_org}`),t.loc_cc&&(e+=`&locCc=${t.loc_cc}`),t.loc_reg&&(e+=`&locReg=${t.loc_reg}`),e}_startConversation(e,t,i,r,a="",s=!1,d=!1,p){return o(this,null,function*(){let u=v.uuid();c.debug("Conversation: start",{conversationId:u,opponentIds:e,opponentType:t,direction:i});let E=r.includes(ue.VIDEO),I=yield this._api.startConversation(u,e,t,E,a,s,d,{onlyAdminCanShareMovie:p});c.debug("Api.startConversation",I);let R=yield this._getConversationParams(I.id);I.endpoint=this._addGeoParamsToEndpoint(I.endpoint,R);let b=yield this._connectSignaling(Ye.START,I);return yield this._setConversation(I,b,i),b})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:a,observedIds:s,payload:d}=e;c.debug("Conversation: join",{conversationId:t,joinLink:a,observedIds:s});let p=i.includes(ue.VIDEO),u;if(t)u=yield this._api.joinConversation(t,p,r);else if(a)u=yield this._api.joinConversationByLink(a,p,s,d);else throw new B(k.UNKNOWN_ERROR);c.debug("Api.joinConversation",u),yield this._getConversationParams(u.id);let E=yield this._connectSignaling(Ye.JOIN,u);return yield this._setConversation(u,E,Ze.JOINING),E})}_prepareConversation(r){return o(this,arguments,function*(e,t=te.USER,i){c.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let a=this._api.getUserId();if(!a)throw new B(k.UNKNOWN_ERROR);let s=yield this._getConversationParams(e),d=s.device_idx||0,p=`${l.wssBase}?userId=${a}&entityType=${t}&deviceIdx=${d}&conversationId=${e}&token=${l.wssToken}`;p=this._addGeoParamsToEndpoint(p,s);let u={id:e,peerId:i,endpoint:p,is_concurrent:!1,p2p_forbidden:!1,device_idx:d},E=yield this._connectSignaling(Ye.ACCEPT,u);return W._current&&(W._current._participantState===j.ACCEPTED||W._current._participantState===j.CALLED)?(c.log("Push rejected (busy)"),_.log(T.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(k.BUSY),Promise.reject({hangup:k.BUSY})):(W._current&&(W._current.destroy(),W._current=null),yield this._setConversation(u,E,Ze.INCOMING,t),E)})}_createParticipant(e){return o(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:Se(),participantState:{},state:j.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[],isInRoom:!1},e);if(e.externalId){let r=v.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(r,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return((i=t.observedIds)==null?void 0:i.length)&&(t.externalId.observer=!0),this._setParticipantMarkers(t,t.markers),t})}_getParticipantId(e){return o(this,null,function*(){try{let t=v.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new B(k.NETWORK_ERROR),t),t}})}_setConversation(a,s,d){return o(this,arguments,function*(e,t,i,r=te.USER){yield this._prepareParticipants(t.conversation.participants);let p=this._api.getUserId(),u=e.device_idx||0;if(!p){let R=(t.conversation.participants||[]).find(b=>v.comparePeerId(b.peerId,t.peerId));if(!R)throw new B(k.UNKNOWN_ERROR);p=Number(R.id),R.idType&&(r=R.idType),R.deviceIdx&&(u=R.deviceIdx),this._api.setUserId(p)}let E=v.composeParticipantId(p,r,u),I=yield this._getParticipantId(E);this._conversation={userId:p,compositeUserId:E,externalId:I,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],featuresPerRole:t.conversation.featuresPerRole,id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||de.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1,asrInfo:null},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(l.forceRelayPolicy=e.p2p_forbidden),_.log(T.RELAY_POLICY,l.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new B(k.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.featuresPerRole=e.conversation.featuresPerRole,this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||de.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 Hi;return this.subscribe(e,ke.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,ke.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new jt(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,ye.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,ye.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,ye.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_processConnection(e){return o(this,null,function*(){yield this._registerConnectionParticipants(e),this._processConnectionData(e)})}_prepareParticipants(e){return o(this,null,function*(){let t=e.map(i=>i.id);t.length&&(yield this._api.prepareUserIds(t))})}_onConversationParticipantListChunk(e){let t=e.participants;t&&g.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(this._createParticipantListChunk(t)))}_createParticipantListChunk(e){return Ve(Ve({},{participants:[],countBefore:0,countAfter:0,markerFound:!1}),e)}_participantListChunkToExternalChunk(e){let t=v.mapSharedParticipants(e.participants.map(i=>{let r=v.composeId(i);return this._participants[r]}));return ht(Ve({},e),{participants:t})}_registerConnectionParticipants(e){return o(this,null,function*(){var i,r,a,s,d,p;yield this._registerParticipants(e.conversation.participants),((i=e.participants)==null?void 0:i.participants)&&(yield this._registerParticipants((r=e.participants)==null?void 0:r.participants));let t=(s=(a=e==null?void 0:e.rooms)==null?void 0:a.rooms)!=null?s:[];for(let u of t)yield this._registerParticipants((p=(d=u==null?void 0:u.participants)==null?void 0:d.participants)!=null?p:[],!0)})}_registerParticipants(e,t=!1){return o(this,null,function*(){if(!!this._conversation)for(let i of e){let r=v.composeId(i);if(this._isMe(r)){this._conversation.roles=i.roles||[],this._conversation.roles.length&&(c.debug(`Local roles changed: ${i.roles}`),g.onLocalRolesChanged(this._conversation.roles)),yield this._registerParticipantLocalMuteState(i);continue}if(i.state===j.HUNGUP||i.state===j.REJECTED){this._participants[i.id]&&this._removeParticipant(this._participants[i.id],k.HUNGUP);continue}this._registerParticipantInCache(yield this._createParticipant({id:r,externalId:i.externalId&&ve.fromSignaling(i.externalId,i.deviceIdx||0),mediaSettings:Se(i.mediaSettings),participantState:v.mapParticipantState(i),state:i.state,roles:i.roles||[],status:l.batchParticipantsOnStart?Q.WAITING:null,muteStates:i.muteStates||{},unmuteOptions:i.unmuteOptions||[],observedIds:i.observedIds||[],markers:this._denormalizeMarkers(r,i.markers),movieShareInfos:i.movieShareInfos,isInRoom:t})),i.roles&&i.roles.length&&(c.debug(`Roles for participant [${r}] changed: ${i.roles}`),g.onRolesChanged(this._participants[r].externalId,i.roles))}})}_registerParticipantLocalMuteState(e){return o(this,null,function*(){if(!e.muteStates)return Promise.resolve();let t=Pt(e.muteStates,Fe.MUTE),i=Pt(e.muteStates,Fe.MUTE_PERMANENT);for(let r of[t,i])!r.length||(yield this._onMuteParticipant({muteStates:e.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:r,stateUpdated:!0}))})}_getStatusByTransportState(e){let t;return e===F.CONNECTED?t=Q.CONNECTED:e===F.CONNECTING||e===F.OPENED?t=Q.CONNECTING:e===F.RECONNECTING&&(t=Q.RECONNECT),t}_registerParticipantInCache(e){return this._participants[e.id]=e}_getExistedParticipantByIdOrCreate(e){return o(this,null,function*(){return this._participants[e]||this._createParticipant({id:e})})}_getExternalIdByParticipantId(e){return o(this,null,function*(){var t;if(this._isMe(e))return this._conversation.externalId;if(l.useParticipantListChunk)return(yield this._getExistedParticipantByIdOrCreate(e)).externalId;if((t=this._participants[e])==null?void 0:t.externalId)return this._participants[e].externalId;{let i=yield this._getParticipantId(e);return this._api.cacheExternalId(e,i),i}})}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){return o(this,null,function*(){if(l.useParticipantListChunk){let i=this._registerParticipantInCache(yield this._getExistedParticipantByIdOrCreate(e));return this._setParticipantMarkers(i,t),i}return this._participants[e]})}_warnParticipantNotInConversation(e){c.warn(`Participant [${e}] isn't in conversation`)}_setParticipantMarkers(e,t){return e.markers=this._denormalizeMarkers(e.id,t),e}_denormalizeMarkers(e,t){if(!t)return null;let i=Object.values(t).find(r=>"ts"in r&&"rank"in r);return Object.entries(t).reduce((r,[a,s])=>(r[a]=ht(Ve(Ve({},i),s),{id:e}),r),{})}_processConnectionData(e){return o(this,null,function*(){v.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0,stateUpdated:!0}),e.conversation.pinnedParticipantId&&(yield this._onPinParticipant(e.conversation.pinnedParticipantId)),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Mi.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)})}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new cr(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new _i,this.subscribe(this._transport,H.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,H.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,H.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,H.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,H.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,H.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,H.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,H.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,H.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,H.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,H.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Ze.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 dr(this._transport),this.subscribe(this._volumesDetector,lt.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new lr(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,pr.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new gi(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new vi(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=P.getCameras().length,t=P.getMicrophones().length;c.debug("Cameras: "+e+(P.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(P.hasMicrophonePermission()?"✔":"✖")),_.log(T.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){_.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===j.CALLED||e.state===j.ACCEPTED||this._state==="CLOSE"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),!!this._participants[e.id]&&(t===k.HUNGUP?this._setParticipantsStatus([e],Q.HANGUP):this._setParticipantsStatus([e],Q.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Me.CAMERA,stopStream:!0}]),delete this._participants[e.id],g.onRemoteRemoved(e.externalId,e.markers)))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(a=>a.stop()),(i=e.secondStream)==null||i.getTracks().forEach(a=>a.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){c.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return o(this,null,function*(){c.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===j.ACCEPTED||r.state===j.CALLED)){c.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(r=this._registerParticipantInCache(yield this._createParticipant({id:e,externalId:t.externalId&&ve.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:Se(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}))),this._setParticipantsStatus([r],Q.WAITING),i?(r.state=j.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=j.CALLED,this._transport.allocate(r.id,!0),_.log(T.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){c.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=zn;i++){let r=v.compose(e,i),a=this._participants[r];a&&t.push(a)}if(!t.length){this._warnParticipantNotInConversation(e);return}if(this._transport)for(let i of t)this._transport.close(i.id);_.log(T.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new jt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ce.UNKNOWN)})}toggleScreenCapturing(e,t){return o(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e,t):Promise.reject(ce.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 _.log(T.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return _.log(T.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:ve.fromId(r.uid),s=ve.toString(a);i[s]=r.priority}for(let r of Object.values(this._participants)){let a=ve.toString(r.externalId);i.hasOwnProperty(a)&&(t[r.id]=i[a])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return o(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return o(this,null,function*(){let t={};return t[$e(e)]={keyFrameRequested:!0},this._signaling.updateDisplayLayout(t)})}requestTestMode(e,t){return o(this,null,function*(){return this._signaling.requestTestMode(e,t)})}updateDisplayLayout(e){return o(this,null,function*(){if(e.length<1||!this._signaling.ready)return;c.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let a=typeof r.uid=="object"?r.uid:ve.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(a);if(!s){let E=ve.toString(a);c.log(`Unknown participant external ID ${E}`);continue}let d=v.compose(s,a.deviceIdx),p=$e({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),u=this._participants[d];u?u.lastRequestedLayouts[p]=r:this._isMe(d)&&(this._myLastRequestedLayouts[p]=r),Gt(r)?(this._isMe(d)&&delete this._myLastRequestedLayouts[p],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]=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]={stopStream:!0}}yield this._sendUpdateDisplayLayout(t)})}feedback(e){return this._signaling.feedback(e)}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(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],{externalId:a}=this._conversation,s=this._isMe(i.participantId);if(r){if(i.streamName&&(i.mediaType===Me.STREAM||i.mediaType===Me.MOVIE)){let d={stream:null,streamName:i.streamName,mediaType:i.mediaType};s?g.onLocalLive(a,d):g.onRemoteLive(r.externalId,d)}else s||g.onRemoteStream(r.externalId,null);_.log(T.PAT_DEALLOCATED)}else 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=Fr.UNKNOWN_ERROR):p=Hr(a),i.push({externalId:d.externalId,errorReason:p})}}if(i&&i.length)throw new Ei("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+Jn>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e)}_onParticipantSourcesUpdate(e){if(this._conversation){c.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){c.log("Promoted in waiting hall",!e.demote),e.demote?(c.log("Kicked from waiting hall"),this._close(new B(k.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=Te.fromSignaling(d.externalId);a.push(p),this._api.cacheExternalId(d.id.id,p)}else s.push(v.decomposeId(d.id.id).id)}),s.length&&!a.length&&(a=yield this._api.getExternalIdsByOkIds(s))),g.onChatRoomUpdated(e,t,a)})}_onSharedMovieUpdate(e){return o(this,null,function*(){let{externalId:t}=this._conversation,{data:i}=e;for(let r of i)if(this._isMe(r.participantId))g.onLocalLiveUpdate(t,r);else{let s=yield this._getExternalIdByParticipantId(r.participantId);s&&g.onRemoteLiveUpdate(s,r)}})}_onSharedMovieInfoStarted(e){return o(this,null,function*(){c.log(`Shared movie started data received: ${e.notification}`),yield this._processSharedMovieInfo(e.movieShareInfo)})}_processSharedMovieInfos(e){return o(this,null,function*(){e&&(yield Promise.all(e.map(t=>this._processSharedMovieInfo(t))))})}_processSharedMovieInfo(e){return o(this,null,function*(){var r;if(!e)return;let{externalId:t}=this._conversation;if(this._isMe(e.initiatorId))g.onLocalSharedMovieInfo(t,e);else{let a=yield this._getExternalIdByParticipantId(e.initiatorId);a&&g.onRemoteSharedMovieInfo(a,e)}this._transport.getTopology()===de.SERVER&&this._transport.getState()===F.IDLE&&this._participantState!==j.CALLED&&this._transport.open(this._transport.allocated(),null,!!((r=this._conversation)==null?void 0:r.observer),!0)})}_processConnectionSharedMovieInfo(e){return o(this,null,function*(){let t=e.conversation.participants.find(i=>this._isMe(v.composeId(i)));yield this._processSharedMovieInfos(t==null?void 0:t.movieShareInfos)})}_onSharedMovieInfoStopped(e){return o(this,null,function*(){c.log(`Shared movie stopped data received: ${e.notification}`);let{externalId:t}=this._conversation,{initiatorId:i,movieId:r,source:a}=e,s={initiatorId:i,movieId:r,source:a};if(this._isMe(i))g.onLocalSharedMovieStoppedInfo(t,s);else{let p=yield this._getExternalIdByParticipantId(i);p&&g.onRemoteSharedMovieStoppedInfo(p,s)}})}_onFeaturesPerRoleChanged(e){c.log(`Features per role changed: ${e.notification}`),g.onFeaturesPerRoleChanged(e.featuresPerRole)}_waitForStreamIfNeeded(e){var d,p;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||l.producerScreenDataChannel&&t.mediaType===Me.SCREEN)return;let i=$e(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}`),_.log(T.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,E=this._participants[u],{externalId:I}=this._conversation,R=this._isMe(u);if(!E&&!R){_.log(T.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${u}`);return}let b=R?I:E.externalId,V=this._streamByStreamId.get(a);if(!V){_.log(T.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}_.log(T.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,a);let Z=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(Z===Me.STREAM||Z===Me.MOVIE){if((p=e.participantStreamDescription)==null?void 0:p.streamName){let _e={streamName:e.participantStreamDescription.streamName,stream:V,mediaType:Z};R?g.onLocalLive(b,_e):g.onRemoteLive(b,_e)}}else if(l.producerScreenTrack&&Z===Me.SCREEN)g.onRemoteScreenStream(E.externalId,V);else if(!R){let _e=(l.producerScreenTrack?null:E.secondStream)||V;g.onRemoteStream(E.externalId,_e)}}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($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:Me.CAMERA};if(this._streamIdByStreamDescription.has($e(i)))return i;let r={participantId:t,mediaType:Me.SCREEN};if(this._streamIdByStreamDescription.has($e(r)))return r}return c.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?v.includesOneOf(this._conversation.roles,[_t.ADMIN,_t.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!v.includesOneOf(this._conversation.roles,[_t.ADMIN,_t.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)})}startAsr(){return o(this,null,function*(){yield this._signaling.startAsr()})}stopAsr(){return o(this,null,function*(){yield this._signaling.stopAsr()})}muteParticipant(){return o(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}enableFeatureForRoles(e,t){return o(this,null,function*(){yield this._signaling.enableFeatureForRoles(e,t)})}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=br(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=Ta(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(E=>{if(E.externalId){let I=Te.fromSignaling(E.externalId);d.push(I),this._api.cacheExternalId(E.id.id,I)}else p.push(v.decomposeId(E.id.id).id)}),p.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(p)),a.hasMore&&(u=Ia(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(r){return o(this,arguments,function*({movieId:e,gain:t,metadata:i}){let a={movieId:e};(t||t===0)&&(a.gain=t),i&&(a.metadata=i);let s=yield this._signaling.addMovie(a);if(s.error)throw new Error(s.error);return{movieId:s.movieId,streamType:s.streamType}})}updateMovie(e){return o(this,null,function*(){let t=yield this._signaling.updateMovie(e);if(t.error)throw new Error(t.error)})}removeMovie(e){return o(this,null,function*(){let t={movieId:e},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}updateRooms(e,t){return o(this,null,function*(){c.debug("Rooms: update",{rooms:e,assignRandomly:t});let i=yield this._signaling.updateRooms(e,t);if(i.error)throw new Error(i.error)})}activateRooms(e,t){return o(this,null,function*(){c.debug("Rooms: activate",{roomIds:e,deactivate:t});let i=yield this._signaling.activateRooms(e,t);if(i.error)throw new Error(i.error)})}switchRoom(e,t){return o(this,null,function*(){c.debug("Room: switch",{toRoomId:e,participantId:t});let i=yield this._signaling.switchRoom(e,t);if(i.error)throw new Error(i.error)})}removeRooms(e){return o(this,null,function*(){c.debug("Rooms: remove",{roomIds:e});let t=yield this._signaling.removeRooms(e);if(t.error)throw new Error(t.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",a=null,s=null){return o(this,null,function*(){let d={movieId:i,name:t,privacy:r,groupId:a,roomId:s,streamMovie:!e},p=yield this._signaling.startStream(d);return p.error?Promise.reject(p.message):p})}stopStream(e=null){return o(this,null,function*(){let t={roomId:e},i=yield this._signaling.stopStream(t);return i.error?Promise.reject():i})}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)})}getParticipants(e){return o(this,null,function*(){let t=e.externalIds.map(s=>({id:s.id,type:l.externalUserType})),i=yield this._signaling.getParticipants(t);if(i.error)throw new Error(i.error);let r=i.participants,a=this._transport.getState();return Promise.all(r.map(s=>o(this,null,function*(){var p;let d=v.composeId(s);return this._createParticipant({id:d,externalId:s.externalId&&ve.fromSignaling(s.externalId,s.deviceIdx||0),mediaSettings:Se(s.mediaSettings),participantState:v.mapParticipantState(s),state:s.state,roles:s.roles||[],status:(p=this._getStatusByTransportState(a))!=null?p:Q.WAITING,muteStates:s.muteStates||{},unmuteOptions:s.unmuteOptions||[],observedIds:s.observedIds||[],markers:this._denormalizeMarkers(d,s.markers)})}))).then(v.mapSharedParticipants)})}getParticipantListChunk(e){return o(this,null,function*(){var d;c.log("Request participant list chunk",e);let t=yield this._signaling.getParticipantListChunk(e);if(t.error)throw new Error(t.error);let i=this._createParticipantListChunk(t.chunk),r=i.participants.filter(p=>{let u=v.composeId(p);return!this._participants[u]});yield this._registerParticipants(r);let a=(d=this._transport)==null?void 0:d.getState();return i.participants.forEach(p=>{var I,R;let u=v.composeId(p),E=this._participants[u];E.status=(I=this._getStatusByTransportState(a))!=null?I:Q.WAITING,E.movieShareInfos=p.movieShareInfos,E.mediaSettings=Se(p.mediaSettings),E.muteStates=p.muteStates,E.unmuteOptions=p.unmuteOptions,this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(E.id)||this._transport.allocate(E.id,!0),this._transport.open([E.id],null,!!((R=this._conversation)==null?void 0:R.observer)))}),this._participantListChunkToExternalChunk(i)})}_getInitialParticiapntListChunk(){return o(this,null,function*(){let e=l.participantListChunkInitIndex,t=l.participantListChunkInitCount,i="GRID",r=yield this._signaling.getParticipantListChunk({listType:i,fromIdx:e,count:t});return c.debug("Get initial participant list chunk",r.chunk),r.chunk})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t,i;!this._conversation||(c.debug("Local media stream changed",e.mediaSettings),g.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return o(this,null,function*(){var t,i;if(c.log("Screen sharing changed",e.track,e.mediaSettings),l.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;g.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){c.debug(`Remote media settings changed [${e}]`,t);let{externalId:i}=this._conversation;if(this._isMe(e)){g.onLocalMediaSettings(i,t);return}let a=this._participants[e];if(!a){this._warnParticipantNotInConversation(e);return}a.mediaSettings=t,this._state==="ACTIVE"&&g.onRemoteMediaSettings(a.externalId,t,a.markers),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t)}_changeRemoteParticipantState(e,t){c.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];if(!i){this._warnParticipantNotInConversation(e);return}i.participantState=t||{},this._state==="ACTIVE"&&g.onRemoteParticipantState(i.externalId,i.participantState,i.markers)}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(c.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),g.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case 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,e.markers);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);case O.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e);case O.FEEDBACK:return this._onFeedback(e);case O.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e);case O.MOVIE_SHARE_STARTED:return this._onSharedMovieInfoStarted(e);case O.MOVIE_SHARE_STOPPED:return this._onSharedMovieInfoStopped(e);case O.ROOMS_UPDATED:return this._onRoomsUpdated(e);case O.ROOM_UPDATED:return this._onRoomUpdated(e);case O.ROOM_PARTICIPANTS_UPDATED:return this._onRoomParticipantsUpdated(e);case O.FEATURES_PER_ROLE_CHANGED:return this._onFeaturesPerRoleChanged(e);case O.ASR_STARTED:return this._onAsrInfo(e.asrInfo);case O.ASR_STOPPED:return this._onAsrInfo(null)}}_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._conversation.featuresPerRole=e.conversation.featuresPerRole,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?yield this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&(yield this._onPinParticipant(this._conversation.pinnedParticipantId,!0))),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let a of e.conversation.participants){let s=v.composeId(a),d=a.roles||[];if(this._isMe(s)){t=Se(a.mediaSettings),wt(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=Se(a.mediaSettings);Qr(u,p.mediaSettings)||this._changeRemoteMediaSettings(s,u);let E=v.mapParticipantState(a),I=p.participantState;v.isEqualParticipantState(E,I)||this._changeRemoteParticipantState(s,E),wt(d,p.roles)||this._onRolesChanged(p.id,d)}}for(let a of i)r.indexOf(a)<0&&this._removeParticipant(this._participants[a],k.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){c.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return o(this,null,function*(){let t=v.composeMessageId(e),i=v.getPeerIdString(e.peerId);if(c.debug(`Participant accepted call [${t}]`),this._conversation&&this._isMe(t)){this._close(new B(k.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(r=this._registerParticipantInCache(yield this._createParticipant({id:t,mediaSettings:Se(e.mediaSettings)}))),r.state=j.ACCEPTED,r.mediaSettings=Se(e.mediaSettings),this._logWithMediaSettings(T.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Ze.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){return o(this,null,function*(){c.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=v.composeMessageId(e);if(this._conversation&&this._isMe(t)){this._close(new B(e.reason,{remote:!0}));return}yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers);let i=this._participants[t];if(!i){this._warnParticipantNotInConversation(t);return}this._transport&&this._transport.close(t),i.state=e.reason===k.REJECTED?j.REJECTED:j.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,k.HUNGUP)})}_onAddedParticipant(e){return o(this,null,function*(){var r,a;c.debug(`Participant added [${e.participantId}]`);let t=v.composeMessageId(e),i=this._participants[t];if(i&&i.state!==j.HUNGUP&&i.state!==j.REJECTED){c.debug(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&ve.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:Se(e.participant.mediaSettings),state:e.participant.state,participantState:v.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}))),i.state=j.CALLED,i.mediaSettings=Se((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=v.mapParticipantState(e.participant),i.roles=((a=e.participant)==null?void 0:a.roles)||[],this._setParticipantsStatus([i],Q.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),g.onParticipantAdded(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return o(this,null,function*(){var r,a;c.debug(`Participant joined [${e.participantId}]`);let t=v.composeMessageId(e),i=this._participants[t];if(i&&i.state===j.ACCEPTED){c.warn(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&ve.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:Se(e.participant.mediaSettings),state:e.participant.state,participantState:v.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},movieShareInfos:e.participant.movieShareInfos,unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[],markers:this._denormalizeMarkers(t,e.participant.markers)}))),this._conversation&&this._conversation.direction===Ze.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=j.ACCEPTED,i.mediaSettings=Se(e.mediaSettings),i.participantState=v.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],Q.CONNECTED):this._setParticipantsStatus([i],Q.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((a=this._conversation)==null?void 0:a.observer))),g.onParticipantJoined(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i),g.onMuteStates(i.muteStates,i.unmuteOptions,Object.keys(i.muteStates),!1,!1,i.externalId,void 0,!0),yield this._processSharedMovieInfos(i.movieShareInfos)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new B(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){return o(this,null,function*(){let t=v.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,Se(e.mediaSettings))})}_onParticipantStateChanged(e){return o(this,null,function*(){let t=v.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteParticipantState(t,v.mapParticipantState(e))})}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._conversation.featuresPerRole=e.featuresPerRole,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),g.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=Se(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,i.isAudioSharingEnabled))})}_onSettingsUpdate(e){c.debug("Got settings update notification",e);let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=nr(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){c.debug("Got video quality update notification",e);let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=nr(this._serverSettings,r),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=v.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return o(this,null,function*(){g.onDeviceSwitched(ue.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return o(this,null,function*(){let t=v.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),g.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return o(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=v.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),g.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return o(this,null,function*(){var i;if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let r=yield this._getParticipantId(e.initiator);g.onRecordStarted(r,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else g.onRecordStopped();this._conversation.recordInfo=e,e&&this._transport.getTopology()===de.SERVER&&this._participantState!==j.CALLED&&this._transport.open(this._transport.allocated(),null,!!((i=this._conversation)==null?void 0:i.observer),!0)})}_onAsrInfo(e){return o(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.asrInfo!=!e?t=!0:this._conversation.asrInfo&&e&&(t=this._conversation.asrInfo.movieId!==e.movieId),t)if(e){let i=yield this._getParticipantId(e.initiatorId);g.onAsrStarted(i,e.movieId)}else g.onAsrStopped();this._conversation.asrInfo=e})}_onRolesChanged(e,t){if(this._conversation&&this._isMe(e)&&!wt(this._conversation.roles,t)){c.debug(`Local roles changed: ${t}`),this._conversation.roles=t,g.onLocalRolesChanged(t),this._processMuteState({mediaOptions:Pt(this._conversation.muteStates,Fe.MUTE_PERMANENT),stateUpdated:!0});return}let i=this._participants[e];i&&!wt(i.roles,t)&&(c.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,g.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],a=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&!this._isMe(e.participantId)){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),g.onMuteStates(i,r,a,e.muteAll,e.unmute,d.externalId,s==null?void 0:s.externalId,e.stateUpdated,e.requestedMedia));return}if(!(v.isObjectsEquals(this._conversation.muteStates,i)&&v.isArraysEquals(this._conversation.unmuteOptions,r)&&!a.length)){if(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,this._isMe(e.adminId)){e.muteAll&&g.onMuteStates(i,r,a,e.muteAll,e.unmute,null,this._conversation.externalId,e.stateUpdated,e.requestedMedia);return}yield this._processMuteState({mediaOptions:a,muteAll:e.muteAll,unmute:e.unmute,serverSettings:t,admin:s,stateUpdated:e.stateUpdated,requestedMedia:e.requestedMedia})}})}_processMuteState(p){return o(this,arguments,function*({mediaOptions:e=[],muteAll:t=!1,unmute:i=!1,serverSettings:r=null,admin:a=null,stateUpdated:s,requestedMedia:d}){if(!this._conversation||!this._mediaSource||this._participantState!==j.ACCEPTED)return;let u=Object.assign({},this._conversation.muteStates),E=this._conversation.unmuteOptions,I=this._mediaSource.getMediaSettings(),R=Object.entries(u);for(let[b,V]of R)if(!(V!==Fe.MUTE&&V!==Fe.MUTE_PERMANENT)&&(this._isCallAdmin()&&V===Fe.MUTE_PERMANENT&&!t&&(u[b]=Fe.MUTE),!(!e.includes(b)||i)))switch(b){case ue.VIDEO:I.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(g.onDeviceSwitched(ue.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case ue.AUDIO:I.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(g.onDeviceSwitched(ue.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case ue.SCREEN_SHARING:I.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(g.onDeviceSwitched(ue.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1,!1));break;case ue.AUDIO_SHARING:I.isAudioSharingEnabled&&!(r==null?void 0:r.isAudioSharingEnabled)&&(g.onDeviceSwitched(ue.AUDIO_SHARING,!1),yield this.toggleScreenCapturing(I.isScreenSharingEnabled,!1));break}g.onMuteStates(u,E,e,t,i,null,a==null?void 0:a.externalId,s,d)})}_onPinParticipant(e,t=!1,i){return o(this,null,function*(){if(!this._conversation)return;let r=this._conversation.pinnedParticipantId;if(r&&r!==e)if(this._isMe(r))g.onLocalPin(!0);else{let a=yield this._getExternalIdByParticipantId(r);a&&g.onPinnedParticipant(a,!0,this._denormalizeMarkers(e,i))}if(this._isMe(e))g.onLocalPin(t);else{let a=yield this._getExternalIdByParticipantId(e);a&&g.onPinnedParticipant(a,t,this._denormalizeMarkers(e,i))}this._conversation.pinnedParticipantId=t?null:e})}_onOptionsChanged(e){this._conversation&&!Pr(this._conversation.options,e)&&(this._conversation.options=e,g.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let a;if(this._isMe(i)||i==="")a=this._conversation.networkRating;else if(this._participants[i])a=this._participants[i].networkRating;else continue;if(a!==r)if(this._isMe(i)||i==="")this._conversation.networkRating=r,g.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;c.log("Received network status update: ",e),g.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(l.producerScreenTrack){g.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){_.log(T.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}g.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&g.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===de.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Ai.ADD_PARTICIPANT);g.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&g.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let a=this._participants[i];a&&a.externalId&&t.push({uid:a.externalId,volume:r.real})}g.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){c.debug(`Transport state has changed: ${t}`,e);let i=this._getStatusByTransportState(t);if(!i)return;let r=e.reduce((a,s)=>{if(s in this._participants){let 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 this._warnParticipantNotInConversation(s);return a},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){var t;if(c.debug(`Local transport state has changed: ${e}`),e===F.CONNECTED&&(g.onLocalStatus(Q.CONNECTED),((t=this._transport)==null?void 0:t.getTopology())===de.SERVER)){let i=Object.values(this._myLastRequestedLayouts);yield this.updateDisplayLayout(i)}e===F.CONNECTING&&g.onLocalStatus(Q.CONNECTING),e===F.RECONNECTING&&g.onLocalStatus(Q.RECONNECT),e===F.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(k.FAILED)),this._close(new B(k.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(He.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i),g.onRemoteMixedAudioStream(t);else if(e.startsWith(He.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))c.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{c.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(c.warn(`Conversation: track added before participant [${e}]`),r=this._registerParticipantInCache(yield this._createParticipant({id:e})),this._setParticipantsStatus([r],Q.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===me.audio&&(this._audioOutput.add(i),l.preserveAudioTracks||t.removeTrack(i)),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;g.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),l.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(c.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case me.audio:this._removeAudioTrack(e,t,i);break;case me.video:case me.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==He.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e===de.DIRECT&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let a=this._participants[r];e||this._lastStalled[r]?t.push(a):i.push(a)}t.length&&this._setParticipantsStatus(t,Q.RECONNECT),i.length&&this._setParticipantsStatus(i,Q.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,Q.RECONNECT),r.length&&this._setParticipantsStatus(r,Q.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!P.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(c.debug("Toggle join availability",{available:t,chatId:e}),g.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==de.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(c.debug("Set participants status",{participants:e,status:t,data:i}),!e.length)return;let r=e.reduce((a,s)=>(s.status!==t&&(s.status=t,l.batchParticipantsOnStart?a.push(s.externalId):g.onParticipantStatus(s.externalId,t,i)),a),[]);!r.length||l.batchParticipantsOnStart&&g.onRemoteStatus(r,t,i)}_onJoinLinkChanged(e){g.onJoinLinkChanged(e.joinLink)}_onRoomsUpdated(e){return o(this,null,function*(){var i,r;let t={};for(let a of Object.keys(ki)){let s=e.updates[a];!s||(t[a]={rooms:yield Promise.all(((r=(i=s==null?void 0:s.rooms)==null?void 0:i.map)==null?void 0:r.call(i,this._convertRoomToExternal.bind(this)))||[]),roomIds:s==null?void 0:s.roomIds,deactivated:s==null?void 0:s.deactivated})}g.onRoomsUpdated(t)})}_onRoomUpdated(e){return o(this,null,function*(){let t=yield this._convertRoomToExternal(e.room);g.onRoomUpdated(e.events,e.roomId,t,e.deactivate)})}_convertRoomToExternal(e){return o(this,null,function*(){var a,s,d,p,u,E;if(!e)return null;let[t,i,r]=yield Promise.all([Promise.all(((s=(a=e==null?void 0:e.participantIds)==null?void 0:a.map)==null?void 0:s.call(a,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((p=(d=e==null?void 0:e.addParticipantIds)==null?void 0:d.map)==null?void 0:p.call(d,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((E=(u=e==null?void 0:e.removeParticipantIds)==null?void 0:u.map)==null?void 0:E.call(u,this._getExternalIdByParticipantId.bind(this)))||[])]);return{id:e.id,name:e.name,participantCount:e.participantCount,participantIds:t,addParticipantIds:i,removeParticipantIds:r,participants:e.participants,active:e.active}})}_onRoomParticipantsUpdated(e){return o(this,null,function*(){var p,u,E,I,R;let t=this._transport.getState(),[i,r]=yield Promise.all([Promise.all(((u=(p=e.addedParticipantIds)==null?void 0:p.map)==null?void 0:u.call(p,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((I=(E=e==null?void 0:e.addedParticipants)==null?void 0:E.map)==null?void 0:I.call(E,b=>o(this,null,function*(){var Z;let V=v.composeId(b);return this._createParticipant({id:V,externalId:b.externalId&&ve.fromSignaling(b.externalId,b.deviceIdx||0),mediaSettings:Se(b.mediaSettings),participantState:v.mapParticipantState(b),state:b.state,roles:b.roles||[],status:(Z=this._getStatusByTransportState(t))!=null?Z:Q.WAITING,muteStates:b.muteStates||{},unmuteOptions:b.unmuteOptions||[],observedIds:b.observedIds||[],markers:this._denormalizeMarkers(V,b.markers)})})))||[])]);for(let b of r)this._registerParticipantInCache(b),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(b.id)||this._transport.allocate(b.id,!0),this._transport.open([b.id],null,!!((R=this._conversation)==null?void 0:R.observer)));let a=[],s=[];if(e==null?void 0:e.removedParticipantMarkers){for(let b of e.removedParticipantMarkers)b.GRID&&s.push(this._getExternalIdByParticipantId(b.GRID.id));a=yield Promise.all(s)}let d={roomId:e.roomId,participantCount:e.participantCount,addedParticipantIds:i,addedParticipants:v.mapSharedParticipants(r),removedParticipantMarkers:e==null?void 0:e.removedParticipantMarkers,removedParticipantIds:a};g.onRoomParticipantsUpdated(d)})}_onFeedback(e){return o(this,null,function*(){let t=a=>o(this,null,function*(){return(yield this._registerParticipantAndSetMarkersIfChunkEnabled(a)).externalId}),i=e.feedback.map(a=>o(this,null,function*(){let s=a.items.map(p=>o(this,null,function*(){if(p.participantId===this._conversation.compositeUserId)return Promise.resolve(ht(Ve({},p),{participantId:this._conversation.externalId}));let u=yield t(p.participantId);return ht(Ve({},p),{participantId:u})})),d=yield Promise.all(s);return ht(Ve({},a),{items:d})})),r=yield Promise.all(i);g.onFeedback(r)})}_isMe(e){var t;return e===((t=this._conversation)==null?void 0:t.compositeUserId)}},N=W;N._delayedHangup=!1;var Ei=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Ei.prototype),this.participantErrors=t}};var Jt,Ii=null;function Yn(){return o(this,null,function*(){var n;if(l.apiEnv!=="AUTO")return l.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(n=i==null?void 0:i.Answer[0])==null?void 0:n.data;if(!r)throw new Error("Wrong DNS response");return c.debug("Resolved API endpoint",r),r}catch(e){return c.warn("Failed to resolve API endpoint using DNS, default is used",e),l.apiEndpoint}})}function Pa(){return Jt?Promise.resolve(Jt):Ii||(Ii=Yn().then(n=>Jt=n).finally(()=>Ii=null))}function ba(){if(!l.apiKey)throw new B(ce.API,{message:"Required argument apiAppKey not passed"})}function ur(i){return o(this,arguments,function*(n,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;yield Pa();let r=Aa(n,e,t),a=new window.Blob([r],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${Jt}/fb.do`,a)})}function Ma(i){return o(this,arguments,function*(n,e={},t=!1){yield Pa();let r=Aa(n,e,t);return Qn(r)})}function Qn(n){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${Jt}/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 Aa(n,e={},t=!1){e.method=n,e.format="JSON",e.application_key||(e.application_key=l.apiKey),t||(se.sessionKey?e.session_key=se.sessionKey:se.accessToken&&(e.access_token=se.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 Zn=10,es=700,ts=3e3,Ti=class extends Dt{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 Ma(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<Zn))return yield v.delay(Math.min(s*es,ts)),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=ce.API;switch(a.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=k.SERVICE_DISABLED;break;case 1102:s=k.CALLEE_IS_OFFLINE;break;case 1103:s=k.NOT_FRIENDS;break;case 1104:case 1106:s=k.EXTERNAL_API_ERROR;break;case 1113:s=k.CALLER_IS_REJECTED;break}throw new B(s,{message:a.error_msg,code:a.error_code})}})}userId(e){return o(this,null,function*(){let t=v.decomposeId(e).id;return se.isEmpty()?Te.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),Te.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return o(this,null,function*(){se.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return o(this,null,function*(){if(!this._uuid){let t=et.get("uuid");t||(t=v.uuid(),et.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)),se.sessionKey=t.session_key,se.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&g.onTokenExpired(),new B(ce.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})};ur("log.externalLog",t)}init(){ba()}joinConversation(e,t=!1,i){return o(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:l.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(a){return o(this,arguments,function*(e,t="",i=!1,{onlyAdminCanShareMovie:r}={}){let s=this._preareStartConversationData({conversationId:e,isVideo:!1,joiningAllowed:!0,payload:t,requireAuthToJoin:i,onlyAdminCanShareMovie:r});return this._startConversation(s)})}startConversation(u,E,I){return o(this,arguments,function*(e,t,i,r=!1,a="",s=!1,d=!1,{onlyAdminCanShareMovie:p}={}){let R=this._preareStartConversationData({conversationId:e,isVideo:r,joiningAllowed:s,payload:a,requireAuthToJoin:d,onlyAdminCanShareMovie:p});if(t&&t.length)switch(i){case ze.USER:R.uids=t.join(",");break;case ze.GROUP:R.gid=t[0];break;case ze.CHAT:R.chatId=t[0];break}return this._startConversation(R)})}_preareStartConversationData({conversationId:e,isVideo:t,payload:i="",joiningAllowed:r=!1,requireAuthToJoin:a=!1,onlyAdminCanShareMovie:s}){let d={conversationId:e,isVideo:t,protocolVersion:l.protocolVersion};return r&&(d.createJoinLink=!0),i&&(d.payload=i),l.domain&&(d.domainId=l.domain),l.externalDomain&&(d.externalDomain=l.externalDomain),a&&(d.requireAuthToJoin=!0),s!==void 0&&(d.onlyAdminCanShareMovie=s),d}_startConversation(e){return o(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return o(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return o(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return o(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i,r){return o(this,null,function*(){let a={joinLink:e,isVideo:t,protocolVersion:l.protocolVersion};return(i==null?void 0:i.length)&&(a.observedIds=i.join(",")),l.anonymToken&&(a.anonymToken=l.anonymToken),r&&(a.payload=r),this._call("vchat.joinConversationByLink",a)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=Te.fromIds(e),i=[],r={methods:[]},a=[],s=Object.keys(this._externalUidsCache),d=Object.values(this._externalUidsCache);for(let u of t){let E=Te.toString(u),I=d.indexOf(E);I>-1?i.push(Number(s[I])):(a.push(E),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:u.id,anonym:u.type===Rt.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((u,E)=>{if(u.ok){let I=Number(u.ok.ok_id);this._externalUidsCache[I]=a[E],i.push(I)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let a of e)this._externalUidsCache.hasOwnProperty(a)?t.push(Te.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(Te.fromString(r[a]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=Te.toString(e),a=i.indexOf(r);return a>-1?v.composeUserId(t[a],te.USER):null}cacheExternalId(e,t){let i=v.decomposeId(e).id;this._externalUidsCache[i]=Te.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:k.HUNGUP};l.anonymToken&&(t.anonymToken=l.anonymToken),ur("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]=Te.fromIdToString(a,Rt.USER);if(i.anonym_ids)for(let[r,a]of Object.entries(i.anonym_ids))t[r]=Te.fromIdToString(a,Rt.ANONYM);return t}catch(i){return t}})}};import{Any as rs,Arr as ka,Int as z,Nil as ut,Str as as}from"messagepack";var Da=(U=>(U.RECOVER="recover",U.ACCEPT_CALL="accept-call",U.ADD_PARTICIPANT="add-participant",U.REMOVE_PARTICIPANT="remove-participant",U.HANGUP="hangup",U.TRANSMIT_DATA="transmit-data",U.ACCEPT_PRODUCER="accept-producer",U.ALLOCATE_CONSUMER="allocate-consumer",U.CHANGE_MEDIA_SETTINGS="change-media-settings",U.CHANGE_PARTICIPANT_STATE="change-participant-state",U.CHANGE_STREAM_PRIORITIES="change-streams-priorities",U.UPDATE_DISPLAY_LAYOUT="update-display-layout",U.REPORT_PERF_STAT="report-perf-stat",U.REPORT_SHARING_STAT="report-sharing-stat",U.RECORD_START="record-start",U.RECORD_STOP="record-stop",U.RECORD_SET_ROLE="record-set-role",U.RECORD_GET_STATUS="record-get-status",U.SWITCH_MICRO="switch-micro",U.SWITCH_TOPOLOGY="switch-topology",U.REQUEST_REALLOC="request-realloc",U.CHAT_MESSAGE="chat-message",U.CHAT_HISTORY="chat-history",U.CUSTOM_DATA="custom-data",U.GRANT_ROLES="grant-roles",U.MUTE_PARTICIPANT="mute-participant",U.ENABLE_FEATURE_FOR_ROLES="enable-feature-for-roles",U.PIN_PARTICIPANT="pin-participant",U.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",U.CHANGE_OPTIONS="change-options",U.GET_WAITING_HALL="get-waiting-hall",U.GET_PARTICIPANT_LIST_CHUNK="get-participant-list-chunk",U.GET_PARTICIPANTS="get-participants",U.PROMOTE_PARTICIPANT="promote-participant",U.REQUEST_TEST_MODE="request-test-mode",U.ADD_MOVIE="add-movie",U.UPDATE_MOVIE="update-movie",U.REMOVE_MOVIE="remove-movie",U.GET_ROOMS="get_rooms",U.GET_ROOM="get_room",U.UPDATE_ROOMS="update-rooms",U.ACTIVATE_ROOMS="activate-rooms",U.REMOVE_ROOMS="remove-rooms",U.SWITCH_ROOM="switch-room",U.FEEDBACK="feedback",U.ASR_START="asr-start",U.ASR_STOP="asr-stop",U))(Da||{}),w=Da;function zt(){let n=new DataView(new ArrayBuffer(64)),e=0;function t(i){if(e+i>n.byteLength){let r=new Uint8Array(Math.max(e+i,n.byteLength+64));r.set(new Uint8Array(n.buffer.slice(0,e))),n=new DataView(r.buffer)}}return{put(i){if(t(i.byteLength),is(i)){let r=i.buffer;new Uint8Array(n.buffer).set(new Uint8Array(r),e)}else new Uint8Array(n.buffer).set(new Uint8Array(i),e);e+=i.byteLength},putI8(i){t(1),n.setInt8(e,i),++e},putI16(i){t(2),n.setInt16(e,i),e+=2},putI32(i){t(4),n.setInt32(e,i),e+=4},putI64(i){t(8);let r=i<0;r&&(i=-i);let a=i/4294967296|0,s=i%4294967296|0;r&&(s=~s+1|0,a=s===0?~a+1|0:~a),n.setUint32(e,a),n.setUint32(e+4,s),e+=8},putUi8(i){t(1),n.setUint8(e,i),++e},putUi16(i){t(2),n.setUint16(e,i),e+=2},putUi32(i){t(4),n.setUint32(e,i),e+=4},putUi64(i){t(8),n.setUint32(e,i/4294967296|0),n.setUint32(e+4,i%4294967296),e+=8},putF(i){t(8),n.setFloat64(e,i),e+=8},ui8array(){return new Uint8Array(n.buffer.slice(0,e))}}}function is(n){return n.buffer!==void 0}function Ci(n){let e=ArrayBuffer.isView(n)?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),t=0;return{peek(){return e.getUint8(t)},get(i){t+=i;let r=e.byteOffset;return e.buffer.slice(r+t-i,r+t)},getI8(){return e.getInt8(t++)},getI16(){return t+=2,e.getInt16(t-2)},getI32(){return t+=4,e.getInt32(t-4)},getI64(){t+=8;let i=e.getInt32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getUi8(){return e.getUint8(t++)},getUi16(){return t+=2,e.getUint16(t-2)},getUi32(){return t+=4,e.getUint32(t-4)},getUi64(){t+=8;let i=e.getUint32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getF32(){return t+=4,e.getFloat32(t-4)},getF64(){return t+=8,e.getFloat64(t-8)}}}var Oa=0,wa=1,ns=2,ss=0,os=1,cs=2,yi=0,ds=0,ps=0,ls=1,mr=class{constructor(){this.participantIdRegistry=null}setParticipantIdRegistry(e){this.participantIdRegistry=e}serializeUpdateDisplayLayout(e,t){let i=zt();z.enc(i,Oa),z.enc(i,yi),z.enc(i,e),ut.enc(i,null);let r=[];for(let a in t)t.hasOwnProperty(a)&&this.writeLayout(t,a,r);return ka.enc(i,r),ut.enc(i,null),i.ui8array()}writeLayout(e,t,i){let r=e[t],a=zt();if(this.writeStreamDesc(t,a),Gt(r))z.enc(a,os);else if(rr(r))z.enc(a,cs);else if(z.enc(a,ss),r.priority!==void 0?z.enc(a,r.priority):ut.enc(a,null),r.width!==void 0&&r.height!==void 0?(z.enc(a,Math.round(r.width)),z.enc(a,Math.round(r.height))):(ut.enc(a,null),ut.enc(a,null)),r.fit!==void 0)switch(r.fit){case"cv":z.enc(a,ps);break;case"cn":z.enc(a,ls);break;default:ut.enc(a,null)}else ut.enc(a,null);i.push(a.ui8array())}writeStreamDesc(e,t){if(this.participantIdRegistry){let i=this.participantIdRegistry.getCompactId(e);if(i!==void 0){z.enc(t,i);return}}as.enc(t,e)}serializePerfStatReport(e,t){let i=zt();return z.enc(i,wa),z.enc(i,yi),z.enc(i,e),z.enc(i,t.framesDecoded),z.enc(i,t.framesReceived),i.ui8array()}serializeSharingStatReport(e,t){let i=zt();return z.enc(i,ns),z.enc(i,yi),z.enc(i,e),z.enc(i,t.minDelay),z.enc(i,t.maxDelay),z.enc(i,t.avgDelay),z.enc(i,t.largeDelayDuration),i.ui8array()}deserializeCommandResponse(e){return o(this,null,function*(){let t;if(e instanceof Blob){let s=yield e.arrayBuffer();t=Ci(s)}else t=Ci(e);let i=z.dec(t),r=z.dec(t);if(r!==yi){c.warn("Unsupported version for command type: "+i+", version "+r);return}if(z.dec(t)!==ds){c.warn("Error code: "+i+"received for command type: "+i+", version "+r);return}switch(i){case Oa:return this.deserializeUpdateDisplayLayoutResponse(t);case wa:return this.deserializeReportPerfStatResponse(t);default:return c.warn("unsupported command response commandType: "+i),null}})}deserializeUpdateDisplayLayoutResponse(e){let t=z.dec(e),i=ka.dec(e),r={};return i.forEach(a=>{let s=Ci(a),d=rs.dec(s);if(typeof d=="string")r[d]=z.dec(s);else{let p=d,u=$e(this.participantIdRegistry.getStreamDescription(p));r[u]=z.dec(s)}}),{type:"response",sequence:t,response:w.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:r}}deserializeReportPerfStatResponse(e){let t=z.dec(e),i=z.dec(e);return{type:"response",sequence:t,response:w.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:i}}};var xa="open",La=[()=>l.producerScreenTrack,()=>l.videoTracksCount>0,()=>!0,()=>l.filteredMessages,()=>l.consumerScreenTrack,()=>!0,()=>l.movieShare,()=>l.useParticipantListChunk,()=>l.useRooms],us=10,xe=class extends Ot{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="+xe._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null;this.producerCommandDataChannelEnabled=!1;this.producerCommandSerializationService=new mr}static _getCapabilityFlags(){let e=0;for(let t=0;t<La.length;t++)La[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e,this.producerCommandSerializationService.setParticipantIdRegistry(e)}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=t=>{this.producerCommandSerializationService.deserializeCommandResponse(t.data).then(i=>{i&&this._handleMessage(i)}).catch(i=>{c.warn("Cannot parse message at producerCommandDataChannel",i)})},this._handleCommandsQueue(this.datachannelCommandsQueue)}useCommandDataChannel(e){this.producerCommandDataChannelEnabled=e}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){_.log(T.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return o(this,arguments,function*(e,t={},i=0){if(t.participantId){let a=v.decomposeParticipantId(t.participantId),s=v.decomposeId(a.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),a.deviceIdx&&(t.deviceIdx=a.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return o(this,arguments,function*(e,t={},i=0){let a=s=>{var p;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((p=this.producerCommandDataChannel)==null?void 0:p.readyState)===xa&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){_.log(T.SOCKET_ACTION,"not_opened"),c.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(_.log(T.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=(E,I=!1)=>{!i||I?d(E):(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.producerCommandDataChannelEnabled?e===w.UPDATE_DISPLAY_LAYOUT||e===w.REPORT_PERF_STAT||e===w.REPORT_SHARING_STAT:!1}static _isDataChannelResponseRequired(e){return e===w.UPDATE_DISPLAY_LAYOUT||e===w.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(w.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(w.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e,t){return o(this,null,function*(){return this._send(w.REQUEST_TEST_MODE,{consumer:e,producer:t})})}sendSdp(e,t){return o(this,null,function*(){return this._send(w.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(w.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(w.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},us)})}changeParticipantState(e){return o(this,null,function*(){return this._send(w.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(w.ADD_PARTICIPANT,Ve({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(w.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(w.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(w.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(w.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(w.UPDATE_DISPLAY_LAYOUT,e)})}addMovie(e){return o(this,null,function*(){return this._send(w.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(w.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(w.REMOVE_MOVIE,e)})}updateRooms(e,t){return o(this,null,function*(){return this._send(w.UPDATE_ROOMS,{rooms:e,assignRandomly:t})})}activateRooms(e,t){return o(this,null,function*(){return this._send(w.ACTIVATE_ROOMS,{roomIds:e,deactivate:t})})}switchRoom(e,t){return o(this,null,function*(){return this._sendRaw(w.SWITCH_ROOM,{toRoomId:e,participantId:t})})}removeRooms(e){return o(this,null,function*(){return this._send(w.REMOVE_ROOMS,{roomIds:e})})}startStream(e){return o(this,null,function*(){return this._send(w.RECORD_START,e)})}stopStream(e){return o(this,null,function*(){return this._send(w.RECORD_STOP,e)})}recordSetRole(e,t){return o(this,null,function*(){return this._send(w.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return o(this,null,function*(){return this._send(w.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(w.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(w.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(w.REPORT_PERF_STAT,e)})}reportSharingStat(e){return o(this,null,function*(){return this._send(w.REPORT_SHARING_STAT,e)})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(w.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(w.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(w.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(w.GRANT_ROLES,r)})}muteParticipant(e,t,i){return o(this,null,function*(){return this._sendRaw(w.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}enableFeatureForRoles(e,t){return o(this,null,function*(){return this._sendRaw(w.ENABLE_FEATURE_FOR_ROLES,{feature:e,roles:t})})}pinParticipant(e,t){return o(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(w.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(w.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(w.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(w.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(w.PROMOTE_PARTICIPANT,i)})}feedback(e){return o(this,null,function*(){return this._sendRaw(w.FEEDBACK,{key:e})})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}getParticipantListChunk(e){return o(this,null,function*(){return this._send(w.GET_PARTICIPANT_LIST_CHUNK,e)})}getParticipants(e){return o(this,null,function*(){return this._send(w.GET_PARTICIPANTS,{externalIds:e})})}startAsr(){return o(this,null,function*(){return this._send(w.ASR_START)})}stopAsr(){return o(this,null,function*(){return this._send(w.ASR_STOP)})}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ye.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),t=i(t),c.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor();function i(r){if(!l.useParticipantListChunk)return r;r+=`&partIdx=${l.participantListChunkInitIndex}`;let s=l.participantListChunkInitCount;return s!==null&&(r+=`&partCount=${s}`),r}}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){c.debug("Socket opened"),_.log(T.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){_.log(T.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(ye.RECONNECT,e),e.conversation.topology&&this._triggerEvent(ye.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(ye.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(_.log(T.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(_.log(T.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new B(k.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(ye.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 B(ce.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(_.log(T.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(ye.FAILED,e)}_onError(e){_.log(T.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){_.log(T.SOCKET_ACTION,"closed"),c.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<xe.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(xe.RECONNECT_MAX_DELAY,xe.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),_.log(T.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ye.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],_.log(T.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),xe.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift();if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==xa){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}xe._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:r.name,sequence:r.sequence}),xe.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r);let s=this._serializeBinary(r);s!==null&&this.producerCommandDataChannel.send(s)}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:r.name,sequence:r.sequence}),xe.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(this._serializeJson(r))}}}_serializeBinary(e){switch(e.name){case w.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case w.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params);case w.REPORT_SHARING_STAT:return this.producerCommandSerializationService.serializeSharingStatReport(e.sequence,e.params)}return c.warn("cannot get binary data for data channel command: "+e.name),null}_serializeJson(e){let t;e.name===w.UPDATE_DISPLAY_LAYOUT?t=this._convertDisplayLayout(e.params):t=e.params;let i=Object.assign({command:e.name,sequence:e.sequence},t);return JSON.stringify(i)}_convertDisplayLayout(e){let t=e,i={};for(let r in t)t.hasOwnProperty(r)&&(i[r]=Sa(t[r]));return{layouts:i}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new B(ce.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},xe.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(Ye.RETRY)},xe.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},qe=xe;qe.RECONNECT_DELAY=l.signalingReconnectDelay,qe.RECONNECT_MAX_DELAY=l.signalingReconnectMaxDelay,qe.RECONNECT_MAX_COUNT=l.signalingReconnectMaxCount,qe.WAIT_CONNECTION_DELAY=l.waitConnectionDelay,qe.WAIT_RESPONSE_DELAY=l.waitResponseDelay,qe.WAIT_MESSAGE_DELAY=l.waitMessageDelay;var Na=(t=>(t.KING="KING",t.PAWN="PAWN",t))(Na||{}),ms=Na;var Ua=class{constructor(e){this._queue=new Array(e).fill(null),this._readCursor=this._writeCursor=this._left=0,this._moveReadCursor=!1}get length(){return this._queue.length}get left(){return this._left}toArray(){return Array.from(this._queue)}add(e){this._moveReadCursor&&(this._readCursor=this.nextCursor(this._readCursor)),this._queue[this._writeCursor]===null&&(this._left+=1),this._queue[this._writeCursor]=e,this._writeCursor=this.nextCursor(this._writeCursor),this._moveReadCursor=this._writeCursor===this._readCursor}nextCursor(e){return(e+1)%this._queue.length}next(){let e=this._queue[this._readCursor];return e&&(this._moveReadCursor=!1,this._queue[this._readCursor]=null,this._readCursor=this.nextCursor(this._readCursor),this._left-=1),e}};var bt,le,Yt=null,qh={getCameras:P.getCameras,getMicrophones:P.getMicrophones,getOutput:P.getOutput,hasCamera:P.hasCamera,hasMicrophone:P.hasMicrophone,getSavedCamera:P.getSavedCamera,getSavedMicrophone:P.getSavedMicrophone,getSavedOutput:P.getSavedOutput,hasCameraPermission:P.hasCameraPermission,hasMicrophonePermission:P.hasMicrophonePermission,hasPermissions:P.hasPermissions,getUserMedia:P.getUserMedia,getUserVideo:P.getUserVideo,getUserAudio:P.getUserAudio,saveDeviceId:P.saveDeviceId,isBrowserSupported:P.isBrowserSupported,isScreenCapturingSupported:P.isScreenCapturingSupported,os:P.os,isMobile:P.isMobile,browserName:P.browserName,browserVersion:P.browserVersion,baseChromeVersion:P.baseChromeVersion,getAudioContext:P.getAudioContext};function hs(n){le=n}function _s(n){bt=n}function Jh(n){Yt=n}function zh(n){l.videoEffects=n}function Yh(n){return o(this,null,function*(){if(l.set(n),P.browserName()==="Sferum"&&(l.platform=`SFERUM:${P.browserVersion()}`),le||hs(new Ti),bt||_s(()=>new qe),l.debug&&(Ba.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${l.sdkVersion}`,n),yield P.init(),!P.isBrowserSupported())throw new B(ce.UNSUPPORTED);c.log("UserAgent:",navigator.userAgent),c.log("Screen resolution:",`${window.screen.width}x${window.screen.height}`),c.log("Permissions:",`Camera: ${P.hasCameraPermission()}, Mic: ${P.hasMicrophonePermission()}`),le.init()})}function Qh(s){return o(this,arguments,function*(n,e=[ue.AUDIO],t="",i=!1,r=!1,a){let d=[],p=[];if(Array.isArray(n)?d=n.length?n:[]:n&&(d=[n]),d.length&&(p=yield le.getOkIdsByExternalIds(d),!p.length))throw new B(k.CALLEE_IS_OFFLINE);return gs(p,ze.USER,e,t,i,r,a)})}function gs(d){return o(this,arguments,function*(n,e=ze.USER,t,i="",r=!1,a=!1,s){if(N.current())throw c.error("There is already active call"),new B(k.FAILED);return new N(le,bt(),Yt).onStart(n,e,t,i,r,a,s)})}function Xh(n){return o(this,null,function*(){return fs(n)})}function fs(i){return o(this,arguments,function*(n,e=te.USER,t){if(n===N.id())throw new Error("Push has already been processed");return new N(le,bt(),Yt).onPush(n,e,t)})}function Zh(n){return o(this,null,function*(){return n&&(l.authToken=n),le.authorize()})}function e_(){return o(this,arguments,function*(n=[ue.AUDIO]){return mt().accept(n)})}function t_(){return o(this,null,function*(){let n=N.current();if(n)return n.decline()})}function i_(t){return o(this,arguments,function*(n,e=[ue.AUDIO]){return Ss(n,e)})}function Ss(n,e,t){return o(this,null,function*(){if(N.current())throw c.error("There is already active call"),new B(k.FAILED);return new N(le,bt(),Yt).onJoin({conversationId:n,mediaOptions:e,chatId:t})})}function r_(a){return o(this,arguments,function*(n,e=[ue.AUDIO],t,i,r){if(N.current())throw c.error("There is already active call"),new B(k.FAILED);return t&&(l.anonymToken=t),new N(le,bt(),Yt).onJoin({joinLink:n,mediaOptions:e,observedIds:i,payload:r})})}function a_(){return o(this,null,function*(){let n=N.current();if(n)return n.hangup();N.hangupAfterInit()})}function n_(n,e){return o(this,null,function*(){let t=yield le.getOkIdsByExternalIds([n]);if(!t.length)throw new Error("User not found");return vs(t[0],e)})}function vs(n,e){return o(this,null,function*(){let t=N.current();t&&(yield t.addParticipant(v.composeUserId(n,te.USER),e))})}function s_(n,e=!1){return o(this,null,function*(){let t=yield le.getOkIdsByExternalIds([n]);return Es(t[0],e)})}function Es(n,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.removeParticipant(v.composeUserId(n,te.USER),e))})}function o_(n,e){return o(this,null,function*(){let t=yield P.saveDeviceId(n,e),i=N.current();return t&&i?i.changeDevice(n):Promise.reject()})}function c_(n){return o(this,null,function*(){return Is(n,!1)})}function Is(n,e){return o(this,null,function*(){if(e){if(!l.audioShareCapabilityEnabled)throw new Error("Audio share capability is disabled");if(!n)throw new Error("Audio share without screen share is not allowed")}let t=N.current();return t?t.toggleScreenCapturing(n,e):Promise.reject()})}function d_(n,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.setVideoStream(n,e))})}function p_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalVideo(n))})}function l_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalAudio(n))})}function u_(n,e,t){return o(this,null,function*(){let i=N.current();if(i)return i.setLocalResolution(n,e,t)})}function m_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changePriorities(n))})}function h_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changeParticipantState(n))})}function __(n){return o(this,null,function*(){let e=N.current();e&&(yield e.updateDisplayLayout(n))})}function g_(n,e,t=!1){return o(this,null,function*(){let i=yield le.getOkIdsByExternalIds([n]);return Ts(i[0],e,t)})}function Ts(n,e,t=!1){return o(this,null,function*(){let i=N.current();i&&(yield i.grantRoles(v.composeUserId(n,te.USER),e,t))})}function f_(){return o(this,arguments,function*(n=null,e,t=[]){let i=null;return n&&(i=(yield le.getOkIdsByExternalIds([n]))[0]),Cs(i,e,t,ve.getDeviceIdx(n))})}function Cs(){return o(this,arguments,function*(n=null,e,t=[],i=0){let r=N.current();if(r){let a=n?v.composeParticipantId(n,te.USER,i):null;yield r.muteParticipant(a,e,t)}})}function S_(n,e=!1){return o(this,null,function*(){let t=yield le.getOkIdsByExternalIds([n]);return ys(t[0],e,ve.getDeviceIdx(n))})}function ys(n,e=!1,t=0){return o(this,null,function*(){let i=N.current();i&&(yield i.pinParticipant(v.composeParticipantId(n,te.USER,t),e))})}function v_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.updateMediaModifiers(n))})}function E_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changeOptions(n))})}function I_(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield le.getOkIdsByExternalIds([e]))[0]),Rs(n,t)})}function Rs(n,e=null){return o(this,null,function*(){let t=N.current();if(t){let i=e?v.composeUserId(e,te.USER):null;yield t.chatMessage(n,i)}})}function T_(n=10){return o(this,null,function*(){let e=N.current();if(e)return e.chatHistory(n)})}function C_(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield le.getOkIdsByExternalIds([e]))[0]),Ps(n,t,ve.getDeviceIdx(e))})}function Ps(n,e=null,t=0){return o(this,null,function*(){let i=N.current();if(i){let r=e?v.composeParticipantId(e,te.USER,t):null;yield i.customData(n,r)}})}function y_(){return o(this,arguments,function*(n="",e=!1,{onlyAdminCanShareMovie:t=!1}={}){return(yield le.createConversation(v.uuid(),n,e,{onlyAdminCanShareMovie:t})).join_link})}function R_(){return o(this,null,function*(){let n=N.current();return n?n.createJoinLink():Promise.reject()})}function P_(){return o(this,null,function*(){let n=N.current();return n?n.removeJoinLink():Promise.reject()})}function b_(n,e){return o(this,null,function*(){return le.getAnonymTokenByLink(n,e)})}function M_(n){let e=N.current();e&&e.setVolume(n)}function A_(n){l.forceRelayPolicy=n}function D_(n=!1,e=null,t=null,i="DIRECT_LINK",r=null,a=null){return o(this,null,function*(){let s=N.current();return s?s.startStream(n,e,t,i,r,a):Promise.reject()})}function k_(n=null){return o(this,null,function*(){let e=N.current();return e?e.stopStream(n):Promise.reject()})}function O_(n,e){return o(this,null,function*(){let t=N.current();if(t){let i=yield le.getOkIdsByExternalIds([n]),r=ve.getDeviceIdx(n);return t.recordSetRole(v.composeParticipantId(i[0],te.USER,r),e)}return Promise.reject()})}function w_(){return o(this,null,function*(){let n=N.current();return n?n.getStreamInfo():Promise.reject()})}function x_(n){return o(this,null,function*(){let e=N.current();return e?e.addMovie(n):Promise.reject()})}function L_(n){return o(this,null,function*(){let e=N.current();return e?e.updateMovie(n):Promise.reject()})}function N_(n){return o(this,null,function*(){let e=N.current();return e?e.removeMovie(n):Promise.reject()})}function U_(n,e){return o(this,null,function*(){let t=N.current();return t?t.updateRooms(n,e):Promise.reject()})}function B_(n,e){return o(this,null,function*(){let t=N.current();return t?t.activateRooms(n,e):Promise.reject()})}function V_(n,e=null){return o(this,null,function*(){let t=null;if(e){let r=yield le.getOkIdsByExternalIds([e]);t=v.composeUserId(r[0],te.USER)}let i=N.current();return i?i.switchRoom(n,t):Promise.reject()})}function F_(n){return o(this,null,function*(){let e=N.current();return e?e.removeRooms(n):Promise.reject()})}function H_(n){l.statisticsInterval=n;let e=N.current();if(e)return e.updateStatisticsInterval()}function G_(n){Ba.disableLog(!n),c.toggle(n)}function W_(n,...e){!l.debugLog||c.send(n,"[external]",...e)}function j_(n){return o(this,null,function*(){let e=N.current();if(e)return e.videoEffect(n)})}function K_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.setAudioStream(n))})}function $_(n=null,e,t=!1){return o(this,null,function*(){return mt().getWaitingHall(n,e,t)})}function q_(n,e=!1){return o(this,null,function*(){let t=mt(),i=yield le.getOkIdsByExternalIds([n]);return t.promoteParticipant(v.composeUserId(i[0],te.USER),e)})}function J_(n){return o(this,null,function*(){return mt().getParticipantListChunk(n)})}function z_(n){return o(this,null,function*(){return mt().getParticipants(n)})}function Y_(n){return o(this,null,function*(){return mt().feedback(n)})}function Q_(n,e){return o(this,null,function*(){return mt().enableFeatureForRoles(n,e)})}function mt(){let n=N.current();if(!n)throw new Error("Conversation not found");return n}function X_(n){return o(this,null,function*(){yield le.removeHistoryRecords(n)})}function Z_(){return o(this,null,function*(){let n=N.current();n&&(yield n.startAsr())})}function eg(){return o(this,null,function*(){let n=N.current();n&&(yield n.stopAsr())})}function tg(){return l.sdkVersion}export{Ti as Api,Ua as ArrayDequeue,Dt as BaseApi,kt as BaseLogger,Ot as BaseSignaling,Ze as CallDirection,ze as CallType,Mi as ChatRoomEventType,Ai as ConversationFeature,Di as ConversationOption,fa as DebugMessageType,Rt as ExternalIdType,na as FacingMode,ce as FatalError,B as HangupReason,k as HangupType,ue as MediaOption,me as MediaTrackKind,Me as MediaType,Fe as MuteState,j as ParticipantState,Q as ParticipantStatus,ms as RecordRole,ki as RoomsEventType,qe as Signaling,w as SignalingCommandType,Ye as SignalingConnectionType,O as SignalingNotification,de as TransportTopology,_t as UserRole,te as UserType,v as Utils,e_ as acceptCall,B_ as activateRooms,x_ as addMovie,n_ as addParticipant,vs as addParticipantInternal,Zh as authorize,qh as browser,gs as callInternal,Qh as callTo,c_ as captureScreen,Is as captureScreenAndAudio,E_ as changeConversationOptions,o_ as changeDevice,h_ as changeParticipantState,m_ as changePriorities,j_ as changeVideoEffect,T_ as chatHistory,I_ as chatMessage,Rs as chatMessageInternal,R_ as createJoinLink,C_ as customData,Ps as customDataInternal,G_ as debug,W_ as debugMessage,t_ as declineCall,Q_ as enableFeatureForRoles,Y_ as feedback,A_ as forceRelayPolicy,b_ as getAnonymTokenByLink,J_ as getParticipantListChunk,z_ as getParticipants,w_ as getStreamInfo,$_ as getWaitingHall,g_ as grantRoles,Ts as grantRolesInternal,a_ as hangup,Yh as init,i_ as joinCall,r_ as joinCallByLink,Ss as joinCallInternal,f_ as muteParticipant,Cs as muteParticipantInternal,S_ as pinParticipant,ys as pinParticipantInternal,Xh as processPush,fs as processPushInternal,q_ as promoteParticipant,O_ as recordSetRole,X_ as removeHistoryRecords,P_ as removeJoinLink,N_ as removeMovie,s_ as removeParticipant,Es as removeParticipantInternal,F_ as removeRooms,hs as setApi,K_ as setAudioStream,u_ as setLocalResolution,Jh as setLogger,v_ as setMediaModifiers,_s as setSignalingFactory,H_ as setStatisticsInterval,zh as setVideoEffects,d_ as setVideoStream,M_ as setVolume,Z_ as startAsr,y_ as startConversation,D_ as startStream,eg as stopAsr,k_ as stopStream,V_ as switchRoom,l_ as toggleLocalAudio,p_ as toggleLocalVideo,__ as updateDisplayLayout,L_ as updateMovie,U_ as updateRooms,tg as version};