@vkontakte/calls-sdk 2.6.3-dev.cd0dd8d.0 → 2.6.3-dev.dea4ecd.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CallsSDK.d.ts +25 -23
- package/abstract/BaseApi.d.ts +1 -1
- package/abstract/BaseSignaling.d.ts +1 -1
- package/calls-sdk.cjs.js +8 -8
- package/calls-sdk.esm.js +8 -8
- package/classes/Conversation.d.ts +15 -4
- package/classes/MediaSource.d.ts +10 -2
- package/classes/VolumeDetector.d.ts +1 -1
- package/classes/codec/Types.d.ts +3 -3
- package/classes/codec/WebCodecsEncoder.d.ts +3 -1
- package/classes/screenshare/PacketHistory.d.ts +1 -1
- package/classes/screenshare/ScreenCaptureSender.d.ts +2 -1
- package/classes/screenshare/ScreenCongestionControl.d.ts +3 -1
- package/classes/screenshare/SharingStatReport.d.ts +1 -1
- package/classes/transport/DirectTransport.d.ts +1 -1
- package/classes/transport/PerfStatReporter.d.ts +2 -2
- package/classes/transport/Statistics.d.ts +4 -4
- package/default/Signaling.d.ts +1 -1
- package/enums/ConversationFeature.d.ts +3 -0
- package/enums/RoomsEventType.d.ts +3 -0
- package/package.json +2 -2
- package/static/External.d.ts +15 -0
- package/static/Json.d.ts +1 -1
- package/static/Params.d.ts +22 -6
- package/static/Utils.d.ts +3 -0
- package/static/WebRTCUtils.d.ts +21 -7
- package/types/ConversationFeature.d.ts +4 -1
- package/types/ConversationParams.d.ts +1 -1
- package/types/ConversationResponse.d.ts +1 -1
- package/types/ExternalId.d.ts +8 -5
- package/types/Feedback.d.ts +6 -0
- package/types/IceServer.d.ts +1 -1
- package/types/MediaDeviceType.d.ts +1 -1
- package/types/MediaModifiers.d.ts +1 -1
- package/types/MediaSettings.d.ts +12 -2
- package/types/MovieShare.d.ts +1 -1
- package/types/MuteStates.d.ts +4 -1
- package/types/Participant.d.ts +14 -5
- package/types/ParticipantLayout.d.ts +4 -4
- package/types/ParticipantPriority.d.ts +1 -1
- package/types/ParticipantStreamDescription.d.ts +1 -1
- package/types/PushData.d.ts +1 -1
- package/types/Room.d.ts +9 -0
- package/types/ScreenCaptureSettings.d.ts +17 -0
- package/types/ServerSettings.d.ts +1 -1
- package/types/SignalingCommand.d.ts +1 -1
- package/types/SignalingMessage.d.ts +2 -2
- package/types/VideoSettings.d.ts +1 -1
- package/types/WaitingHall.d.ts +4 -4
package/calls-sdk.esm.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/calls-sdk v2.6.3-dev.
|
|
3
|
-
* Fri,
|
|
2
|
+
* @vkontakte/calls-sdk v2.6.3-dev.dea4ecd.0
|
|
3
|
+
* Fri, 24 Mar 2023 07:32:54 GMT
|
|
4
4
|
* https://st.mycdn.me/static/callssdk/2-6-3/doc/
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
var Ka=Object.defineProperty,$a=Object.defineProperties;var qa=Object.getOwnPropertyDescriptors;var Cr=Object.getOwnPropertySymbols;var Ja=Object.prototype.hasOwnProperty,za=Object.prototype.propertyIsEnumerable;var Rr=Math.pow,yr=(n,e,t)=>e in n?Ka(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ae=(n,e)=>{for(var t in e||(e={}))Ja.call(e,t)&&yr(n,t,e[t]);if(Cr)for(var t of Cr(e))za.call(e,t)&&yr(n,t,e[t]);return n},et=(n,e)=>$a(n,qa(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 ja from"webrtc-adapter";var wt=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 xt=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 Lt=class extends ae{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e,t){}getNextCommandSequenceNumber(){return 0}};var Pr=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(Pr||{}),tt=Pr;var br=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(br||{}),Ye=br;var Mr=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(Mr||{}),Li=Mr;var Ar=(i=>(i.ADD_PARTICIPANT="ADD_PARTICIPANT",i.RECORD="RECORD",i.MOVIE_SHARE="MOVIE_SHARE",i))(Ar||{}),Ni=Ar;var Dr=(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))(Dr||{}),Ui=Dr;function kr(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}function Or(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 wr=(F=>(F.CAMERA_PERMISSION="camera",F.MIC_PERMISSION="mic",F.CAMERA_ACCESS="cameralock",F.MIC_ACCESS="miclock",F.MIC_NOT_FOUND="nomic",F.SCREEN_PERMISSION="screenpermission",F.SCREEN_ACCESS="screenlock",F.CONNECTION="connection",F.NETWORK="network",F.UNKNOWN="unknown",F.UNSUPPORTED="unsupported",F.SIGNALING_FAILED="signalingfailed",F.API="api",F.AUTH="auth",F))(wr||{}),ne=wr;var xr=(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))(xr||{}),k=xr;var Lr=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SCREEN_SHARING="SCREEN_SHARING",s.MOVIE_SHARING="MOVIE_SHARING",s.AUDIO_SHARING="AUDIO_SHARING",s.ANIMOJI="ANIMOJI",s))(Lr||{}),ue=Lr;var Nr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(Nr||{}),Ue=Nr;var Ur=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(Ur||{}),$=Ur;var Br=(i=>(i.UPDATE="UPDATE",i.REMOVE="REMOVE",i.ACTIVATE="ACTIVATE",i))(Br||{}),Nt=Br;var Vr=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(Vr||{}),Qe=Vr;var Fr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(Fr||{}),Te=Fr;var jr=(U=>(U.TRANSMITTED_DATA="transmitted-data",U.ACCEPTED_CALL="accepted-call",U.HUNGUP="hungup",U.PARTICIPANT_ADDED="participant-added",U.PARTICIPANT_JOINED="participant-joined",U.CLOSED_CONVERSATION="closed-conversation",U.MEDIA_SETTINGS_CHANGED="media-settings-changed",U.PARTICIPANT_STATE_CHANGED="participant-state-changed",U.RATE_CALL_DATA="rate-call-data",U.FEATURE_SET_CHANGED="feature-set-changed",U.TOPOLOGY_CHANGED="topology-changed",U.PRODUCER_UPDATED="producer-updated",U.CONSUMER_ANSWERED="consumer-answered",U.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",U.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",U.SETTINGS_UPDATE="settings-update",U.VIDEO_QUALITY_UPDATE="video-quality-update",U.REGISTERED_PEER="registered-peer",U.SWITCH_MICRO="switch-micro",U.RECORD_STARTED="record-started",U.RECORD_STOPPED="record-stopped",U.REALLOC_CON="realloc-con",U.AUDIO_ACTIVITY="audio-activity",U.SPEAKER_CHANGED="speaker-changed",U.STALLED_ACTIVITY="stalled-activity",U.CHAT_MESSAGE="chat-message",U.CUSTOM_DATA="custom-data",U.ROLES_CHANGED="roles-changed",U.MUTE_PARTICIPANT="mute-participant",U.PIN_PARTICIPANT="pin-participant",U.OPTIONS_CHANGED="options-changed",U.NETWORK_STATUS="network-status",U.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",U.PROMOTE_PARTICIPANT="promote-participant",U.CHAT_ROOM_UPDATED="chat-room-updated",U.PROMOTION_APPROVED="promotion-approved",U.JOIN_LINK_CHANGED="join-link-changed",U.FEEDBACK="feedback",U.MOVIE_UPDATE_NOTIFICATION="movie-update-notification",U.MOVIE_SHARE_INFO="movie-share-info",U.MOVIE_SHARE_STARTED="movie-share-started",U.MOVIE_SHARE_STOPPED="movie-share-stopped",U.ROOM_UPDATED="room-updated",U.ROOMS_UPDATED="rooms-updated",U.ROOM_PARTICIPANTS_UPDATED="room-participants-updated",U.FEATURES_PER_ROLE_CHANGED="features-per-role-changed",U.ASR_STARTED="asr-started",U.ASR_STOPPED="asr-stopped",U))(jr||{}),w=jr;var Hr=(z=>(z.ERROR="callError",z.DEVICES="callDevices",z.CALL_SPEC_ERROR="callSpecError",z.ICE_CONNECTION_STATE="callIceConnectionState",z.ICE_CONNECTION_TYPE="callIceConnectionType",z.ICE_RESTART="callIceRestart",z.PUSH="callPush",z.OUTGOING_CALL="callStart",z.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",z.JOIN_CONVERSATION="callJoinConversation",z.ACCEPTED_OUTGOING="callAcceptedOutgoing",z.ACCEPT_INCOMING="callAcceptIncoming",z.DECLINE_INCOMING="callDeclineIncoming",z.ACCEPT_CONCURRENT="callAcceptConcurrent",z.HANGUP="callHangup",z.MEDIA_STATUS="callMediaStatus",z.DEVICE_CHANGED="callDeviceChanged",z.SOCKET_ACTION="callSocketAction",z.ADD_PARTICIPANT="callAddParticipant",z.REMOVE_PARTICIPANT="callRemoveParticipant",z.POOR_CONNECTION="callPoorConnection",z.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",z.RELAY_POLICY="callForceRelay",z.PAT_ALLOCATED="patAllocate",z.PAT_DEALLOCATED="patDeallocate",z.PAT_ERROR="patError",z.PAT_WAITING_TIME_ERROR="patWaitingTimeError",z.PAT_OUTDATED_RESPONSE="patOutdatedResponse",z))(Hr||{}),T=Hr;var Gr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(Gr||{}),Be=Gr;var Wr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(Wr||{}),Kr=Wr;function $r(n){switch(n){case 1:return"no-available-tracks";default:return"unknown-error"}}var qr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(qr||{}),it=qr;function Ut(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}var Jr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(Jr||{}),te=Jr;var Bi=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 zr=2*1024*1024,Ya=512*1024,Bt=100*1024,Qa=5,Vi="_okcls_logs_session_",Xa=3e4,Yr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=zr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(Vi)!==0)continue;let i=e.getItem(t);if(!i){Zr(t);continue}let r=Xr(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(Bt)}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(Vi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Zr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>zr||this.length>Qa-1||this.size+e>this.available);)this.deleteOldestItem()}};function Qr(){return`${Vi}${Date.now()}`}function Xr(n){return new Blob([n]).size}function Zr(n){try{window.localStorage.removeItem(n)}catch(e){console.error("Failed to remove log from storage",e)}}function Fi(){let n=ct.toString();if(!ye.available||!n)return;let e=Xr(n);ye.cleanup(e);try{window.localStorage.setItem(ei,n)}catch(t){if(console.warn("Failed to write log to storage",t),ye.storageSize=ye.size+e,ye.cleanup(Bt+e),ye.available>=Bt+e){Fi();return}if(e>Bt){ct.bisect(),Fi();return}ye.storageSize=0;return}e>Ya&&(ye.add(ei,e),ei=Qr(),ct.clear(),ye.cleanup(Bt))}function ji(){!ye.available||!ct.length||Fi()}function Za(n=!1){let e=[];try{let r=window.localStorage;for(let s of ye.items){let d=r.getItem(s.key);e.push(d)}let a=ct.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 en(t,i),i}function en(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 ea(n,e){if(!ye.available)return;let t=new Date;ct.push({t:t.getTime(),l:n,d:e,h:t.toLocaleString("ru-RU",{dateStyle:"short",timeStyle:"long"})}),Gi||(Gi=window.setTimeout(()=>{Gi=null,ji()},Xa))}function Hi(){ye||(ye=new Yr,ct=new Bi,ei=Qr(),window.addEventListener("beforeunload",ji))}var ye,ct,ei,Gi=null;window.__VKCallsSDKLogs__=(n=!1)=>(ye||Hi(),ji(),Za(n));import ta from"@vkontakte/libvpx";var Se=(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))(Se||{});var f=class extends xt{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){f._instance||(f._instance=new f(e,t))}static log(e,t,i=!1){f._instance&&f._instance.log(e,t,i)}static logCustom(e,t,i=!1){f._instance&&f._instance.logCustom(e,t,i)}static destroy(){f._instance&&f._instance.destroy(),f._instance=null}};var We=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(","),C=new Blob([e,`exports.default(${E});`],{type:"application/javascript; charset=utf-8"}),M=window.URL.createObjectURL(C);this._worker=new Worker(M),this._worker.onmessage=O=>{switch(O.data.type){case Se.READY:p();break;case Se.ERROR:u(O.data.error);break;case Se.FRAME:t(O.data);break;case Se.DEBUG:c.debug(O.data.message);break;case Se.LOG_ERROR:f.log(T.ERROR,O.data.message);break}},this._sendToWorker(Se.INIT,r,a)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var vt=class extends We{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)},[ta,ta.getUrl])})}decodeFrame(e,t,i,r){let a="ImageBitmap"in window;this._sendToWorker(Se.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 ia=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};function ra(n){return o(this,null,function*(){return new Promise((e,t)=>{let i=new FileReader;i.onload=r=>{e(r.target.result)},i.onerror=t,i.readAsArrayBuffer(n)})})}var Et=":",ti="d",rn=533,Wi="a=fmtp:",an="sps-pps-idr-in-keyframe=1",Ki;(Oi=>{function n(g,m,I,A,b,G=!1,Z=!1){let Ee=/[\r\n]+/,Oe=`\r
|
|
8
|
-
`;if(!m&&!
|
|
9
|
-
`);for(let G of I)if(G.startsWith("a=fingerprint")){let Z=G.split(" ");if(Z.length===2){m=Z[1];break}}if(!m)return BigInt(-1);let A=m.split(":"),b=BigInt(0);for(let G=Math.min(7,A.length-1);G>=0;G--){let Z=BigInt(parseInt(A[G],16));b<<=BigInt(8),b|=Z}return BigInt.asIntN(64,b)}Oi.sdpFingerprint=pe;function K(g){return o(this,null,function*(){return new Promise(m=>window.setTimeout(m,g))})}Oi.delay=K;function ke(g,m,I){let A=[];return g.getSenders().forEach(b=>re(m,b,b.track,I,A)),A}Oi.applySettings=ke;function re(g,m,I,A,b){var G;if(g&&I&&I.kind===oe.video){let Z=I.getSettings();if(Z){let Ee=g.maxBitrateK?g.maxBitrateK*1024:null,Oe=Z.width,He=Z.height,qe=Oe&&He&&g.maxDimension?Math.max(1,Math.max(Oe,He)/g.maxDimension):null,xe=g.maxFramerate?g.maxFramerate:null;if(Oe&&He&&g.maxDimension&&g.maxDimension>Math.max(Oe,He)){let L=Math.round(Oe*He/256),U=(Math.round(L*rn/1e4)+1)*1e4;Ee=Ee===null?U:Math.min(U,Ee)}let Le=g.degradationPreference?g.degradationPreference:"balanced",Ne=A[I.id];if(Ne&&Ne.bitrate===Ee&&Ne.scaleResolutionDownBy===qe&&Ne.maxFramerate===xe&&Ne.degradationPreference===Le){b[I.id]=Ne;return}b[I.id]={bitrate:Ee,scaleResolutionDownBy:qe,maxFramerate:xe,degradationPreference:Le};let Ge=m.getParameters();Ge.encodings||(Ge.encodings=[{}]),Ge.encodings.forEach(L=>{Ee?L.maxBitrate=Ee:delete L.maxBitrate,qe?L.scaleResolutionDownBy=qe:delete L.scaleResolutionDownBy,xe?L.maxFramerate=xe:delete L.maxFramerate}),Ge.degradationPreference=Le,(G=m.setParameters)==null||G.call(m,Ge)}}}Oi.applyVideoTrackSettings=re;function Re(g,m){Array.isArray(m)||(m=[m]);for(let I of m)if(g.includes(I))return!0;return!1}Oi.includesOneOf=Re;function Me(g){var m;return Object.entries(((m=g.participantState)==null?void 0:m.state)||{}).reduce((I,[A,b])=>(g.participantState&&(I[A]={ts:g.participantState.stateUpdateTs[A],state:b}),I),{})}Oi.mapParticipantState=Me;function ot(g){let m=g.map(I=>({uid:I.externalId,mediaSettings:I.mediaSettings,status:I.status,muteStates:I.muteStates,unmuteOptions:I.unmuteOptions,participantState:I.participantState,markers:I.markers,movieShareInfos:I.movieShareInfos}));return l.filterObservers?m.filter(I=>!I.uid.observer):m}Oi.mapSharedParticipants=ot;function Zt(g,m){let I=Object.keys(g),A=Object.keys(m);if(I.length!==A.length)return!1;for(let b of I)if(!A.hasOwnProperty(b)||g[b].state!==m[b].state||g[b].ts!==m[b].ts)return!1;return!0}Oi.isEqualParticipantState=Zt;function Q(g,m){let I=Object.keys(g),A=Object.keys(m);if(I.length!==A.length)return!1;for(let b of I)if(!m.hasOwnProperty(b)||g[b]!==m[b])return!1;return!0}Oi.isObjectsEquals=Q;function Er(g,m){if(g.length!==m.length)return!1;for(let I of g)if(m.indexOf(I)<0)return!1;return!0}Oi.isArraysEquals=Er;function Ai(g){return!Object.keys(g).length}Oi.isEmptyObject=Ai;function Di(g,m){if(!g&&!m)return 0;if(!g||!m)return g?-1:1;return A(m.rank,g.rank)||A(g.ts,m.ts)||I(g,m);function I(b,G){let Z={[te.USER]:0,[te.GROUP]:1},{compositeUserId:Ee,deviceIdx:Oe}=O(b.id),{compositeUserId:He,deviceIdx:qe}=O(G.id),{id:xe,type:Le}=M(Ee),{id:Ne,type:Ge}=M(He);return A(Z[Le],Z[Ge])||A(xe,Ne)||A(Oe,qe)}function A(b,G){return b<G?-1:b===G?0:1}}Oi.participantMarkerCompare=Di;function z(g,m){let I=Object.entries(g).filter(([,A])=>Array.isArray(m)?!m.includes(A):A!==m);return ia(I)}Oi.objectFilterOutValues=z;function ki(g,m,I){let A=I;for(let b in g)!g.hasOwnProperty(b)||(A=m(A,g[b],b));return A}Oi.objectReduce=ki,Oi.setImmediate=(()=>{let g=1,m={},I=null;return typeof MessageChannel!="undefined"&&(I=new MessageChannel,I.port1.onmessage=A=>{let b=A.data;m[b]&&(m[b](),delete m[b])}),function(A){if(I&&document.visibilityState==="hidden"){let G=g;return g=g>=Number.MAX_SAFE_INTEGER?1:g+1,m[G]=A,I.port2.postMessage(G),()=>{m[G]&&delete m[G]}}let b=setTimeout(A,0);return()=>clearTimeout(b)}})()})(Ki||(Ki={}));var v=Ki;function aa(n,e){if(n.isAudioEnabled!==e.isAudioEnabled||n.isVideoEnabled!==e.isVideoEnabled||n.isScreenSharingEnabled!==e.isScreenSharingEnabled||n.isAudioSharingEnabled!==e.isAudioSharingEnabled||n.isAnimojiEnabled!==e.isAnimojiEnabled||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 fe(n){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,isAudioSharingEnabled:!1,isAnimojiEnabled:!1,videoStreams:[]},n||{})}var na=n=>n.stop(),sa=n=>n.getTracks().forEach(na),$i=n=>n.getVideoTracks().forEach(na),oa=n=>n.getVideoTracks()[0].clone();var V=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,V)}};var Pe=(r=>(r.SOURCE_CHANGED="SOURCE_CHANGED",r.TRACK_REPLACED="TRACK_REPLACED",r.SCREEN_STATUS="SCREEN_STATUS",r.ANIMOJI_STATUS="ANIMOJI_STATUS",r))(Pe||{}),oe=(r=>(r.audio="audio",r.video="video",r.screen="screen",r.audioshare="audioshare",r))(oe||{}),qi=class extends ae{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._audioShareTrack=null;this._sendVideoTrack=null;this._mediaSettings=fe();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._sourceBusy=!1;this._animojiEnabled=!1;this._initDeviceChangeListener(),l.audioShare&&(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),a=e.includes(ue.ANIMOJI);if(!P.isBrowserSupported())throw new V(ne.UNSUPPORTED);try{this._stream=yield P.getUserMedia(i,r,t),this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(s=>s.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=r&&this._stream.getAudioTracks().filter(s=>s.enabled).length>0||!1,this._mediaSettings.isAnimojiEnabled=a&&!this._mediaSettings.isVideoEnabled||!1,this._animojiEnabled=a}catch(s){throw new V(s)}})}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}getAnimojiEnabled(){return this._animojiEnabled}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,C=p.findIndex(M=>M.mimeType===u&&M.clockRate===E);if(C>=0){let M=[];M.push(p[C]);for(let O=0;O<p.length;O++)O!==C&&M.push(p[O]);e.getTransceivers().forEach(O=>O.setCodecPreferences(M))}}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":if(this._mediaSettings.isVideoEnabled)return this._stopAndRemoveTrackVideoStreamBackup(),this._changeVideoInput();break;case"audioinput":if(this._mediaSettings.isAudioEnabled)return this._changeAudioInput();break;default:return Promise.reject(ne.UNKNOWN)}})}setVideoStream(e,t){return o(this,null,function*(){return t?this._changeScreen(!1,e):(this._stopAndRemoveTrackVideoStreamBackup(),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(C=>C.deviceId===s)),!t&&u&&(t=!E.find(C=>C.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*(){this._busy();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"),f.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 f.log(T.ERROR,"change_video"),c.warn("Camera change failed",t),t}finally{this._free()}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=oa(e)),t=this._trackVideoStreamBackup.clone(),$i(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),$i(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return o(this,null,function*(){return this._changeAudioInput(e)})}_busy(){if(this._sourceBusy)throw f.log(T.ERROR,"change_device"),c.warn("Device change failed: MediaSource is busy"),new Error("MediaSource is busy");this._sourceBusy=!0}_free(){this._sourceBusy=!1}_changeAudioInput(e=null){return o(this,null,function*(){this._busy();try{if(e=e||(yield P.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),f.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 f.log(T.ERROR,"change_audio"),c.error("Microphone change failed",t),t}finally{this._free()}})}_changeScreen(e,t){return o(this,null,function*(){this._busy();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(f.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}e&&!this._mediaSettings.isAudioSharingEnabled&&c.debug("Audio share requested but not captured"),this._triggerEvent("SCREEN_STATUS",{track:r,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(i){throw f.log(T.ERROR,"screen"),c.warn("Screen capturing failed",i),i}finally{this._free()}})}_disableScreenCapture(){return o(this,null,function*(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),yield this.stopAudioShareTrack(),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))})}disableAudioShare(){return o(this,null,function*(){yield this.stopAudioShareTrack(),this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"audioshare",mediaSettings:this._mediaSettings})})}stopAudioShareTrack(){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=!1}})}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){var t;if(this._stream){if(e==="audioshare")return(t=this._stream.getTracks().find(i=>i.contentHint==="music"))==null?void 0:t.stop();this._stream.getTracks().forEach(i=>{i.kind===e&&i.contentHint!=="music"&&i.stop()})}}_videoEffect(e,t){return o(this,null,function*(){if(!l.videoEffects)return t;try{return f.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&&(sa(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e,t){return o(this,null,function*(){if(e){yield this._changeScreen(t);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();if(this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._animojiEnabled){this._triggerEvent("ANIMOJI_STATUS",!e);return}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})})}toggleAnimojiCapturing(e){this._animojiEnabled=e,this._mediaSettings.isVideoEnabled||this._triggerEvent("ANIMOJI_STATUS",e)}onAnimojiSender(e){this._mediaSettings.isAnimojiEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}onAnimojiStream(e=null){return o(this,null,function*(){var i;if(this._mediaSettings.isVideoEnabled)return;let t=(i=e==null?void 0:e.getVideoTracks())==null?void 0:i[0];t&&(this._stopLocalTrack("video"),yield this._replaceLocalTrack(t))})}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().find(t=>t.contentHint==="");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 Ji="_okcls_",It=(()=>{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 nn(n){let e=It?It.getItem(Ji+n):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function sn(n,e){try{It&&It.setItem(Ji+n,JSON.stringify(e))}catch(t){}}function on(n){It&&It.removeItem(Ji+n)}var zi;(i=>{function n(r){return nn(r)||null}i.get=n;function e(r,a){sn(r,a)}i.set=e;function t(r){on(r)}i.remove=t})(zi||(zi={}));var rt=zi;var dt=null,Yi=null,ii=[],ri=[],ai=[],at=null,nt=null,Qi=null,Xi=!1,Zi=!1,ni,Tt,si,er=null,tr="",oi=[],ir=null,ca=navigator.appVersion,cn=navigator.appName,De=navigator.userAgent,da=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(da||{}),Vt=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;at&&(d=at.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}},la=class extends Vt{constructor(e,t,i){super(!1,!0);this.captureController="CaptureController"in window?new CaptureController:null,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,this.video.displaySurface=l.displaySurface,Ke.browserName()==="Safari"&&Number(Ke.browserVersion())===16&&(delete this.video.width,delete this.video.height),i&&(this.audio={noiseSuppression:!1,echoCancellation:!1,autoGainControl:!1})}getNative(){return Object.assign(super.getNative(),{systemAudio:"exclude",controller:this.captureController})}};function dn(){return o(this,null,function*(){dt=null,yield ci()})}function ln(){dt=null,ci().then(()=>_.onDeviceChange())}function ci(){return o(this,null,function*(){return dt||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Yi&&navigator.mediaDevices.addEventListener&&(Yi=v.throttle(ln,1e3),navigator.mediaDevices.addEventListener("devicechange",Yi)),dt=navigator.mediaDevices.enumerateDevices().then(n=>{ii=n.filter(r=>r.kind==="videoinput"?(r.label&&(Xi=!0),!0):!1),ri=n.filter(r=>r.kind==="audioinput"?(r.label?Zi=!0:Ke.isMobile()&&Ke.browserName()==="Firefox"&&(Zi=Xi),!0):!1),ai=n.filter(r=>r.kind==="audiooutput");let e=rt.get("videoinput"),t=rt.get("audioinput"),i=rt.get("audiooutput");return at=ii.find(r=>r.deviceId===e)||null,nt=ri.find(r=>r.deviceId===t)||null,Qi=ai.find(r=>r.deviceId===i)||ai[0]||null,dt=Promise.resolve(n),n}).catch(()=>(dt=null,[]))))})}function pn(n){if(at&&nt)return;let e=(t,i)=>{var a;let r=(a=i.getSettings())==null?void 0:a.deviceId;return t.find(s=>s.deviceId===r||s.label===i.label)||null};n==null||n.getTracks().forEach(t=>{!at&&t.kind===oe.video?at=e(Ke.getCameras(),t):!nt&&t.kind===oe.audio&&(nt=e(Ke.getMicrophones(),t))})}function di(n,e){return o(this,null,function*(){c.debug("Try to get media",n.getNative());let t=Ke.hasPermissions(n.isVideo());!t&&!e&&_.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(n.getNative());return t||(yield dn()),pn(i),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=n.isVideo()?ne.CAMERA_PERMISSION:ne.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":e=ne.UNKNOWN;break;case"AbortError":case"NotReadableError":e=n.isVideo()?ne.CAMERA_ACCESS:ne.MIC_ACCESS;break}if(n.canSimplify())return di(n.simplify(),e);let r=e||ne.UNKNOWN;throw _.onPermissionsError(r,i),r}})}function un(n){return o(this,null,function*(){var e;c.debug("Try to get screen",n.getNative());try{let t=yield navigator.mediaDevices.getDisplayMedia(n.getNative()),i=t==null?void 0:t.getVideoTracks()[0];if(i&&(c.debug("Got display media track",i.id),i.contentHint="text",n.captureController)){let r=(e=i.getSettings())==null?void 0:e.displaySurface;(r==="browser"||r==="window")&&n.captureController.setFocusBehavior("no-focus-change")}return t}catch(t){switch(t.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw ne.SCREEN_PERMISSION;default:throw ne.SCREEN_ACCESS}}})}function li(){return oi.length||(oi=(()=>{let n,e=!1,t=0,i="0",r=De.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return n=/\brv[ :]+(\d+)/g.exec(De),["IE",n&&n[1]||"Unknown",e,t,i];if(r[1]==="Safari"){if(n=De.match(/\bEdge\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t,i];if(n=De.match(/\bCriOS\/(\d+)/),n)return["Chrome",n[1],!0,Number(n[1]),i];if(n=De.match(/\bFxiOS\/(\d+)/),n)return["Firefox",n[1],!1,t,i];if(n=De.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1],!1,t,i];if(n=De.match(/\bOPT\/(\d+)/),n)return["Opera",n[1],!1,t,i]}if(r[1]==="Chrome"){if(e=!0,t=Number(r[2]),n=De.match(/\bOPR\/(\d+)/),n)return["Opera",n[1]||"Unknown",e,t,i];if(n=De.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1]||"Unknown",e,t,i];if(n=De.match(/\bSferum\/((\d+)(?:\.\d+)*)/),n)return["Sferum",n[1]||"Unknown",e,t,i];if(n=De.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=De.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),n&&n[2]!==void 0&&(i=n[2]),[r[2]?r[1]:cn,n&&n[1]||r[2]||ca,e,t,i]})()),oi}var Ke;(g=>{function n(){return o(this,null,function*(){let m=()=>{K(),document.removeEventListener("click",m),document.removeEventListener("touchstart",m)};return document.addEventListener("click",m),document.addEventListener("touchstart",m),ci()})}g.init=n;function e(){return ii}g.getCameras=e;function t(){return ri}g.getMicrophones=t;function i(){return ai}g.getOutput=i;function r(){return ii.length>0}g.hasCamera=r;function a(){return ri.length>0}g.hasMicrophone=a;function s(){return at}g.getSavedCamera=s;function d(){return nt}g.getSavedMicrophone=d;function p(){return Qi}g.getSavedOutput=p;function u(){return Xi}g.hasCameraPermission=u;function E(){return Zi}g.hasMicrophonePermission=E;function C(m=!1){return E()?r()&&m?u():!0:!1}g.hasPermissions=C;function M(m=!1,I=!0,A=!0){return o(this,null,function*(){let b=a()&&I,G=r()&&m,Z;if(!b&&!G)Z=new MediaStream;else try{Z=yield di(new Vt(b,G))}catch(Ee){Z=new MediaStream}return!Z.getVideoTracks().length&&A&&Z.addTrack(ke()),!Z.getAudioTracks().length&&A&&Z.addTrack(K()),Z})}g.getUserMedia=M;function O(m){return o(this,null,function*(){return un(new la(window.screen.width,window.screen.height,m))})}g.getScreenMedia=O;function F(m,I=!1){return o(this,null,function*(){let A=I?l.videoEffectMaxWidth:l.videoMaxWidth,b=I?l.videoEffectMaxHeight:l.videoMaxHeight;return di(new Vt(!1,m||!0,A,b))})}g.getUserVideo=F;function D(m){return o(this,null,function*(){return di(new Vt(m||!0,!1))})}g.getUserAudio=D;function pe(m,I){return o(this,null,function*(){let b=(yield ci()).find(G=>G.kind===m&&G.deviceId===I);return b?(m==="videoinput"?at=b:m==="audioinput"?nt=b:m==="audiooutput"&&(Qi=b),rt.set(m,I),b):null})}g.saveDeviceId=pe;function K(){if(!si||si.readyState==="ended"){let m=ki(),I=m.createMediaStreamDestination(),A=m.createGain();A.gain.value=1e-5,A.connect(I),A.connect(m.destination);let b=m.createOscillator();b.type="sine",b.frequency.value=0,b.connect(A),b.start(),si=I.stream.getAudioTracks()[0]}return Object.assign(si.clone(),{enabled:!1})}g.getSilentMediaTrack=K;function ke(m=l.videoMinWidth,I=l.videoMinHeight){Tt||(Tt=document.createElement("canvas")),Tt.width=m,Tt.height=I;let A=Tt.getContext("2d");return A.rect(0,0,m,I),A.fillStyle="black",A.fill(),(!ni||ni.readyState==="ended")&&(ni=Tt.captureStream(l.videoFrameRate).getVideoTracks()[0]),Object.assign(ni.clone(),{enabled:!1})}g.getBlackMediaTrack=ke;function re(){if(Ai()==="Edge"&&Number(Di())<70)return!1;try{let m=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&m.RTCPeerConnection&&m.RTCIceCandidate&&m.RTCSessionDescription&&m.HTMLCanvasElement&&m.HTMLCanvasElement.prototype.captureStream&&m.RTCRtpSender&&m.RTCRtpSender.prototype.replaceTrack&&m.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(m){return!1}}g.isBrowserSupported=re;function Re(){return!!navigator.mediaDevices.getDisplayMedia}g.isScreenCapturingSupported=Re;function Me(){let m=g.browserName()==="Safari"&&g.browserVersion()==="15"&&g.browserSubVersion()==="1",I=g.browserName()==="Opera"&&g.os()==="Windows";return m||I}g.isBrokenH264=Me;function ot(){return!(g.baseChromeVersion()&&g.isMobile())}g.canPreferH264=ot;function Zt(){var m;return((m=window.RTCRtpTransceiver)==null?void 0:m.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}g.canPreferRed=Zt;function Q(){return tr||(tr=(()=>{let m={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 I in m)if(m.hasOwnProperty(I)&&m[I].test(De))return I;return"Unknown"})()),tr}g.os=Q;function Er(){return er===null&&(er=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(ca)),er}g.isMobile=Er;function Ai(){return li()[0]}g.browserName=Ai;function Di(){return li()[1]}g.browserVersion=Di;function z(){return li()[3]}g.baseChromeVersion=z;function ki(){return ir||(ir=new(window.AudioContext||window.webkitAudioContext)),ir}g.getAudioContext=ki;function Ir(){return li()[4]}g.browserSubVersion=Ir;function Oi(){return g.baseChromeVersion()>=105&&!g.isMobile()}g.isAudioShareSupported=Oi})(Ke||(Ke={}));var P=Ke;var Xe=class extends We{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(Se.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 mn}from"bit-buffer";var hn=65536,lt=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)%hn!==e.sequence){c.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:a}=lt.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 mn(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 Ct=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 Ft=class extends Ct{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)&&!(P.browserName()==="Firefox"&&Number(P.browserVersion())<60)}};var Rt=class extends Ct{constructor(e){super(e);c.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:oe.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 jt=class extends lt{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];c.debug(`StreamBuilder started for participant [${e}]`),Rt.isBrowserSupported()?this._renderer=new Rt(t):this._renderer=new Ft(t),Xe.isBrowserSupported()?this._decoder=new Xe:this._decoder=new vt;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 Ft.isBrowserSupported()||Rt.isBrowserSupported()}};var Ht=1,_n=1,gn=2,rr=0,pi=11,pa=1,ua=2,ma=4,ha=8;function _a(n,e,t,i,r,a,s){let d=0;e&&(d|=pa),t&&(d|=ua),i&&(d|=ma),s||(d|=ha);let p=new ArrayBuffer(pi),u=new DataView(p);if(u.setUint8(0,Ht),u.setUint16(1,r),u.setUint32(3,n),u.setUint8(7,a?1:0),u.setUint16(8,rr),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 ga(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&pa),u=!!(d&ua),E=!!(d&ma),C=!!(d&ha);if(t!==Ht)throw new Error(`Unexpected protocol version. Got ${t}, expected ${Ht}`);return{timestamp:r,start:p,end:u,keyframe:E,sequence:i,isVP9:a,ssrc:s,eos:C,data:n.slice(pi)}}function fa(n){if(!n||!n.byteLength||n.byteLength!==4)return!1;let e=new DataView(n);return!(e.getUint8(0)!==Ht||e.getUint8(1)!==_n||e.getUint16(2)!==rr)}function Sa(n){if(!n||!n.byteLength||n.byteLength!==10)return null;let e=new DataView(n);if(e.getUint8(0)!==Ht||e.getUint8(1)!==gn||e.getUint16(2)!==rr)return null;let a=e.getUint16(4),s=e.getUint32(6);return{seq:a,ts2:s}}import*as R from"simple-ebml-builder";var fn=Rr(2,15)-1,ar=1,Sn=5,vn=5;var ui=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=ui._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return R.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=R.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)-Sn);r-i>vn&&(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}},Ve=class extends lt{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 R.element(R.ID.EBML,[R.element(R.ID.EBMLVersion,R.number(1)),R.element(R.ID.EBMLReadVersion,R.number(1)),R.element(R.ID.EBMLMaxIDLength,R.number(4)),R.element(R.ID.EBMLMaxSizeLength,R.number(8)),R.element(R.ID.DocType,R.string("webm")),R.element(R.ID.DocTypeVersion,R.number(2)),R.element(R.ID.DocTypeReadVersion,R.number(2))])}static _genSegmentHeader(e,t,i){let r=R.element(R.ID.Info,[R.element(R.ID.TimecodeScale,R.number(1e6)),R.element(R.ID.MuxingApp,R.string("vk-webm-builder")),R.element(R.ID.WritingApp,R.string("vk-webm-builder"))]),a=[R.element(R.ID.PixelWidth,R.number(e)),R.element(R.ID.PixelHeight,R.number(t))],s=R.element(R.ID.Tracks,R.element(R.ID.TrackEntry,[R.element(R.ID.TrackNumber,R.number(ar)),R.element(R.ID.TrackUID,R.number(ar)),R.element(R.ID.TrackType,R.number(1)),R.element(R.ID.FlagLacing,R.number(0)),R.element(R.ID.DefaultDuration,R.number(1e9)),R.element(R.ID.CodecID,R.string(`V_${i.toUpperCase()}`)),R.element(R.ID.Video,a)]));return R.unknownSizeElement(R.ID.Segment,[r,s])}static _genClusterHeader(e){return R.unknownSizeElement(R.ID.Cluster,[R.element(R.ID.Timecode,R.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new ui(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=Ve._genWebmHeader();this._mediaBuffer.append(s);let d=Ve._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(d)}let r=Math.round(i-this._clusterStartTime);if(r>fn&&(this._clusterStartTime=i,r=0),r===0){c.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=Ve._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let a=R.element(R.ID.SimpleBlock,[R.vintEncodedNumber(ar),R.bytes(Ve._intToU16BE(r)),R.number((e.keyframe?1:0)<<7),R.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 yt=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=ga(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&&Ve.isBrowserSupported()?r=new Ve(i,d):r=new jt(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()||vt.isBrowserSupported())&&(jt.isBrowserSupported()||Ve.isBrowserSupported())}};import va from"@vkontakte/libvpx";var En=1e3,Gt=class extends We{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
|
|
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(Se.FRAME,{keyFrame:e})}setBitrate(e,t){this._sendToWorker(Se.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 In=1.2,Ea=.8,Tn=2e3,Cn=8e3,nr=8e3,Rn=16e3,yn=4,Pn=2e3,mi=(i=>(i[i.NONE=0]="NONE",i[i.UP=1]="UP",i[i.DOWN=2]="DOWN",i))(mi||{}),hi=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),C=i;e%100==0&&c.debug(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${mi[a]} tr=${E} br=${i}`);let M=r-this._lastDown;if(a===2&&M>Tn){this._probing&&(this._upPenalty=Math.min(++this._upPenalty,yn),this._probing=!1);let K=Ea*C*1e3;if(K>=this._targetBitrate&&(K=this._targetBitrate*Ea),K=Math.max(K,this._minBitrate),K<this._targetBitrate){let ke=Math.round(K/1e3),re=Math.round(this._upPenalty*nr/1e3);c.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${mi[a]}`),c.log(`#${e}: cc: DOWN delay=${t} bitrate=${C} target=${E} -> newBitrate=${ke} penalty=${re}s`),this._onCongestion(K,!0),this._targetBitrate=K}this._lastDown=r}let O=r-this._lastUp,F=Cn+this._upPenalty*nr;if(a===1&&O>F&&M>F){let K=Math.min(this._targetBitrate*In,this._maxBitrate);if(K>this._targetBitrate){let ke=Math.round(K/1e3),re=Math.round(this._targetBitrate/1e3),Re=Math.round(this._upPenalty*nr/1e3);c.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${mi[a]}`),c.log(`#${e}: cc: UP bitrate=${C} target=${re} -> newBitrate=${ke} penalty=${Re}s`),this._onCongestion(K,!1),this._targetBitrate=K,this._probing=!0,this._lastProbing=r,this._lastUp=r}}let D=r-this._lastProbing;this._probing&&D>Rn&&(this._probing=!1);let pe=r-this._lastDown;this._upPenalty>0&&pe>3*F&&(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>Pn){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 _i=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 bn=65536,Mn=50,An=400,Dn=1e6,kn=3e4,gi=0,bt=class{constructor(e,t,i){this._destroyed=!1;this._needKeyframe=!0;this._frameNum=0;this._feedback=new _i(1024);this._lastSharingStat=Date.now();this._congestionControlEnabled=!1;c.debug("ScreenCaptureSender started"),this.DATA_SIZE=l.consumerScreenDataChannelPacketSize-pi,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 hi(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(),C=this._feedback.getServerBitrateK(2e3);E>0&&this._congestionControl.checkDelay(this._frameNum,E,C),this._requestFrame()}),this._sendSharingStat()}};Pt.isBrowserSupported()?this._encoder=new Pt(e,d,l.screenShareCongestionControl,a):this._encoder=new Gt(e,d,l.screenShareCongestionControl,a),this._datachannel.onmessage=p=>{fa(p.data)&&(c.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0);let u=Sa(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=_a(e,t,i,r,gi,this._encoder.isVP9(),a);return gi=(gi+1)%bn,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(gi,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 Pt.isBrowserSupported()||Gt.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(Dn,Math.round(i*Mn)),a=Math.round(i*An);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>kn){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("apiAuth")&&(se.accessToken=e.apiAuth.accessToken,se.sessionKey=e.apiAuth.sessionKey,se.sessionSecretKey=e.apiAuth.sessionSecretKey),e.hasOwnProperty("api")&&(Object.assign(S._params.api,e.api),delete e.api),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.3-dev.cd0dd8d.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 displaySurface(){return S._params.displaySurface}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 useVmoji(){var e;return((e=S._params.vmoji)==null?void 0:e.isBrowserSupported())||!1}static get vmoji(){return S._params.vmoji}static set vmoji(e){S._params.vmoji=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&&bt.isBrowserSupported()}static get producerScreenDataChannel(){return S._params.producerScreenDataChannel&&S.producerNotificationDataChannel&&yt.isBrowserSupported()}static get asrDataChannel(){return S._params.asrDataChannel&&S.producerNotificationDataChannel}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 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 audioShare(){return P.isAudioShareSupported()&&S._params.audioShare}static get screenShareCongestionControl(){return S._params.screenShareCongestionControl}static get api(){return S._params.api}},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,displaySurface:"monitor",videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,vmoji:null,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},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,asrDataChannel:!1,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,audioShare:!1,screenShareCongestionControl:!1,api:{userIdsByOkBatchedTimeout:1e3}};var Y=(p=>(p.WAITING_HALL="WAITING_HALL",p.WAITING="WAITING",p.CONNECTING="CONNECTING",p.CONNECTED="CONNECTED",p.RECONNECT="RECONNECT",p.ERROR="ERROR",p.HANGUP="HANGUP",p.PERMISSIONS="PERMISSIONS",p))(Y||{});function H(n,...e){let t=l.get(n);t&&setTimeout(t,0,...e)}function me(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}H(n,e,...t)}function be(n){return Object.assign({},n)}function pt(n){return n.slice()}var sr;(js=>{function n(h,y){H("onLocalStream",h,be(y))}js.onLocalStream=n;function e(h,y){H("onScreenStream",h,be(y))}js.onScreenStream=e;function t(h,y){H("onLocalStreamUpdate",be(h),y)}js.onLocalStreamUpdate=t;function i(h){H("onLocalStatus",h)}js.onLocalStatus=i;function r(h,y){me("onRemoteStream",h,y)}js.onRemoteStream=r;function a(h,y){me("onRemoteLive",h,y)}js.onRemoteLive=a;function s(h,y){me("onLocalLive",h,y)}js.onLocalLive=s;function d(h,y){me("onRemoteLiveUpdate",h,y)}js.onRemoteLiveUpdate=d;function p(h,y){me("onLocalLiveUpdate",h,y)}js.onLocalLiveUpdate=p;function u(h,y){me("onRemoteScreenStream",h,y)}js.onRemoteScreenStream=u;function E(h,y,ee,ze,Ot){me("onConversation",h,be(y),be(ee),ze,Ot)}js.onConversation=E;function C(h){h&&H("onConversationParticipantListChunk",h)}js.onConversationParticipantListChunk=C;function M(h,y,ee){me("onRemoteMediaSettings",h,be(y),ee)}js.onRemoteMediaSettings=M;function O(h,y){me("onLocalMediaSettings",h,be(y))}js.onLocalMediaSettings=O;function F(h,y){me("onRemoteSharedMovieInfo",h,be(y))}js.onRemoteSharedMovieInfo=F;function D(h,y){me("onRemoteSharedMovieStoppedInfo",h,be(y))}js.onRemoteSharedMovieStoppedInfo=D;function pe(h,y){me("onLocalSharedMovieInfo",h,be(y))}js.onLocalSharedMovieInfo=pe;function K(h,y){me("onLocalSharedMovieStoppedInfo",h,be(y))}js.onLocalSharedMovieStoppedInfo=K;function ke(h,y){me("onParticipantAdded",h,y)}js.onParticipantAdded=ke;function re(h,y){me("onParticipantJoined",h,y)}js.onParticipantJoined=re;function Re(h,y,ee){me("onRemoteParticipantState",h,be(y),ee)}js.onRemoteParticipantState=Re;function Me(h,y,ee=null){me("onRemoteStatus",h,y,ee)}js.onRemoteStatus=Me;function ot(h,y,ee=null){me("onParticipantStatus",h,y,ee)}js.onParticipantStatus=ot;function Zt(){H("onPermissionsRequested")}js.onPermissionsRequested=Zt;function Q(h,y){H("onPermissionsError",h,y)}js.onPermissionsError=Q;function Er(h,y){me("onRemoteRemoved",h,y)}js.onRemoteRemoved=Er;function Ai(h,y,ee){H("onCallState",h,y,be(ee))}js.onCallState=Ai;function Di(h,y){H("onDeviceSwitched",h,y)}js.onDeviceSwitched=Di;function z(h,y,ee,ze=!1,Ot=!1,wi=null,xi=null,Ha,Tr,Ga=null){let Wa=Tr?pt(Tr):void 0;H("onMuteStates",be(h),pt(y),pt(ee),ze,Ot,wi,xi,Ha,Wa,Ga)}js.onMuteStates=z;function ki(h,y){me("onRolesChanged",h,pt(y))}js.onRolesChanged=ki;function Ir(h){H("onLocalRolesChanged",pt(h))}js.onLocalRolesChanged=Ir;function Oi(h,y,ee){me("onPinnedParticipant",h,y,ee)}js.onPinnedParticipant=Oi;function g(h){H("onLocalPin",h)}js.onLocalPin=g;function m(h){H("onOptionsChanged",pt(h))}js.onOptionsChanged=m;function I(){H("onCallAccepted")}js.onCallAccepted=I;function A(){H("onRateNeeded")}js.onRateNeeded=A;function b(h){me("onSpeakerChanged",h)}js.onSpeakerChanged=b;function G(h){H("onVolumesDetected",pt(h))}js.onVolumesDetected=G;function Z(h,y){H("onLocalVolume",h,y)}js.onLocalVolume=Z;function Ee(h,y){H("onJoinStatus",h,y)}js.onJoinStatus=Ee;function Oe(h,y){H("onHangup",h,y)}js.onHangup=Oe;function He(h){H("onMultipartyChatCreated",be(h))}js.onMultipartyChatCreated=He;function qe(){H("onDeviceChange")}js.onDeviceChange=qe;function xe(h){H("onFingerprintChange",h)}js.onFingerprintChange=xe;function Le(){H("onTokenExpired")}js.onTokenExpired=Le;function Ne(h,y,ee=!1){H("onChatMessage",h,y,ee)}js.onChatMessage=Ne;function Ge(h,y,ee=!1){H("onCustomData",h,y,ee)}js.onCustomData=Ge;function L(h,y,ee,ze,Ot,wi,xi=null){H("onRecordStarted",h,y,ee,ze,Ot,wi,xi)}js.onRecordStarted=L;function U(h=null){H("onRecordStopped",h)}js.onRecordStopped=U;function St(h){H("onLocalNetworkStatusChanged",h)}js.onLocalNetworkStatusChanged=St;function q(h){H("onNetworkStatusChanged",h)}js.onNetworkStatusChanged=q;function ge(h,...y){H("onDebugMessage",h,...y)}js.onDebugMessage=ge;function Ie(h,y){let ee=Object.assign({},h,{memory:y});H("onStatistics",ee)}js.onStatistics=Ie;function ie(){H("onAutoplayError")}js.onAutoplayError=ie;function X(h,y,ee){H("onChatRoomUpdated",h,y,ee)}js.onChatRoomUpdated=X;function ce(h){H("onRemoteMixedAudioStream",h)}js.onRemoteMixedAudioStream=ce;function Je(h){H("onJoinLinkChanged",h)}js.onJoinLinkChanged=Je;function ks(h){H("onRoomsUpdated",h)}js.onRoomsUpdated=ks;function Os(h,y,ee,ze){H("onRoomUpdated",h,y,ee,ze)}js.onRoomUpdated=Os;function ws(h){H("onRoomParticipantsUpdated",h)}js.onRoomParticipantsUpdated=ws;function xs(h){H("onRoomSwitched",h)}js.onRoomSwitched=xs;function Ls(h){H("onRoomStart",h)}js.onRoomStart=Ls;function Ns(h,y=null){H("onFeedback",h,y)}js.onFeedback=Ns;function Us(h){H("onFeaturesPerRoleChanged",h)}js.onFeaturesPerRoleChanged=Us;function Bs(h,y){H("onAsrStarted",h,y)}js.onAsrStarted=Bs;function Vs(){H("onAsrStopped")}js.onAsrStopped=Vs;function Fs(h,y,ee,ze){H("onAsrTranscription",h,y,ee,ze)}js.onAsrTranscription=Fs})(sr||(sr={}));var _=sr;var Ia=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(Ia||{}),or;(re=>{let n="📞",e=(Re,...Me)=>{_.onDebugMessage(Re,...Me)},t=!1,i=(Re,Me)=>(...ot)=>{Re(...ot),ea(Me,ot)},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"),C=e.bind(null,"ERROR");re.debug=p,re.log=u,re.warn=E,re.error=C;function pe(){return t}re.enabled=pe;function K(Re){t=Re,l.debugLog&&Hi(),Re?(re.debug=l.debugLog?i(r,"DEBUG"):r,re.log=l.debugLog?i(a,"LOG"):a,re.warn=l.debugLog?i(s,"WARN"):s,re.error=l.debugLog?i(d,"ERROR"):d):(re.debug=l.debugLog?i(p,"DEBUG"):p,re.log=l.debugLog?i(u,"LOG"):u,re.warn=l.debugLog?i(E,"WARN"):E,re.error=l.debugLog?i(C,"ERROR"):C)}re.toggle=K;function ke(Re,...Me){switch(Re){case"DEBUG":re.debug(...Me);break;case"LOG":re.log(...Me);break;case"WARN":re.warn(...Me);break;case"ERROR":re.error(...Me);break}}re.send=ke})(or||(or={}));var c=or;var Mt=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(Mt||{}),ve;(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})(ve||(ve={}));var he;(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},ve.fromSignaling(a))}r.fromSignaling=t;function i(a){return a&&typeof a=="object"?a.deviceIdx:0}r.getDeviceIdx=i})(he||(he={}));var On="kf";function Wt(n){return n.stopStream}function cr(n){return n.keyFrameRequested}function Ta(n){if(Wt(n))return"ss";if(cr(n))return On;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 Ce=(s=>(s.CAMERA="CAMERA",s.SCREEN="SCREEN",s.STREAM="STREAM",s.MOVIE="MOVIE",s.AUDIOSHARE="AUDIOSHARE",s.ANIMOJI="ANIMOJI",s))(Ce||{}),Ca="s",Ra="m";function Fe(n){return n.participantId+(n.mediaType?Et+Ca+n.mediaType:"")+(n.streamName?Et+Ra+n.streamName:"")}function Kt(n){let e=n.split(Et),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 Ca:i=wn(d.slice(1));break;case Ra:r=d.slice(1);break;case ti: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 wn(n){for(let e of Object.keys(Ce))if(e===n)return Ce[e];return null}function dr(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 fi(n,e){return!(!dr(n.camera,e.camera)||!dr(n.screenSharing,e.screenSharing))}function lr(n,e){return{camera:Object.assign({},n.camera,e.camera),screenSharing:Object.assign({},n.screenSharing,e.screenSharing)}}function ya(n){try{return btoa(JSON.stringify(n))}catch(e){c.warn("WaitingParticipant: failed convert to string",n,e)}return null}function Pa(n){try{return JSON.parse(atob(n))}catch(e){c.warn("WaitingParticipant: failed convert from string",n,e)}return null}var At=(n,e)=>v.objectReduce(n,(t,i,r)=>(i===e&&t.push(r),t),[]);var $t=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,f.log(T.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,f.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"),f.log(T.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),f.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===oe.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Si=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"),_.onAutoplayError()},r=d=>{t.srcObject=new MediaStream([d]),t.load();let p=t.play();p&&p.catch(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 f.log(T.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var xn=90,Ln=3,vi=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}),_.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>xn?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Ln)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var Nn=44100,qt=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=Nn/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 Ei=class extends ae{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&_.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,l.voiceParams.interval)};this._interval=window.setTimeout(t,l.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,Pe.SOURCE_CHANGED,r=>{r.kind===oe.audio&&r.contentHint===""&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks().find(i=>i.contentHint==="");t&&(this._track=t.clone(),this._detector=new qt("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 ba=(s=>(s.producerNotification="producerNotification",s.producerCommand="producerCommand",s.consumerScreenShare="consumerScreenShare",s.producerScreenShare="producerScreenShare",s.asr="asr",s.animoji="animoji",s))(ba||{}),Ze=ba;var Ma="videochat-epi",Un=5e3,Bn=3e4,ut=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,B.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Ma)||"",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+Un<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),l.callStatReportEnabled&&this._previousCallStatReportTimestamp+Bn<=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(Ma,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}f.logCustom("callStat",i),c.log("Sent call stats",i),this._previousCallStatReport=t}};var Vn=1e3;function _e(n,e,t=0){return e in n&&n[e]?n[e]:t}function Aa(...n){return e=>{for(let t of n)if(t(e))return!0;return!1}}function st(n,e){return t=>t[n]===e}function Fn(n){return(e,t)=>e[n]-t[n]}function Ii(n,e){return e.reduce((t,i)=>(t[i[n]]=i,t),{})}function jn(n){let e={},t=[];for(let i of n)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Hn(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function pr(n){return Object.keys(n).filter(e=>n[e]!==void 0).map(e=>[e,n[e]]).reduce((e,t)=>(e[t[0]]=Hn(t[1])?pr(t[1]):t[1],e),{})}function Gn(n){let e=[];for(let t of n)t.forEach(i=>e.push(i));return e}function Wn(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(Gn).then(jn)})}function Kn(n){let e=n.filter(st("type","candidate-pair")).sort(Fn("priority")).find(Aa(st("nominated",!0),st("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(st("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(st("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}})),pr(t)}function $n(n,e){let t=Ii("id",n),i=n.filter(Aa(st("type","inbound-rtp"),st("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(st("type","track"));r=Ii("trackIdentifier",a)}return i.map(a=>{let s=Number(a.ssrc),d=a.mediaType||a.kind,p=a.trackId,u=a.type,E=a.codecId;if(P.browserName()==="Safari"){let M=/^.+_([\d]+)$/.exec(a.id);if(M&&(s=parseInt(M[1],10)),d=a.id.indexOf("Audio")>0?"audio":"video",e[s]){let O=d+"-"+e[s];r[O]&&(p=r[O].id)}}if(!u||!s||!d)return null;let C={ssrc:s,type:u,kind:d,bytesReceived:_e(a,"bytesReceived"),bytesSent:_e(a,"bytesSent"),jitter:_e(a,"jitter"),packetsLost:_e(a,"packetsLost"),packetsReceived:_e(a,"packetsReceived"),packetsSent:_e(a,"packetsSent"),fractionLost:_e(a,"fractionLost"),pliCount:_e(a,"pliCount"),firCount:_e(a,"firCount"),nackCount:_e(a,"nackCount"),userId:e[s]};if(d==="video"){let M=_e(a,"framesDecoded"),O=_e(a,"totalInterFrameDelay"),F=_e(a,"totalSquaredInterFrameDelay");C.interframeDelayVariance=(F-O*O/M)/M}if(d==="audio"&&(C.totalSamplesReceived=_e(a,"totalSamplesReceived"),C.concealedSamples=_e(a,"concealedSamples"),C.insertedSamplesForDeceleration=_e(a,"insertedSamplesForDeceleration"),C.removedSamplesForAcceleration=_e(a,"removedSamplesForAcceleration"),C.silentConcealedSamples=_e(a,"silentConcealedSamples"),C.concealmentEvents=_e(a,"concealmentEvents"),C.totalAudioEnergy=_e(a,"totalAudioEnergy")),E&&t[E]){let M=t[E];C.clockRate=M.clockRate,C.mimeType=M.mimeType}if(p&&t[p]){let M=t[p];C.frameHeight=M.frameHeight,C.frameWidth=M.frameWidth,C.framesDecoded=M.framesDecoded,C.framesReceived=M.framesReceived,C.framesDropped=M.framesDropped}return pr(C)}).filter(a=>!!a)}function qn(n,e){if(!e||!e.rtps||!n.rtps)return n;let t=Ii("ssrc",n.rtps),i=Ii("ssrc",e.rtps),r=(n.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(a=>{let s=t[a],d=i[a];if(!(!s||!d)){if(s.bytesReceived&&s.bytesReceived>d.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-d.bytesReceived)/r)),s.bytesSent&&s.bytesSent>d.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-d.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>d.packetsReceived||s.packetsLost>d.packetsLost){let p=s.packetsLost-d.packetsLost,u=s.packetsReceived-d.packetsReceived;s.packetLoss=parseFloat((100*p/(p+u)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&d.framesDropped&&s.framesDropped>d.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-d.framesDropped)/r).toFixed(0)))}}),n}function Jt(i,r){return o(this,arguments,function*(n,e,t={}){let a=yield Wn(n),s={timestamp:Date.now(),transport:Kn(a),rtps:$n(a,t)};return e?qn(s,e):(yield v.delay(Vn),Jt(n,s,t))})}var Ti=.8,mt=class extends ae{constructor(e,t,i,r,a){super();this._remoteSDP={};this._remoteCandidates={};this._state=j.IDLE;this._animojiDataChannel=null;this._animojiReceiver=null;this._animojiSender=null;this._animojiSvgDataByParticipantId={};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 ut(this,i,!0),this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Pe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Pe.SOURCE_CHANGED,this._applySettings.bind(this)),this.subscribe(this._mediaSource,Pe.ANIMOJI_STATUS,this._onAnimojiStatus.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){f.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===j.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==j.IDLE&&e!==j.CLOSED&&e!==j.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,l.useVmoji&&this._createDataChannel(this._pc,Ze.animoji,i=>{this._animojiDataChannel=i,this._animojiDataChannel.binaryType="arraybuffer",this._createAnimojiReceiver(),this._mediaSource.getAnimojiEnabled()&&this._createAnimojiSender()}),!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,l.p2pAudioRed),this._applySettings()}catch(i){f.log(T.ERROR,"addTrack-direct"),c.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(j.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){fi(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._removeAnimojiReceiver(),this._removeAnimojiSender(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(B.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(c.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(j.FAILED)):(c.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(j.CLOSED)),this._triggerEvent(B.PEER_CONNECTION_CLOSED)}setAnimojiSvg(e,t){if(this._animojiReceiver){this._animojiReceiver.setParticipantSvg(e,t);return}this._animojiSvgDataByParticipantId[e]=t}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(B.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,a;switch(e.notification){case w.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case w.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case w.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((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 f.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 f.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(B.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(B.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return o(this,null,function*(){e.candidate&&this._signaling.ready&&(c.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(c.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>o(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(c.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===j.IDLE||e===j.OPENED?this._setState(j.CONNECTING):this._setState(j.RECONNECTING);break}}_onConnectionStateChange(){switch(c.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),f.log(T.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(j.CONNECTED),this._stopReconnection(),v.getPeerConnectionHostInfo(this._pc).then(e=>{e&&f.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(j.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?(f.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}),f.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}),f.log(T.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=mt._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}),f.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}),f.log(T.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=mt._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}),f.log(T.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!P.baseChromeVersion();return e.sdp=v.patchLocalSDP(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}),f.log(T.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_onAnimojiStatus(e){e?this._createAnimojiSender():this._removeAnimojiSender(),this._mediaSource.onAnimojiSender(e)}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Jt(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(B.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=K=>K.rtt<=this._networkLimits.goodNet.rtt&&K.loss<=this._networkLimits.goodNet.loss,i=K=>K.rtt>=this._networkLimits.badNet.rtt||K.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,a=e.inbound.rtps.reduce((K,ke)=>Math.max(K,ke.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-Ti)+r*Ti,loss:this._lastNetworkStat.loss*(1-Ti)+a*Ti},d=i(s),p=t(s),u=i(this._remoteNetworkStat),E=t(this._remoteNetworkStat),C=i(this._lastNetworkStat),M=t(this._lastNetworkStat),D=d||u?.2:p&&E?1:0,pe=Date.now();if((C!==d||M!==p||pe-this._lastNetworkStat.date>l.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(K=>{c.warn("Unable to send [bad-net]",K)})),D){let K={};K[this._participantId]=K[""]=D,this._triggerEvent(B.NETWORK_STATUS,K)}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:(_.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=v.applySettings(this._pc,e,this._prevConsumerSettings)),this._animojiSender){let i=this._mediaSource.getStream();i&&this._animojiSender.setStream(i)}}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{negotiated:!0,id:1});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}]`)}}_createAnimojiReceiver(){!l.useVmoji||!this._animojiDataChannel||!this._participantId||(this._animojiReceiver&&this._removeAnimojiReceiver(),this._animojiReceiver=new l.vmoji.AnimojiReceiver(this._animojiDataChannel,this._participantId,(e,t)=>{this._triggerEvent(B.ANIMOJI_STREAM,e,t)},e=>{this._triggerEvent(B.ANIMOJI_STREAM,e,null)}),Object.entries(this._animojiSvgDataByParticipantId).forEach(([e,t])=>{this._animojiReceiver.setParticipantSvg(e,t),delete this._animojiSvgDataByParticipantId[e]}))}_removeAnimojiReceiver(){var e;(e=this._animojiReceiver)==null||e.destroy(),this._animojiReceiver=null}_createAnimojiSender(){if(!l.useVmoji||!this._animojiDataChannel)return;let e=this._mediaSource.getStream();e&&(this._animojiSender&&this._removeAnimojiSender(),this._animojiSender=new l.vmoji.AnimojiSender(this._animojiDataChannel,e))}_removeAnimojiSender(){var e;(e=this._animojiSender)==null||e.destroy(),this._animojiSender=null}};var Jn=16,zt=class{constructor(e,t,i){c.debug("AsrReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._asrCallback=i,this._textDecoder=new TextDecoder,this._datachannel.onmessage=r=>this._onDataChannelMessage(r.data)}static parse(e){let t=new DataView(e),i=t.getUint8(0),r=t.getUint8(1);if(r!==0)throw new Error(`Unsupported message type. Message type: ${r}`);let a=t.getUint16(2),s=t.getUint32(4),d=t.getUint32(8),p=t.getUint32(12);if(i!==1)throw new Error(`Unexpected protocol version. Got ${i}, expected 1`);return{sequence:a,ssrc:s,timestamp:d,duration:p,data:e.slice(Jn)}}_onDataChannelMessage(e){var a,s;let t=zt.parse(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}let r={participantId:i,text:this._textDecoder.decode(t.data),timestamp:t.timestamp,duration:t.duration};this._asrCallback(r)}destroy(){this._datachannel.onmessage=null}};import{decode as ht}from"messagepack";var ur=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=ht(r);return Object.entries(d).forEach(([F,D])=>{let pe=Kt(F);this.streamDescriptionByCompactId.set(D,pe),this.compactIdByStreamDescription.set(F,D)}),null;case 2:case 4:let p=ht(r),u=[];for(let F of p){let D=this.getStreamDescription(F);D&&u.push(D.participantId)}return i===2?{type:"notification",notification:w.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:w.STALLED_ACTIVITY,stalledParticipants:u};case 3:let E=ht(r);return{type:"notification",notification:w.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(E))==null?void 0:a.participantId};case 5:let C=ht(r);return{type:"notification",notification:w.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:C[0],maxDimension:C[1]}};case 6:let M=ht(r),O={};for(let[F,D]of Object.entries(M)){let pe=(s=this.getStreamDescription(Number(F)))==null?void 0:s.participantId;pe&&(O[pe]=D/100)}return{type:"notification",notification:w.NETWORK_STATUS,statuses:O};case 7:return this._createParticipantSourcesUpdateNotification(r);case 8:{let D=ht(r).map(pe=>{var Q;let[K,ke,re,Re,Me,ot,Zt]=pe;return{participantId:(Q=this.getStreamDescription(K))==null?void 0:Q.participantId,gain:ke,pause:re,offset:Re,mute:Me,liveStatus:ot,startTimeMs:Zt}});return{type:"notification",notification:w.MOVIE_UPDATE_NOTIFICATION,data:D}}default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=ht(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=Be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,C=d?d>>>0:null;i.push({participantStreamDescription:u,streamId:E,rtpTimestamp:C,sequenceNumber:p})}return{type:"notification",notification:w.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var zn=90,Yn=4294967295,je=class extends ae{constructor(e,t,i,r={}){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._asr=null;this._animojiDataChannel=null;this._animojiReceiver=null;this._animojiSender=null;this._animojiSvgDataByParticipantId={};this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=j.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._asrTrack=null;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.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Pe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Pe.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,Pe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this.subscribe(this._mediaSource,Pe.ANIMOJI_STATUS,this._onAnimojiStatus.bind(this)),this._perfStatReporter=new ut(this,e),this._serverSettings=i,this._animojiSvgDataByParticipantId=r,c.debug("ServerTransport: Created")}getState(){return this._state||j.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==j.IDLE&&e!==j.CLOSED&&e!==j.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(j.FAILED)):(c.debug("ServerTransport: Closed"),this._setState(j.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){fi(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}setAnimojiSvg(e,t){if(this._animojiReceiver){this._animojiReceiver.setParticipantSvg(e,t);return}this._animojiSvgDataByParticipantId[e]=t}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeAsrTrack(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._removeAnimojiReceiver(),this._removeAnimojiSender(),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,je._closeDataChannel(this._producerNotification),je._closeDataChannel(this._producerCommand),je._closeDataChannel(this._producerScreen),je._closeDataChannel(this._consumerScreen),je._closeDataChannel(this._asr),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(B.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let a=r.readyState;a==="open"?(c.debug(`[${t}] data channel opened`),r.onerror=s=>{c.error(`[${t}] data channel error`,s)},i(r)):c.error(`[${t}] data channel open failed, state [${a}]`)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection"),this._pc=new RTCPeerConnection({},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=v.throttle(t=>{this._pc&&this._onConnectionStateChange(this._pc,t)},500),this._pc.onsignalingstatechange=je._onSignalingStateChange.bind(this,this._pc),this._participantIdRegistry=new ur,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),l.producerNotificationDataChannel&&this._createDataChannel(this._pc,Ze.producerNotification,t=>{this._producerNotification=t,this._producerNotification.binaryType="arraybuffer",this._signaling.setProducerNotificationDataChannel(t)}),l.producerCommandDataChannel&&(this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,Ze.producerCommand,t=>{this._producerCommand=t,this._signaling.setProducerCommandDataChannel(t)})),l.producerScreenDataChannel&&this._createDataChannel(this._pc,Ze.producerScreenShare,t=>{this._producerScreen=t,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()}),l.asrDataChannel&&this._createDataChannel(this._pc,Ze.asr,t=>{this._asr=t,this._asr.binaryType="arraybuffer",this._removeAsrTrack(),this._asrTrack=new zt(t,this._participantIdRegistry,i=>{this._onAsrTranscription(i)}),this._signaling.setAsrDataChannel(t)}),l.useVmoji&&this._createDataChannel(this._pc,Ze.animoji,t=>{this._animojiDataChannel=t,this._animojiDataChannel.binaryType="arraybuffer",this._createAnimojiReceiver(),this._mediaSource.getAnimojiEnabled()&&this._createAnimojiSender()}),this._newAudioShareTrack=this._mediaSource.getAudioShareTrack();try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,l.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(t){c.error("ServerTransport: Unable to add media source tracks",t),f.log(T.ERROR,"addTrack-single"),this.close(t);return}l.consumerScreenDataChannel&&this._createDataChannel(this._pc,Ze.consumerScreenShare,t=>{this._consumerScreen=t,this._consumerScreen.binaryType="arraybuffer";let i=this._mediaSource.getScreenTrack();i&&this._createCaptureSender(i)}),e||this._allocateConsumer(),this._setState(j.OPENED),this._startStatInterval(),this._startSettingsInterval()}_removeAsrTrack(){var e;(e=this._asrTrack)==null||e.destroy(),this._asrTrack=null}_reconnect(){this.getState()!==j.OPENED&&(this._setState(j.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(B.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(B.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(B.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(B.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
|
|
12
|
-
`).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Be.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 bt(e,this._consumerScreen,this._signaling))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!l.producerScreenDataChannel||!this._producerScreen||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new yt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(B.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(B.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_createAnimojiSender(){if(!l.useVmoji||!this._animojiDataChannel)return;let e=this._mediaSource.getStream();e&&(this._animojiSender&&this._removeAnimojiSender(),this._animojiSender=new l.vmoji.AnimojiSender(this._animojiDataChannel,e))}_removeAnimojiSender(){var e;(e=this._animojiSender)==null||e.destroy(),this._animojiSender=null}_createAnimojiReceiver(){!l.useVmoji||!this._animojiDataChannel||!this._participantIdRegistry||(this._animojiReceiver&&this._removeAnimojiReceiver(),this._animojiReceiver=new l.vmoji.AnimojiReceiver(this._animojiDataChannel,this._participantIdRegistry,(e,t)=>{this._triggerEvent(B.ANIMOJI_STREAM,e,t)},e=>{this._triggerEvent(B.ANIMOJI_STREAM,e,null)}),Object.entries(this._animojiSvgDataByParticipantId).forEach(([e,t])=>{this._animojiReceiver.setParticipantSvg(e,t),delete this._animojiSvgDataByParticipantId[e]}))}_removeAnimojiReceiver(){var e;(e=this._animojiReceiver)==null||e.destroy(),this._animojiReceiver=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!==oe.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}if(this._animojiSender){let t=this._mediaSource.getStream();t&&this._animojiSender.setStream(t)}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_onAnimojiStatus(e){e?this._createAnimojiSender():this._removeAnimojiSender(),this._mediaSource.onAnimojiSender(e)}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(B.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,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 Jt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(B.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=Be.AUDIO_MIX,r=this._statBytes[i],a=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(a=!0),r.stalled!==a&&this._triggerEvent(B.REMOTE_ALL_STALL,a)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:a}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:ut.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,asrDataChannelVersion:l.asrDataChannel?1:0,animojiDataChannelVersion:l.useVmoji?1:0,onDemandTracks:!0,unifiedPlan:!0,singleSession:!0,videoTracksCount:l.videoTracksCount,red:l.serverAudioRed,audioShare:l.audioShare};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:v.patchRemoteSDP(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),f.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),f.log(T.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=v.patchLocalSDP(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),f.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),f.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),f.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 w.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case w.REALLOC_CON:this._reconnect();break;case w.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case w.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case w.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case w.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onAsrTranscription(e){this._triggerEvent(B.ASR_TRANSCRIPTION,e)}_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(B.REMOTE_TRACK_REMOVED,i.id,i,a.track)}),i.getTracks().find(a=>a.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(B.REMOTE_TRACK_ADDED,i.id,i,t.track)):c.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){c.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(c.debug("[single] connection state changed",{state:e.connectionState},t),f.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===j.IDLE||i===j.OPENED?this._setState(j.CONNECTING):e.iceConnectionState==="checking"&&this._setState(j.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(j.RECONNECTING);break;case"connected":this._setState(j.CONNECTED),v.getPeerConnectionHostInfo(e).then(r=>{r&&f.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),f.log(T.ERROR,"replaceTrack-single")}),i=!0)}),!i&&e.kind===oe.audio&&e.contentHint==="music"&&(this._newAudioShareTrack=e)}this._applyConsumerSettings()}getStreamWaitingTimeMs(e,t){if(!this._pc)return f.log(T.PAT_WAITING_TIME_ERROR,"noConnection"),c.error("Cannot get stream waiting time, peer connection is not initialized"),0;if(!RTCRtpReceiver.prototype.getSynchronizationSources)return f.log(T.PAT_WAITING_TIME_ERROR,"oldBrowser"),c.error("Cannot get stream waiting time, RTCRtpReceiver.getSynchronizationSources is not supported"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return f.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 f.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&Yn,p=Math.ceil(d/zn);return Math.min(100,Math.max(0,p))}};var B=(D=>(D.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",D.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",D.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",D.REMOTE_ALL_STALL="REMOTE_ALL_STALL",D.REMOTE_DATA_STATS="REMOTE_DATA_STATS",D.STATE_CHANGED="STATE_CHANGED",D.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",D.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",D.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",D.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",D.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",D.NETWORK_STATUS="NETWORK_STATUS",D.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",D.ASR_TRANSCRIPTION="ASR_TRANSCRIPTION",D.ANIMOJI_STREAM="ANIMOJI_STREAM",D))(B||{}),j=(d=>(d.IDLE="IDLE",d.OPENED="OPENED",d.CONNECTING="CONNECTING",d.RECONNECTING="RECONNECTING",d.CONNECTED="CONNECTED",d.CLOSED="CLOSED",d.FAILED="FAILED",d))(j||{}),de=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(de||{}),mr=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._animojiSvgDataByParticipantId={};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(c.log(`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.log("Trying open participant",{participantIds: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()}setAnimojiSvg(e,t){if(this._topology==="DIRECT"&&this._directTransport)if(this._directTransport.setAnimojiSvg(e,t),t.svg instanceof ArrayBuffer){let i=new Uint8Array(t.svg.byteLength);i.set(new Uint8Array(t.svg)),this._animojiSvgDataByParticipantId[e]=et(Ae({userId:""},t),{svg:i.buffer})}else this._animojiSvgDataByParticipantId[e]=t;else this._topology==="SERVER"&&this._serverTransport&&this._serverTransport.setAnimojiSvg(e,t)}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===w.TOPOLOGY_CHANGED)return this._onTopologyChanged(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),f.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 mt(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.addEventListener("ANIMOJI_STREAM",this._onAnimojiStream.bind(this))),i}_createServerTransport(){let e=new je(this._signaling,this._mediaSource,this._serverSettings,this._animojiSvgDataByParticipantId);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.addEventListener("ASR_TRANSCRIPTION",this._onAsrTranscription.bind(this)),e.addEventListener("ANIMOJI_STREAM",this._onAnimojiStream.bind(this))),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)}_onAsrTranscription(e){this._triggerEvent("ASR_TRANSCRIPTION",e)}_onAnimojiStream(e,t){this._triggerEvent("ANIMOJI_STREAM",e,t)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(f.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):(f.log(T.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var _t=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(_t||{}),hr=class extends ae{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,B.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,B.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,B.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,B.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===oe.audio&&((r=this._detector)==null||r.destroy(),this._detector=new qt(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===oe.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===Be.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e===de.DIRECT&&(this._activeParticipants=null)}};var _r=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(_r||{}),gr=class extends ae{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i===de.SERVER,this.subscribe(e,_t.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,B.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,B.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let a=e[r].smoothed;a>t&&a>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 Ci=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,B.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,_t.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===j.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===j.FAILED&&this._connectionTimeout&&(c.warn("Transport failed, send callSpecError"),f.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!==j.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(c.warn("There is not connected transport, send callSpecError"),f.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),f.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,Xn=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=$.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;f.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),f.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new Si,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 f.log(T.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new V(k.FAILED);W._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let p=this._mediaSource.getMediaSettings();t===Ye.CHAT||e.length>1?this._logWithMediaSettings(T.OUTGOING_MULTIPARTY_CALL,p):this._logWithMediaSettings(T.OUTGOING_CALL,p);let u=yield this._startConversation(e,t,tt.OUTGOING,i,r,a,s,d);if(!this._conversation)throw new V(k.UNKNOWN_ERROR);if(this._participantState=$.ACCEPTED,this._signaling.changeMediaSettings(p),yield this._processConnection(u),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),W._delayedHangup)throw new V(k.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let E=Object.values(this._participants),C;return l.batchParticipantsOnStart&&(C=v.mapSharedParticipants(E)),yield this._processConnectionSharedMovieInfo(u),_.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),_.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),C),this._onConversationParticipantListChunk(u),_.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),W._current=this,this._conversation.concurrent?yield this._acceptConcurrent():l.batchParticipantsOnStart||this._setParticipantsStatus(E,Y.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 f.log(T.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new V(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 V(k.UNKNOWN_ERROR);return this._conversation.observer=i,_.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(c.log("In waiting hall"),W._current=this,W._activationMutex=!1,this._signaling.readyToSend(),_.onLocalStatus(Y.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,p;c.debug("Join conversation part 2"),W._activationMutex=!0;try{if(this._participantState=$.ACCEPTED,!this._conversation||!this._mediaSource)throw new V(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 V(k.CANCELED);let u=Object.values(this._participants),E;l.batchParticipantsOnStart&&(E=v.mapSharedParticipants(u.filter(O=>!O.isInRoom)));let C=[];if((i=(t=e==null?void 0:e.rooms)==null?void 0:t.rooms)==null?void 0:i.length)for(let O of e.rooms.rooms)C.push({id:O.id,name:O.name,participantCount:O.participantCount,participantIds:yield Promise.all(((a=(r=O==null?void 0:O.participantIds)==null?void 0:r.map)==null?void 0:a.call(r,this._getExternalIdByParticipantId.bind(this)))||[]),participants:((s=O==null?void 0:O.participants)==null?void 0:s.participants)?this._participantListChunkToExternalChunk(O.participants):void 0,active:O.active,muteStates:O.muteStates});let M=(p=(d=e==null?void 0:e.rooms)==null?void 0:d.roomId)!=null?p:null;return yield this._processConnectionSharedMovieInfo(e),_.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),E,{rooms:C,roomId:M}),this._onConversationParticipantListChunk(e),_.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),W._current=this,l.batchParticipantsOnStart||this._setParticipantsStatus(u,Y.WAITING),this._openTransport(u,!1),this._conversation}catch(u){throw this._close(u,"Unable to join conversation"),u}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 V(k.REJECTED);W._activationMutex=!0;try{let a=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new V(k.UNKNOWN_ERROR);if(!a.conversation.participants.find(d=>{var p;return d.state===$.CALLED&&d.id===((p=this._conversation)==null?void 0:p.userId)}))throw c.log("Push rejected (there is an active call)"),f.log(T.PUSH,"rejected"),new V(k.REJECTED);if(yield this._processConnection(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),f.log(T.PUSH,"accepted"),W._current=this,W._delayedHangup)throw new V(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(Ui.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 V(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()),_.onCallAccepted(),this._state="ACTIVE",this._participantState=$.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 f.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 V(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=$.ACCEPTED;let r=Object.values(this._participants),a;if(l.batchParticipantsOnStart&&(a=v.mapSharedParticipants(r)),_.onCallAccepted(),_.onLocalStream(this._mediaSource.getStream(),i),_.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),a),l.useParticipantListChunk){let p=yield this._getInitialParticiapntListChunk();(t=p==null?void 0:p.participants)==null||t.forEach(u=>{let E=v.composeId(u),C=this._participants[E];C&&(C.movieShareInfos=u.movieShareInfos)}),this._onConversationParticipantListChunk({participants:p})}_.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let s=At(this._getMuteStatesForCurrentRoom(),Ue.MUTE),d=At(this._getMuteStatesForCurrentRoom(),Ue.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,Y.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 f.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=$.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(k.REJECTED)),this._close(new V(k.REJECTED))})}hangup(){return o(this,null,function*(){c.debug("Hangup");let e=this._state==="ACTIVE"?k.HUNGUP:k.CANCELED;f.log(T.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new V(e))):_.onHangup(new V(k.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new V(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===$.CALLED||a.state===$.ACCEPTED)&&(this._transport.isAllocated(a.id)||this._transport.allocate(a.id,t)),a.state===$.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):f.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){_.onHangup(e,i),this.destroy();return}if(e.hangup===k.HUNGUP&&(!e.remote||this._participantState===$.CALLED)){_.onHangup(e,i),this.destroy();return}if(e.hangup===k.MISSED&&!e.remote){_.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=$.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),f.destroy(),this._conversation=null,this._myLastRequestedLayouts={},W._current=null,W._delayedHangup=!1,_.onHangup(e||new V(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(),f.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),C=yield this._api.startConversation(u,e,t,E,a,s,d,{onlyAdminCanShareMovie:p});c.debug("Api.startConversation",C);let M=yield this._getConversationParams(C.id);C.endpoint=this._addGeoParamsToEndpoint(C.endpoint,M);let O=yield this._connectSignaling(Qe.START,C);return yield this._setConversation(C,O,i),O})}_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 V(k.UNKNOWN_ERROR);c.debug("Api.joinConversation",u),yield this._getConversationParams(u.id);let E=yield this._connectSignaling(Qe.JOIN,u);return yield this._setConversation(u,E,tt.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 V(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(Qe.ACCEPT,u);return W._current&&(W._current._participantState===$.ACCEPTED||W._current._participantState===$.CALLED)?(c.log("Push rejected (busy)"),f.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,tt.INCOMING,t),E)})}_createParticipant(e){return o(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:fe(),participantState:{},state:$.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 V(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 M=(t.conversation.participants||[]).find(O=>v.comparePeerId(O.peerId,t.peerId));if(!M)throw new V(k.UNKNOWN_ERROR);p=Number(M.id),M.idType&&(r=M.idType),M.deviceIdx&&(u=M.deviceIdx),this._api.setUserId(p)}let E=v.composeParticipantId(p,r,u),C=yield this._getParticipantId(E);this._conversation={userId:p,compositeUserId:E,externalId:C,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:[],recordsInfoByRoom:new Map,muteStates:new Map,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1,asrInfo:null,roomId:null},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(l.forceRelayPolicy=e.p2p_forbidden),f.log(T.RELAY_POLICY,l.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new V(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 qi;return this.subscribe(e,Pe.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Pe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new $t(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&&_.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(this._createParticipantListChunk(t)))}_createParticipantListChunk(e){return Ae(Ae({},{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 et(Ae({},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}`),_.onLocalRolesChanged(this._conversation.roles)),yield this._registerParticipantLocalMuteState(i);continue}if(i.state===$.HUNGUP||i.state===$.REJECTED){this._participants[i.id]&&this._removeParticipant(this._participants[i.id],k.HUNGUP);continue}this._registerParticipantInCache(yield this._createParticipant({id:r,externalId:i.externalId&&he.fromSignaling(i.externalId,i.deviceIdx||0),mediaSettings:fe(i.mediaSettings),participantState:v.mapParticipantState(i),state:i.state,roles:i.roles||[],status:l.batchParticipantsOnStart?Y.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}`),_.onRolesChanged(this._participants[r].externalId,i.roles))}})}_registerParticipantLocalMuteState(e){return o(this,null,function*(){if(!e.muteStates)return Promise.resolve();let t=At(e.muteStates,Ue.MUTE),i=At(e.muteStates,Ue.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===j.CONNECTED?t=Y.CONNECTED:e===j.CONNECTING||e===j.OPENED?t=Y.CONNECTING:e===j.RECONNECTING&&(t=Y.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]=et(Ae(Ae({},i),s),{id:e}),r),{})}_processConnectionData(e){return o(this,null,function*(){this._processRooms(e),this._processMuteStates(e),e.conversation.pinnedParticipantId&&(yield this._onPinParticipant(e.conversation.pinnedParticipantId)),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Li.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)})}_processRooms(e){var i,r;let t=(r=(i=e.rooms)==null?void 0:i.roomId)!=null?r:null;this._onRoomSwitched(t,!0)}_processMuteStates(e){var i,r,a;this._setMuteStatesForRoomId((i=e.conversation)==null?void 0:i.muteStates,null);for(let s of(a=(r=e.rooms)==null?void 0:r.rooms)!=null?a:[])this._setMuteStatesForRoomId(s.muteStates,s.id);let t=this._getMuteStatesForCurrentRoom();this._onMuteParticipant({muteStates:t,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(t),muteAll:!0,stateUpdated:!0,roomId:this._conversation.roomId})}_processRecordInfos(e){var t,i,r,a;this._onRecordInfo((t=e.conversation.recordInfo)!=null?t:null);for(let s of(r=(i=e.rooms)==null?void 0:i.rooms)!=null?r:[])this._onRecordInfo((a=s.recordInfo)!=null?a:null,s.id)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new mr(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new vi,this.subscribe(this._transport,B.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,B.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,B.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,B.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,B.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,B.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,B.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,B.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,B.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,B.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,B.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this)),this.subscribe(this._transport,B.ASR_TRANSCRIPTION,this._onAsrTranscription.bind(this)),this.subscribe(this._transport,B.ANIMOJI_STREAM,this._onAnimojiStream.bind(this));let e=this._conversation.direction===tt.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===$.ACCEPTED||t.state===$.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new hr(this._transport),this.subscribe(this._volumesDetector,_t.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new gr(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,_r.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Ei(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Ci(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()?"✔":"✖")),f.log(T.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){f.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===$.CALLED||e.state===$.ACCEPTED||this._state==="CLOSE"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),!!this._participants[e.id]&&(t===k.HUNGUP?this._setParticipantsStatus([e],Y.HANGUP):this._setParticipantsStatus([e],Y.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Ce.CAMERA,stopStream:!0}]),delete this._participants[e.id],_.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===$.ACCEPTED||r.state===$.CALLED)){c.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(r=this._registerParticipantInCache(yield this._createParticipant({id:e,externalId:t.externalId&&he.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:fe(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}))),this._setParticipantsStatus([r],Y.WAITING),i?(r.state=$.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=$.CALLED,this._transport.allocate(r.id,!0),f.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);f.log(T.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new $t(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ne.UNKNOWN)})}toggleScreenCapturing(e,t){return o(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e,t):Promise.reject(ne.UNKNOWN)})}toggleAnimojiCapturing(e){this._mediaSource&&this._mediaSource.toggleAnimojiCapturing(e)}setAnimojiSvg(e,t=null,i=null){if(!this._transport)return;let r=!t,a=t!=null?t:this._conversation.compositeUserId;if(e instanceof ArrayBuffer){let s=i!=null?i:this._conversation.externalId.id;this._transport.setAnimojiSvg(a,{svg:e,userId:s,isMe:r});return}this._transport.setAnimojiSvg(a,{svg:e,isMe:r})}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 f.log(T.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return f.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:he.fromId(r.uid),s=he.toString(a);i[s]=r.priority}for(let r of Object.values(this._participants)){let a=he.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[Fe(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:he.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(a);if(!s){let E=he.toString(a);c.log(`Unknown participant external ID ${E}`);continue}let d=v.compose(s,a.deviceIdx),p=Fe({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),u=this._participants[d];u?u.lastRequestedLayouts[p]=r:this._isMe(d)&&(this._myLastRequestedLayouts[p]=r),Wt(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=Kt(e),r=this._participants[i.participantId],{externalId:a}=this._conversation,s=this._isMe(i.participantId);if(r){if(i.streamName&&(i.mediaType===Ce.STREAM||i.mediaType===Ce.MOVIE)){let d={stream:null,streamName:i.streamName,mediaType:i.mediaType};s?_.onLocalLive(a,d):_.onRemoteLive(r.externalId,d)}else s||_.onRemoteStream(r.externalId,null);f.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=Kt(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=Kr.UNKNOWN_ERROR):p=$r(a),i.push({externalId:d.externalId,errorReason:p})}}if(i&&i.length)throw new Ri("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+Xn>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e)}_onParticipantSourcesUpdate(e){if(this._conversation){c.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){c.log("Promoted in waiting hall",!e.demote),e.demote?(c.log("Kicked from waiting hall"),this._close(new V(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=ve.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))),_.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))_.onLocalLiveUpdate(t,r);else{let s=yield this._getExternalIdByParticipantId(r.participantId);s&&_.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))_.onLocalSharedMovieInfo(t,e);else{let a=yield this._getExternalIdByParticipantId(e.initiatorId);a&&_.onRemoteSharedMovieInfo(a,e)}this._transport.getTopology()===de.SERVER&&this._transport.getState()===j.IDLE&&this._participantState!==$.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))_.onLocalSharedMovieStoppedInfo(t,s);else{let p=yield this._getExternalIdByParticipantId(i);p&&_.onRemoteSharedMovieStoppedInfo(p,s)}})}_onFeaturesPerRoleChanged(e){c.log(`Features per role changed: ${e.notification}`),_.onFeaturesPerRoleChanged(e.featuresPerRole)}_waitForStreamIfNeeded(e){var d,p;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||l.producerScreenDataChannel&&t.mediaType===Ce.SCREEN||t.mediaType===Ce.ANIMOJI)return;let i=Fe(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}`),f.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:C}=this._conversation,M=this._isMe(u);if(!E&&!M){f.log(T.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${u}`);return}let O=M?C:E.externalId,F=this._streamByStreamId.get(a);if(!F){f.log(T.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}f.log(T.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,a);let D=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(D===Ce.STREAM||D===Ce.MOVIE){if((p=e.participantStreamDescription)==null?void 0:p.streamName){let pe={streamName:e.participantStreamDescription.streamName,stream:F,mediaType:D};M?_.onLocalLive(O,pe):_.onRemoteLive(O,pe)}}else if(l.producerScreenTrack&&D===Ce.SCREEN)_.onRemoteScreenStream(E.externalId,F);else if(!M){let pe=(l.producerScreenTrack?null:E.secondStream)||F;_.onRemoteStream(E.externalId,pe)}}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(Fe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Fe(i)))return i}else{let i={participantId:t,mediaType:Ce.CAMERA};if(this._streamIdByStreamDescription.has(Fe(i)))return i;let r={participantId:t,mediaType:Ce.SCREEN};if(this._streamIdByStreamDescription.has(Fe(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,[it.ADMIN,it.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!v.includesOneOf(this._conversation.roles,[it.ADMIN,it.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()})}requestAsr(e){return o(this,null,function*(){yield this._signaling.requestAsr(e)})}muteParticipant(){return o(this,arguments,function*(e=null,t,i=[],r=null){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i,r)})}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=Or(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return o(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Pa(e));let 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 C=ve.fromSignaling(E.externalId);d.push(C),this._api.cacheExternalId(E.id.id,C)}else p.push(v.decomposeId(E.id.id).id)}),p.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(p)),a.hasMore&&(u=ya(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*(){let i=yield this._signaling.updateRooms(e,t);if(i.error)throw new Error(i.error)})}activateRooms(e,t){return o(this,null,function*(){let i=yield this._signaling.activateRooms(e,t);if(i.error)throw new Error(i.error)})}switchRoom(e,t){return o(this,null,function*(){let i=yield this._signaling.switchRoom(e,t);if(i.error)throw new Error(i.error)})}removeRooms(e){return o(this,null,function*(){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=yield this._signaling.stopStream({roomId:e});return t.error?Promise.reject():t})}recordSetRole(e,t,i=null){return o(this,null,function*(){let r=yield this._signaling.recordSetRole(e,t,i);if(r.error)throw new Error(r.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&&he.fromSignaling(s.externalId,s.deviceIdx||0),mediaSettings:fe(s.mediaSettings),participantState:v.mapParticipantState(s),state:s.state,roles:s.roles||[],status:(p=this._getStatusByTransportState(a))!=null?p:Y.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 C,M;let u=v.composeId(p),E=this._participants[u];E.status=(C=this._getStatusByTransportState(a))!=null?C:Y.WAITING,E.movieShareInfos=p.movieShareInfos,Object.assign(E.mediaSettings,fe(p.mediaSettings)),Object.assign(E.muteStates,p.muteStates),E.unmuteOptions=(M=p.unmuteOptions)!=null?M:E.unmuteOptions,this._openTransport([E],!0)}),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),_.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;_.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)){_.onLocalMediaSettings(i,t);return}let a=this._participants[e];if(!a){this._warnParticipantNotInConversation(e);return}a.mediaSettings=t,this._state==="ACTIVE"&&_.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"&&_.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}`),_.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case w.ACCEPTED_CALL:return this._onAcceptedCall(e);case w.HUNGUP:return this._onHungup(e);case w.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case w.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case w.CLOSED_CONVERSATION:return this._onClosedConversation(e);case w.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case w.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case w.RATE_CALL_DATA:return this._onNeedRate();case w.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case w.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case w.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case w.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case w.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case w.REGISTERED_PEER:return this._onPeerRegistered(e);case w.SWITCH_MICRO:return this._onMicSwitched(e);case w.CHAT_MESSAGE:return this._onChatMessage(e);case w.CUSTOM_DATA:return this._onCustomData(e);case w.RECORD_STARTED:return this._onRecordInfo(e.recordInfo,e.roomId);case w.RECORD_STOPPED:return this._onRecordInfo(null,e.roomId);case w.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case w.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case w.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin,e.markers);case w.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case w.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case w.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case w.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants);case w.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e);case w.FEEDBACK:return this._onFeedback(e);case w.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e);case w.MOVIE_SHARE_STARTED:return this._onSharedMovieInfoStarted(e);case w.MOVIE_SHARE_STOPPED:return this._onSharedMovieInfoStopped(e);case w.ROOMS_UPDATED:return this._onRoomsUpdated(e);case w.ROOM_UPDATED:return this._onRoomUpdated(e);case w.ROOM_PARTICIPANTS_UPDATED:return this._onRoomParticipantsUpdated(e);case w.FEATURES_PER_ROLE_CHANGED:return this._onFeaturesPerRoleChanged(e);case w.ASR_STARTED:return this._onAsrInfo(e.asrInfo);case w.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=fe(a.mediaSettings),Ut(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=fe(a.mediaSettings);aa(u,p.mediaSettings)||this._changeRemoteMediaSettings(s,u);let E=v.mapParticipantState(a),C=p.participantState;v.isEqualParticipantState(E,C)||this._changeRemoteParticipantState(s,E),Ut(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._processRecordInfos(e),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 V(k.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(r=this._registerParticipantInCache(yield this._createParticipant({id:t,mediaSettings:fe(e.mediaSettings)}))),r.state=$.ACCEPTED,r.mediaSettings=fe(e.mediaSettings),this._logWithMediaSettings(T.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===tt.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 V(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?$.REJECTED:$.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!==$.HUNGUP&&i.state!==$.REJECTED){c.debug(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&he.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:fe(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=$.CALLED,i.mediaSettings=fe((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],Y.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),_.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===$.ACCEPTED){c.warn(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&he.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:fe(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===tt.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=$.ACCEPTED,i.mediaSettings=fe(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],Y.CONNECTED):this._setParticipantsStatus([i],Y.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((a=this._conversation)==null?void 0:a.observer))),_.onParticipantJoined(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i),_.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 V(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,fe(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(),_.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=fe(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),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=lr(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=lr(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*(){_.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),_.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),_.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e,t=null){return o(this,null,function*(){var a;if(!this._conversation)return;let i=this._conversation.recordsInfoByRoom.get(t),r=!1;if(!i!=!e?r=!0:i&&e&&(r=i.recordMovieId!==e.recordMovieId),r)if(this._conversation.recordsInfoByRoom.set(t,e),e){let s=yield this._getParticipantId(e.initiator);_.onRecordStarted(s,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId,t)}else _.onRecordStopped(t);e&&this._transport.getTopology()===de.SERVER&&this._participantState!==$.CALLED&&this._transport.open(this._transport.allocated(),null,!!((a=this._conversation)==null?void 0:a.observer),!0)})}_changeRecordInfoForRoom(){return o(this,null,function*(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.recordsInfoByRoom.get(e);if(t){let i=yield this._getParticipantId(t.initiator);_.onRecordStarted(i,t.recordMovieId,t.recordStartTime,t.recordType,t.recordExternalMovieId,t.recordExternalOwnerId,e)}else _.onRecordStopped(e)})}_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);_.onAsrStarted(i,e.movieId)}else _.onAsrStopped();this._conversation.asrInfo=e})}_onAsrTranscription(e){return o(this,null,function*(){if(!this._conversation)return;let t=yield this._getParticipantId(e.participantId);_.onAsrTranscription(t,e.text,e.timestamp,e.duration)})}_onRolesChanged(e,t){if(this._conversation&&this._isMe(e)&&!Ut(this._conversation.roles,t)){c.debug(`Local roles changed: ${t}`),this._conversation.roles=t,_.onLocalRolesChanged(t),this._processMuteState({mediaOptions:At(this._getMuteStatesForCurrentRoom(),Ue.MUTE_PERMANENT),stateUpdated:!0}),v.includesOneOf(t,[it.ADMIN,it.CREATOR])&&this._refreshRooms(!0);return}let i=this._participants[e];i&&!Ut(i.roles,t)&&(c.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,_.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){var u;if(!this._conversation)return;let i=(u=e.roomId)!=null?u:null,r=e.muteStates||{},a=e.unmuteOptions||[],s=e.mediaOptions||[],d=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 E=this._participants[e.participantId];E&&(c.debug(`Mute states for participant [${e.participantId}] changed`,r),_.onMuteStates(r,a,s,e.muteAll,e.unmute,E.externalId,d==null?void 0:d.externalId,e.stateUpdated,e.requestedMedia,e.roomId));return}let p=this._getMuteStatesForRoomId(i);if(!(v.isObjectsEquals(p,r)&&v.isArraysEquals(this._conversation.unmuteOptions,a)&&!s.length)){if(this._setMuteStatesForRoomId(r,i),this._conversation.unmuteOptions=a,this._isMe(e.adminId)){e.muteAll&&_.onMuteStates(r,a,s,e.muteAll,e.unmute,null,this._conversation.externalId,e.stateUpdated,e.requestedMedia,e.roomId);return}yield this._processMuteState({mediaOptions:s,muteAll:e.muteAll,unmute:e.unmute,serverSettings:t,admin:d,stateUpdated:e.stateUpdated,requestedMedia:e.requestedMedia,roomId:e.roomId})}})}_changeMuteStatesForRoom(e,t){if(!this._conversation)return;this._conversation.unmuteOptions=[];let i=this._getMuteStatesForRoomId(t),r=this._getMuteStatesForRoomId(e),a=Object.keys(i),s=Object.keys(r);this._processMuteState({mediaOptions:Array.from(new Set([...a,...s])),roomId:e,muteAll:!0,stateUpdated:!0})}_processMuteState(u){return o(this,arguments,function*({mediaOptions:e=[],muteAll:t=!1,unmute:i=!1,serverSettings:r=null,admin:a=null,stateUpdated:s,requestedMedia:d,roomId:p=null}){if(!this._conversation||!this._mediaSource||this._participantState!==$.ACCEPTED)return;let E=Object.assign({},this._getMuteStatesForRoomId(p)),C=this._conversation.unmuteOptions,M=this._mediaSource.getMediaSettings(),O=Object.entries(E);for(let[F,D]of O)if(!(D!==Ue.MUTE&&D!==Ue.MUTE_PERMANENT)&&(this._isCallAdmin()&&D===Ue.MUTE_PERMANENT&&!t&&(E[F]=Ue.MUTE),!(!e.includes(F)||i)))switch(F){case ue.VIDEO:M.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(_.onDeviceSwitched(ue.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case ue.AUDIO:M.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(_.onDeviceSwitched(ue.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case ue.SCREEN_SHARING:M.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(_.onDeviceSwitched(ue.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1,!1));break;case ue.AUDIO_SHARING:M.isAudioSharingEnabled&&!(r==null?void 0:r.isAudioSharingEnabled)&&(_.onDeviceSwitched(ue.AUDIO_SHARING,!1),yield this.toggleScreenCapturing(M.isScreenSharingEnabled,!1));break}_.onMuteStates(E,C,e,t,i,null,a==null?void 0:a.externalId,s,d,p)})}_onPinParticipant(e,t=!1,i){return o(this,null,function*(){if(!this._conversation)return;let r=this._conversation.pinnedParticipantId;if(r&&r!==e)if(this._isMe(r))_.onLocalPin(!0);else{let a=yield this._getExternalIdByParticipantId(r);a&&_.onPinnedParticipant(a,!0,this._denormalizeMarkers(e,i))}if(this._isMe(e))_.onLocalPin(t);else{let a=yield this._getExternalIdByParticipantId(e);a&&_.onPinnedParticipant(a,t,this._denormalizeMarkers(e,i))}this._conversation.pinnedParticipantId=t?null:e})}_onOptionsChanged(e){this._conversation&&!kr(this._conversation.options,e)&&(this._conversation.options=e,_.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let 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,_.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),_.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(l.producerScreenTrack){_.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){f.log(T.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}_.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&_.onRemoteStream(i.externalId,r)}}}_onAnimojiStream(e,t){if(this._isMe(e)){this._mediaSource.onAnimojiStream(t);return}let i=this._participants[e];if(!i)return;if(t){_.onRemoteStream(i.externalId,t);return}let r=Fe({participantId:e,mediaType:Ce.CAMERA,streamName:null});if(!this._streamIdByStreamDescription.has(r))return;let a=this._streamIdByStreamDescription.get(r);if(!this._streamByStreamId.has(a))return;let s=this._streamByStreamId.get(a);_.onRemoteStream(i.externalId,s)}_onPeerConnectionClosed(e){e===de.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Ni.ADD_PARTICIPANT);_.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&_.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let a=this._participants[i];a&&a.externalId&&t.push({uid:a.externalId,volume:r.real})}_.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(_.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return 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===j.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===j.CONNECTED&&(_.onLocalStatus(Y.CONNECTED),((t=this._transport)==null?void 0:t.getTopology())===de.SERVER)){let i=Object.values(this._myLastRequestedLayouts);yield this.updateDisplayLayout(i)}e===j.CONNECTING&&_.onLocalStatus(Y.CONNECTING),e===j.RECONNECTING&&_.onLocalStatus(Y.RECONNECT),e===j.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(k.FAILED)),this._close(new V(k.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(Be.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i),_.onRemoteMixedAudioStream(t);else if(e.startsWith(Be.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],Y.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(_.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===oe.audio&&(this._audioOutput.add(i),l.preserveAudioTracks||t.removeTrack(i)),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;_.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 oe.audio:this._removeAudioTrack(e,t,i);break;case oe.video:case oe.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Be.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_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,Y.RECONNECT),i.length&&this._setParticipantsStatus(i,Y.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(a=>{if(t[a]=!0,!this._lastStalled[a]){let s=this._participants[a];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[a]}),Object.keys(this._lastStalled).forEach(a=>{let s=this._participants[a];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,Y.RECONNECT),r.length&&this._setParticipantsStatus(r,Y.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!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}),_.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(!e.length)return;let r=e.reduce((a,s)=>(s.status!==t&&(s.status=t,l.batchParticipantsOnStart?a.push(s.externalId):_.onParticipantStatus(s.externalId,t,i)),a),[]);!r.length||l.batchParticipantsOnStart&&_.onRemoteStatus(r,t,i)}_onJoinLinkChanged(e){_.onJoinLinkChanged(e.joinLink)}_onRoomsUpdated(e){return o(this,null,function*(){var i,r;let t={};for(let a of Object.keys(Nt)){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})}_.onRoomsUpdated(t)})}_onRoomUpdated(e){return o(this,null,function*(){let t=yield this._convertRoomToExternal(e.room);e.events.some(i=>i===Nt.UPDATE)&&(e.muteStates!==void 0&&this._setMuteStatesForRoomId(e.muteStates,e.roomId),e.recordInfo!==void 0&&this._conversation.recordsInfoByRoom.set(e.roomId,e.recordInfo)),_.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,muteStates:e.muteStates}})}_onRoomParticipantsUpdated(e){return o(this,null,function*(){var E,C,M,O,F;let t=this._transport.getState(),i=(E=e.roomId)!=null?E:null,[r,a]=yield Promise.all([Promise.all(((M=(C=e.addedParticipantIds)==null?void 0:C.map)==null?void 0:M.call(C,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((F=(O=e==null?void 0:e.addedParticipants)==null?void 0:O.map)==null?void 0:F.call(O,D=>o(this,null,function*(){var K;let pe=v.composeId(D);return this._createParticipant({id:pe,externalId:D.externalId&&he.fromSignaling(D.externalId,D.deviceIdx||0),mediaSettings:fe(D.mediaSettings),participantState:v.mapParticipantState(D),state:D.state,roles:D.roles||[],status:(K=this._getStatusByTransportState(t))!=null?K:Y.WAITING,muteStates:D.muteStates||{},unmuteOptions:D.unmuteOptions||[],observedIds:D.observedIds||[],markers:this._denormalizeMarkers(pe,D.markers)})})))||[])]),s=!1;for(let D of a)D.id===this._conversation.compositeUserId&&(s=!0),this._registerParticipantInCache(D);this._openTransport(a,!0);let d=[],p=[];if(e==null?void 0:e.removedParticipantMarkers){for(let D of e.removedParticipantMarkers)D.GRID&&p.push(this._getExternalIdByParticipantId(D.GRID.id));d=yield Promise.all(p)}s&&(yield this._onRoomSwitched(i));let u={roomId:i,participantCount:e.participantCount,addedParticipantIds:r,addedParticipants:v.mapSharedParticipants(a),removedParticipantMarkers:e==null?void 0:e.removedParticipantMarkers,removedParticipantIds:d};_.onRoomParticipantsUpdated(u)})}_onRoomSwitched(e,t=!1){return o(this,null,function*(){if(!this._conversation||this._conversation.roomId===e)return;let i=this._conversation.roomId;if(this._conversation.roomId=e,t){_.onRoomStart(e);return}_.onRoomSwitched(e),e!==null&&!this._isCallAdmin()&&(yield this._refreshRooms(!1)),this._changeRecordInfoForRoom(),this._changeMuteStatesForRoom(e,i)})}_refreshRooms(e){return o(this,null,function*(){var r,a;let i=(a=(r=(yield this._signaling.getRooms(e)).rooms)==null?void 0:r.rooms)!=null?a:[];for(let s of i)this._setMuteStatesForRoomId(s.muteStates,s.id),this._conversation.recordsInfoByRoom.set(s.id,s.recordInfo);e&&_.onRoomsUpdated({[Nt.UPDATE]:{rooms:yield Promise.all(i.map(this._convertRoomToExternal.bind(this)))}})})}_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(et(Ae({},p),{participantId:this._conversation.externalId}));let u=yield t(p.participantId);return et(Ae({},p),{participantId:u})})),d=yield Promise.all(s);return et(Ae({},a),{items:d})})),r=yield Promise.all(i);_.onFeedback(r,e.roomId)})}_isMe(e){var t;return e===((t=this._conversation)==null?void 0:t.compositeUserId)}_getMuteStatesForRoomId(e=null){var i;return(i=this._conversation.muteStates.get(e))!=null?i:{}}_getMuteStatesForCurrentRoom(){return this._getMuteStatesForRoomId(this._conversation.roomId)}_setMuteStatesForRoomId(e={},t=null){this._conversation.muteStates.set(t,e)}},N=W;N._delayedHangup=!1;var Ri=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Ri.prototype),this.participantErrors=t}};var Dt,Yt=null;function es(){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 Da(){return o(this,null,function*(){return Dt||Yt||(Yt=es(),Dt=yield Yt,Yt=null,Dt)})}function ka(){if(!l.apiKey)throw new V(ne.API,{message:"Required argument apiAppKey not passed"})}function fr(i){return o(this,arguments,function*(n,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;yield Da();let r=wa(n,e,t),a=new window.Blob([r],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${Dt}/fb.do`,a)})}function Oa(i){return o(this,arguments,function*(n,e={},t=!1){yield Da();let r=wa(n,e,t);return ts(r)})}function ts(n){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${Dt}/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 wa(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 rs=10,as=700,ns=3e3,yi=class extends wt{constructor(){super(...arguments);this._userId=null;this._externalUidsCache=new Map;this._extrnalUidsBatch=new Set;this._extrnalUidsBatchTimeout=null}_callUnsafe(r){return o(this,arguments,function*(e,t={},i=!1){let a=s=>o(this,null,function*(){try{return yield Oa(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<rs))return yield v.delay(Math.min(s*as,ns)),a(s);throw c.warn(e,"error",d),d}});return a(0)})}_call(r){return o(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(a){c.warn("Api call error",a);let s=ne.API;switch(a.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=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 V(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()?ve.fromId(String(t)):(yield this._prepareUserIdsByOkIdsBatched([t]),ve.fromString(this._externalUidsCache.get(t)))})}prepareUserIds(e){return o(this,null,function*(){se.isEmpty()||(yield this._prepareUserIdsByOkIdsBatched(e))})}_prepareUserIdsByOkIdsBatched(e){return e.some(i=>!this._externalUidsCache.has(i))?(e.forEach(i=>this._extrnalUidsBatch.add(i)),this._extrnalUidsBatchTimeout||(this._extrnalUidsBatchPromise=new Promise(i=>{this._extrnalUidsBatchTimeout=window.setTimeout(()=>{if(this._extrnalUidsBatch.size>0){let r=[...this._extrnalUidsBatch];this._extrnalUidsBatch.clear(),this._getExternalIdsByOkIds(r).then(a=>{for(let s in a)!a.hasOwnProperty(s)||this._externalUidsCache.set(parseInt(s,10),a[s]);i()})}this._extrnalUidsBatchTimeout=null},l.api.userIdsByOkBatchedTimeout)})),this._extrnalUidsBatchPromise):Promise.resolve()}authorize(){return o(this,null,function*(){if(!this._uuid){let t=rt.get("uuid");t||(t=v.uuid(),rt.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&&_.onTokenExpired(),new V(ne.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${l.appName}:${l.sdkVersion}`,platform:l.platform,items:e})};fr("log.externalLog",t)}init(){ka()}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,C){return o(this,arguments,function*(e,t,i,r=!1,a="",s=!1,d=!1,{onlyAdminCanShareMovie:p}={}){let M=this._preareStartConversationData({conversationId:e,isVideo:r,joiningAllowed:s,payload:a,requireAuthToJoin:d,onlyAdminCanShareMovie:p});if(t&&t.length)switch(i){case Ye.USER:M.uids=t.join(",");break;case Ye.GROUP:M.gid=t[0];break;case Ye.CHAT:M.chatId=t[0];break}return this._startConversation(M)})}_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=ve.fromIds(e),i=[],r={methods:[]},a=[],s=[...this._externalUidsCache.keys()],d=[...this._externalUidsCache.values()];for(let u of t){let E=ve.toString(u),C=d.indexOf(E);C>-1?i.push(Number(s[C])):(a.push(E),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:u.id,anonym:u.type===Mt.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((u,E)=>{if(u.ok){let C=Number(u.ok.ok_id);this._externalUidsCache.set(C,a[E]),i.push(C)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let a of e)this._externalUidsCache.has(a)?t.push(ve.fromString(this._externalUidsCache.get(a))):i.push(a);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);for(let a in r)!r.hasOwnProperty(a)||this._externalUidsCache.set(parseInt(a,10),r[a]);for(let a of i)r.hasOwnProperty(a)&&t.push(ve.fromString(r[a]));return t})}getCachedOkIdByExternalId(e){let t=[...this._externalUidsCache.keys()],i=[...this._externalUidsCache.values()],r=ve.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.set(i,ve.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),fr("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]=ve.fromIdToString(a,Mt.USER);if(i.anonym_ids)for(let[r,a]of Object.entries(i.anonym_ids))t[r]=ve.fromIdToString(a,Mt.ANONYM);return t}catch(i){return t}})}};var Sr=class{requestAsr(e){let t=new ArrayBuffer(2),i=new DataView(t);return i.setUint8(0,1),i.setUint8(1,e?0:1),t}};import{Any as os,Arr as La,Int as J,Nil as gt,Str as cs}from"messagepack";var xa=(L=>(L.RECOVER="recover",L.ACCEPT_CALL="accept-call",L.ADD_PARTICIPANT="add-participant",L.REMOVE_PARTICIPANT="remove-participant",L.HANGUP="hangup",L.TRANSMIT_DATA="transmit-data",L.ACCEPT_PRODUCER="accept-producer",L.ALLOCATE_CONSUMER="allocate-consumer",L.CHANGE_MEDIA_SETTINGS="change-media-settings",L.CHANGE_PARTICIPANT_STATE="change-participant-state",L.CHANGE_STREAM_PRIORITIES="change-streams-priorities",L.UPDATE_DISPLAY_LAYOUT="update-display-layout",L.REPORT_PERF_STAT="report-perf-stat",L.REPORT_SHARING_STAT="report-sharing-stat",L.RECORD_START="record-start",L.RECORD_STOP="record-stop",L.RECORD_SET_ROLE="record-set-role",L.RECORD_GET_STATUS="record-get-status",L.SWITCH_MICRO="switch-micro",L.SWITCH_TOPOLOGY="switch-topology",L.REQUEST_REALLOC="request-realloc",L.CHAT_MESSAGE="chat-message",L.CHAT_HISTORY="chat-history",L.CUSTOM_DATA="custom-data",L.GRANT_ROLES="grant-roles",L.MUTE_PARTICIPANT="mute-participant",L.ENABLE_FEATURE_FOR_ROLES="enable-feature-for-roles",L.PIN_PARTICIPANT="pin-participant",L.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",L.CHANGE_OPTIONS="change-options",L.GET_WAITING_HALL="get-waiting-hall",L.GET_PARTICIPANT_LIST_CHUNK="get-participant-list-chunk",L.GET_PARTICIPANTS="get-participants",L.PROMOTE_PARTICIPANT="promote-participant",L.REQUEST_TEST_MODE="request-test-mode",L.ADD_MOVIE="add-movie",L.UPDATE_MOVIE="update-movie",L.REMOVE_MOVIE="remove-movie",L.GET_ROOMS="get-rooms",L.UPDATE_ROOMS="update-rooms",L.ACTIVATE_ROOMS="activate-rooms",L.REMOVE_ROOMS="remove-rooms",L.SWITCH_ROOM="switch-room",L.FEEDBACK="feedback",L.ASR_START="asr-start",L.ASR_STOP="asr-stop",L.REQUEST_ASR="request-asr",L))(xa||{}),x=xa;function Qt(){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),ss(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 ss(n){return n.buffer!==void 0}function Pi(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 Na=0,Ua=1,ds=2,ls=0,ps=1,us=2,bi=0,ms=0,hs=0,_s=1,vr=class{constructor(){this.participantIdRegistry=null}setParticipantIdRegistry(e){this.participantIdRegistry=e}serializeUpdateDisplayLayout(e,t){let i=Qt();J.enc(i,Na),J.enc(i,bi),J.enc(i,e),gt.enc(i,null);let r=[];for(let a in t)t.hasOwnProperty(a)&&this.writeLayout(t,a,r);return La.enc(i,r),gt.enc(i,null),i.ui8array()}writeLayout(e,t,i){let r=e[t],a=Qt();if(this.writeStreamDesc(t,a),Wt(r))J.enc(a,ps);else if(cr(r))J.enc(a,us);else if(J.enc(a,ls),r.priority!==void 0?J.enc(a,r.priority):gt.enc(a,null),r.width!==void 0&&r.height!==void 0?(J.enc(a,Math.round(r.width)),J.enc(a,Math.round(r.height))):(gt.enc(a,null),gt.enc(a,null)),r.fit!==void 0)switch(r.fit){case"cv":J.enc(a,hs);break;case"cn":J.enc(a,_s);break;default:gt.enc(a,null)}else gt.enc(a,null);i.push(a.ui8array())}writeStreamDesc(e,t){if(this.participantIdRegistry){let i=this.participantIdRegistry.getCompactId(e);if(i!==void 0){J.enc(t,i);return}}cs.enc(t,e)}serializePerfStatReport(e,t){let i=Qt();return J.enc(i,Ua),J.enc(i,bi),J.enc(i,e),J.enc(i,t.framesDecoded),J.enc(i,t.framesReceived),i.ui8array()}serializeSharingStatReport(e,t){let i=Qt();return J.enc(i,ds),J.enc(i,bi),J.enc(i,e),J.enc(i,t.minDelay),J.enc(i,t.maxDelay),J.enc(i,t.avgDelay),J.enc(i,t.largeDelayDuration),i.ui8array()}deserializeCommandResponse(e){return o(this,null,function*(){let t;if(e instanceof Blob){let s=Blob.prototype.arrayBuffer?yield e.arrayBuffer():yield ra(e);t=Pi(s)}else t=Pi(e);let i=J.dec(t),r=J.dec(t);if(r!==bi){c.warn("Unsupported version for command type: "+i+", version "+r);return}if(J.dec(t)!==ms){c.warn("Error code: "+i+"received for command type: "+i+", version "+r);return}switch(i){case Na:return this.deserializeUpdateDisplayLayoutResponse(t);case Ua:return this.deserializeReportPerfStatResponse(t);default:return c.warn("unsupported command response commandType: "+i),null}})}deserializeUpdateDisplayLayoutResponse(e){let t=J.dec(e),i=La.dec(e),r={};return i.forEach(a=>{let s=Pi(a),d=os.dec(s);if(typeof d=="string")r[d]=J.dec(s);else{let p=d,u=Fe(this.participantIdRegistry.getStreamDescription(p));r[u]=J.dec(s)}}),{type:"response",sequence:t,response:x.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:r}}deserializeReportPerfStatResponse(e){let t=J.dec(e),i=J.dec(e);return{type:"response",sequence:t,response:x.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:i}}};var Mi="open",Ba=[()=>l.producerScreenTrack,()=>l.videoTracksCount>0,()=>!0,()=>l.filteredMessages,()=>l.consumerScreenTrack,()=>!0,()=>l.movieShare,()=>l.useParticipantListChunk,()=>l.useRooms,()=>l.useVmoji],gs=10,we=class extends Lt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.asrCommandsQueue=[];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="+we._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null;this.asrDataChannel=null;this.producerCommandDataChannelEnabled=!1;this.producerCommandSerializationService=new vr;this.asrCommandSerializer=new Sr}static _getCapabilityFlags(){let e=0;for(let t=0;t<Ba.length;t++)Ba[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){f.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 d,p;if(e===x.REQUEST_ASR)this.asrCommandsQueue.push(s),((d=this.asrDataChannel)==null?void 0:d.readyState)===Mi&&this._handleCommandsQueue(this.asrCommandsQueue);else if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((p=this.producerCommandDataChannel)==null?void 0:p.readyState)===Mi&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){f.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&&(f.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,C=!1)=>{!i||C?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===x.UPDATE_DISPLAY_LAYOUT||e===x.REPORT_PERF_STAT||e===x.REPORT_SHARING_STAT:!1}static _isDataChannelResponseRequired(e){return e===x.UPDATE_DISPLAY_LAYOUT||e===x.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(x.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(x.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e,t){return o(this,null,function*(){return this._send(x.REQUEST_TEST_MODE,{consumer:e,producer:t})})}sendSdp(e,t){return o(this,null,function*(){return this._send(x.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(x.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(x.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},gs)})}changeParticipantState(e){return o(this,null,function*(){return this._send(x.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(x.ADD_PARTICIPANT,Ae({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(x.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(x.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(x.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(x.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(x.UPDATE_DISPLAY_LAYOUT,e)})}addMovie(e){return o(this,null,function*(){return this._send(x.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(x.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(x.REMOVE_MOVIE,e)})}updateRooms(e,t){return o(this,null,function*(){return this._send(x.UPDATE_ROOMS,{rooms:e,assignRandomly:t})})}activateRooms(e,t){return o(this,null,function*(){return this._send(x.ACTIVATE_ROOMS,{roomIds:e,deactivate:t})})}switchRoom(e,t){return o(this,null,function*(){return this._sendRaw(x.SWITCH_ROOM,{toRoomId:e,participantId:t})})}getRooms(e){return o(this,null,function*(){return this._sendRaw(x.GET_ROOMS,{withParticipants:e})})}removeRooms(e){return o(this,null,function*(){return this._send(x.REMOVE_ROOMS,{roomIds:e})})}startStream(e){return o(this,null,function*(){return this._send(x.RECORD_START,e)})}stopStream(){return o(this,arguments,function*(e={roomId:null}){return this._send(x.RECORD_STOP,e)})}recordSetRole(e,t,i=null){return o(this,null,function*(){return this._send(x.RECORD_SET_ROLE,{participantId:e,role:t,roomId:i})})}getRecordStatus(){return o(this,null,function*(){return this._send(x.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(x.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(x.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(x.REPORT_PERF_STAT,e)})}reportSharingStat(e){return o(this,null,function*(){return this._send(x.REPORT_SHARING_STAT,e)})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(x.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(x.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(x.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(x.GRANT_ROLES,r)})}muteParticipant(e,t,i,r=null){return o(this,null,function*(){return this._sendRaw(x.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i,roomId:r})})}enableFeatureForRoles(e,t){return o(this,null,function*(){return this._sendRaw(x.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(x.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(x.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(x.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(x.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(x.PROMOTE_PARTICIPANT,i)})}feedback(e){return o(this,null,function*(){return this._sendRaw(x.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(x.GET_PARTICIPANT_LIST_CHUNK,e)})}getParticipants(e){return o(this,null,function*(){return this._send(x.GET_PARTICIPANTS,{externalIds:e})})}startAsr(){return o(this,null,function*(){return this._send(x.ASR_START)})}stopAsr(){return o(this,null,function*(){return this._send(x.ASR_STOP)})}requestAsr(e){return o(this,null,function*(){return this._send(x.REQUEST_ASR,{request:e})})}setAsrDataChannel(e){this.asrDataChannel=e,this._handleCommandsQueue(this.asrCommandsQueue)}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Qe.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"),f.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){f.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(Te.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Te.NOTIFICATION,{type:"notification",notification:w.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(Te.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(f.log(T.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(f.log(T.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new V(k.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(Te.NOTIFICATION,{notification:w.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new V(ne.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(f.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(Te.FAILED,e)}_onError(e){f.log(T.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){f.log(T.SOCKET_ACTION,"closed"),c.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<we.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(we.RECONNECT_MAX_DELAY,we.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),f.log(T.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Qe.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],f.log(T.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),we.WAIT_RESPONSE_DELAY)}_serializeAsrCommand(e){let t=e.params;return this.asrCommandSerializer.requestAsr(t.request)}_handleCommandsQueue(e){var t,i,r,a;for(;e.length>0;){let s=e.shift();if(s.name===x.REQUEST_ASR){if(((t=this.asrDataChannel)==null?void 0:t.readyState)!==Mi){s.reject(new Error(`Invalid data channel state: ${(i=this.asrDataChannel)==null?void 0:i.readyState}`));return}let d=this._serializeAsrCommand(s);d!==null&&this.asrDataChannel.send(d)}else if(this._isDataChannelCommand(s.name)){if(((r=this.producerCommandDataChannel)==null?void 0:r.readyState)!==Mi){s.reject(new Error(`Invalid data channel state: ${(a=this.producerCommandDataChannel)==null?void 0:a.readyState}`));return}we._isDataChannelResponseRequired(s.name)&&(s.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:s.name,sequence:s.sequence}),we.WAIT_RESPONSE_DELAY),this.responseHandlers[s.sequence]=s);let d=this._serializeBinary(s);d!==null&&this.producerCommandDataChannel.send(d)}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){s.reject(new Error("Invalid state or socket already closed"));continue}s.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:s.name,sequence:s.sequence}),we.WAIT_RESPONSE_DELAY),this.responseHandlers[s.sequence]=s,this.socket.send(this._serializeJson(s))}}}_serializeBinary(e){switch(e.name){case x.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case x.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params);case x.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===x.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]=Ta(t[r]));return{layouts:i}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new V(ne.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},we.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{c.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Qe.RETRY)},we.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},$e=we;$e.RECONNECT_DELAY=l.signalingReconnectDelay,$e.RECONNECT_MAX_DELAY=l.signalingReconnectMaxDelay,$e.RECONNECT_MAX_COUNT=l.signalingReconnectMaxCount,$e.WAIT_CONNECTION_DELAY=l.waitConnectionDelay,$e.WAIT_RESPONSE_DELAY=l.waitResponseDelay,$e.WAIT_MESSAGE_DELAY=l.waitMessageDelay;var Va=(t=>(t.KING="KING",t.PAWN="PAWN",t))(Va||{}),fs=Va;var Fa=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 kt,le,Xt=null,c_={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,isAudioShareSupported:P.isAudioShareSupported};function Ss(n){le=n}function vs(n){kt=n}function d_(n){Xt=n}function l_(n){l.videoEffects=n}function p_(n,e=null){l.vmoji=n,e&&n.setSDK(e)}function u_(n){return o(this,null,function*(){if(l.set(n),P.browserName()==="Sferum"&&(l.platform=`SFERUM:${P.browserVersion()}`),le||Ss(new yi),kt||vs(()=>new $e),l.debug&&(ja.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${l.sdkVersion}`,n),yield P.init(),!P.isBrowserSupported())throw new V(ne.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 m_(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 V(k.CALLEE_IS_OFFLINE);return Es(p,Ye.USER,e,t,i,r,a)})}function Es(d){return o(this,arguments,function*(n,e=Ye.USER,t,i="",r=!1,a=!1,s){if(N.current())throw c.error("There is already active call"),new V(k.FAILED);return new N(le,kt(),Xt).onStart(n,e,t,i,r,a,s)})}function h_(n){return o(this,null,function*(){return Is(n)})}function Is(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,kt(),Xt).onPush(n,e,t)})}function __(n){return o(this,null,function*(){return n&&(l.authToken=n),le.authorize()})}function g_(){return o(this,arguments,function*(n=[ue.AUDIO]){return ft().accept(n)})}function f_(){return o(this,null,function*(){let n=N.current();if(n)return n.decline()})}function S_(t){return o(this,arguments,function*(n,e=[ue.AUDIO]){return Ts(n,e)})}function Ts(n,e,t){return o(this,null,function*(){if(N.current())throw c.error("There is already active call"),new V(k.FAILED);return new N(le,kt(),Xt).onJoin({conversationId:n,mediaOptions:e,chatId:t})})}function v_(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 V(k.FAILED);return t&&(l.anonymToken=t),new N(le,kt(),Xt).onJoin({joinLink:n,mediaOptions:e,observedIds:i,payload:r})})}function E_(){return o(this,null,function*(){let n=N.current();if(n)return n.hangup();N.hangupAfterInit()})}function I_(n,e){return o(this,null,function*(){let t=yield le.getOkIdsByExternalIds([n]);if(!t.length)throw new Error("User not found");return Cs(t[0],e)})}function Cs(n,e){return o(this,null,function*(){let t=N.current();t&&(yield t.addParticipant(v.composeUserId(n,te.USER),e))})}function T_(n,e=!1){return o(this,null,function*(){let t=yield le.getOkIdsByExternalIds([n]);return Rs(t[0],e)})}function Rs(n,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.removeParticipant(v.composeUserId(n,te.USER),e))})}function C_(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 R_(n){return o(this,null,function*(){return ys(n)})}function ys(n,e=!1){return o(this,null,function*(){let t=e&&n&&l.audioShare,i=N.current();return i?i.toggleScreenCapturing(n,t):Promise.reject()})}function y_(n){let e=N.current();e&&e.toggleAnimojiCapturing(n)}function P_(n,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.setVideoStream(n,e))})}function b_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalVideo(n))})}function M_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalAudio(n))})}function A_(n,e,t){return o(this,null,function*(){let i=N.current();if(i)return i.setLocalResolution(n,e,t)})}function D_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changePriorities(n))})}function k_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changeParticipantState(n))})}function O_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.updateDisplayLayout(n))})}function w_(n,e,t=!1){return o(this,null,function*(){let i=yield le.getOkIdsByExternalIds([n]);return Ps(i[0],e,t)})}function Ps(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 x_(r){return o(this,arguments,function*({externalId:n=null,muteStates:e,requestedMedia:t=[],roomId:i=null}){let a=null;return n&&(a=(yield le.getOkIdsByExternalIds([n]))[0]),bs({uid:a,muteStates:e,requestedMedia:t,deviceIdx:he.getDeviceIdx(n),roomId:i})})}function bs(a){return o(this,arguments,function*({uid:n=null,muteStates:e,requestedMedia:t=[],deviceIdx:i=0,roomId:r=null}){let s=N.current();if(s){let d=n?v.composeParticipantId(n,te.USER,i):null;yield s.muteParticipant(d,e,t,r)}})}function L_(n,e=!1){return o(this,null,function*(){let t=yield le.getOkIdsByExternalIds([n]);return Ms(t[0],e,he.getDeviceIdx(n))})}function Ms(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 N_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.updateMediaModifiers(n))})}function U_(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changeOptions(n))})}function B_(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield le.getOkIdsByExternalIds([e]))[0]),As(n,t)})}function As(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 V_(n=10){return o(this,null,function*(){let e=N.current();if(e)return e.chatHistory(n)})}function F_(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield le.getOkIdsByExternalIds([e]))[0]),Ds(n,t,he.getDeviceIdx(e))})}function Ds(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 j_(){return o(this,arguments,function*(n="",e=!1,{onlyAdminCanShareMovie:t=!1}={}){return(yield le.createConversation(v.uuid(),n,e,{onlyAdminCanShareMovie:t})).join_link})}function H_(){return o(this,null,function*(){let n=N.current();return n?n.createJoinLink():Promise.reject()})}function G_(){return o(this,null,function*(){let n=N.current();return n?n.removeJoinLink():Promise.reject()})}function W_(n,e){return o(this,null,function*(){return le.getAnonymTokenByLink(n,e)})}function K_(n){let e=N.current();e&&e.setVolume(n)}function $_(n){l.forceRelayPolicy=n}function q_(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 J_(n=null){return o(this,null,function*(){let e=N.current();return e?e.stopStream(n):Promise.reject()})}function z_(n,e,t=null){return o(this,null,function*(){let i=N.current();if(i){let r=yield le.getOkIdsByExternalIds([n]),a=he.getDeviceIdx(n);return i.recordSetRole(v.composeParticipantId(r[0],te.USER,a),e,t)}return Promise.reject()})}function Y_(){return o(this,null,function*(){let n=N.current();return n?n.getStreamInfo():Promise.reject()})}function Q_(n){return o(this,null,function*(){let e=N.current();return e?e.addMovie(n):Promise.reject()})}function X_(n){return o(this,null,function*(){let e=N.current();return e?e.updateMovie(n):Promise.reject()})}function Z_(n){return o(this,null,function*(){let e=N.current();return e?e.removeMovie(n):Promise.reject()})}function eg(n,e){return o(this,null,function*(){let t=N.current();return t?t.updateRooms(n,e):Promise.reject()})}function tg(n,e){return o(this,null,function*(){let t=N.current();return t?t.activateRooms(n,e):Promise.reject()})}function ig(n=null,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 rg(n){return o(this,null,function*(){let e=N.current();return e?e.removeRooms(n):Promise.reject()})}function ag(n){l.statisticsInterval=n;let e=N.current();if(e)return e.updateStatisticsInterval()}function ng(n){ja.disableLog(!n),c.toggle(n)}function sg(n,...e){!l.debugLog||c.send(n,"[external]",...e)}function og(n){return o(this,null,function*(){let e=N.current();if(e)return e.videoEffect(n)})}function cg(n){return o(this,null,function*(){let e=N.current();e&&(yield e.setAudioStream(n))})}function dg(n,e=null,t=null){return o(this,null,function*(){let i=N.current();if(!i)return;let r=t!=null?t:e==null?void 0:e.id,a=null;if(e){let d=(yield le.getOkIdsByExternalIds([e]))[0];if(!d)throw new Error("Could not get user id to set animoji svg");a=v.composeParticipantId(d,te.USER,he.getDeviceIdx(e))}i.setAnimojiSvg(n,a,r)})}function lg(n=null,e,t=!1){return o(this,null,function*(){return ft().getWaitingHall(n,e,t)})}function pg(n,e=!1){return o(this,null,function*(){let t=ft(),i=yield le.getOkIdsByExternalIds([n]);return t.promoteParticipant(v.composeUserId(i[0],te.USER),e)})}function ug(n){return o(this,null,function*(){return ft().getParticipantListChunk(n)})}function mg(n){return o(this,null,function*(){return ft().getParticipants(n)})}function hg(n){return o(this,null,function*(){return ft().feedback(n)})}function _g(n,e){return o(this,null,function*(){return ft().enableFeatureForRoles(n,e)})}function ft(){let n=N.current();if(!n)throw new Error("Conversation not found");return n}function gg(n){return o(this,null,function*(){yield le.removeHistoryRecords(n)})}function fg(){return o(this,null,function*(){let n=N.current();n&&(yield n.startAsr())})}function Sg(){return o(this,null,function*(){let n=N.current();n&&(yield n.stopAsr())})}function vg(n){return o(this,null,function*(){let e=N.current();e&&(yield e.requestAsr(n))})}function Eg(){return l.sdkVersion}export{yi as Api,Fa as ArrayDequeue,wt as BaseApi,xt as BaseLogger,Lt as BaseSignaling,tt as CallDirection,Ye as CallType,Li as ChatRoomEventType,Ni as ConversationFeature,Ui as ConversationOption,Ia as DebugMessageType,Mt as ExternalIdType,da as FacingMode,ne as FatalError,V as HangupReason,k as HangupType,ue as MediaOption,oe as MediaTrackKind,Ce as MediaType,Ue as MuteState,$ as ParticipantState,Y as ParticipantStatus,fs as RecordRole,Nt as RoomsEventType,$e as Signaling,x as SignalingCommandType,Qe as SignalingConnectionType,w as SignalingNotification,de as TransportTopology,it as UserRole,te as UserType,v as Utils,g_ as acceptCall,tg as activateRooms,Q_ as addMovie,I_ as addParticipant,Cs as addParticipantInternal,__ as authorize,c_ as browser,Es as callInternal,m_ as callTo,R_ as captureScreen,ys as captureScreenAndAudio,y_ as captureVmoji,U_ as changeConversationOptions,C_ as changeDevice,k_ as changeParticipantState,D_ as changePriorities,og as changeVideoEffect,V_ as chatHistory,B_ as chatMessage,As as chatMessageInternal,H_ as createJoinLink,F_ as customData,Ds as customDataInternal,ng as debug,sg as debugMessage,f_ as declineCall,_g as enableFeatureForRoles,hg as feedback,$_ as forceRelayPolicy,W_ as getAnonymTokenByLink,ug as getParticipantListChunk,mg as getParticipants,Y_ as getStreamInfo,lg as getWaitingHall,w_ as grantRoles,Ps as grantRolesInternal,E_ as hangup,u_ as init,S_ as joinCall,v_ as joinCallByLink,Ts as joinCallInternal,x_ as muteParticipant,bs as muteParticipantInternal,L_ as pinParticipant,Ms as pinParticipantInternal,h_ as processPush,Is as processPushInternal,pg as promoteParticipant,z_ as recordSetRole,gg as removeHistoryRecords,G_ as removeJoinLink,Z_ as removeMovie,T_ as removeParticipant,Rs as removeParticipantInternal,rg as removeRooms,vg as requestAsr,Ss as setApi,cg as setAudioStream,A_ as setLocalResolution,d_ as setLogger,N_ as setMediaModifiers,vs as setSignalingFactory,ag as setStatisticsInterval,l_ as setVideoEffects,P_ as setVideoStream,p_ as setVmoji,dg as setVmojiSvg,K_ as setVolume,fg as startAsr,j_ as startConversation,q_ as startStream,Sg as stopAsr,J_ as stopStream,ig as switchRoom,M_ as toggleLocalAudio,b_ as toggleLocalVideo,O_ as updateDisplayLayout,X_ as updateMovie,eg as updateRooms,Eg as version};
|
|
7
|
+
var Va=Object.defineProperty,Fa=Object.defineProperties;var ja=Object.getOwnPropertyDescriptors;var Tr=Object.getOwnPropertySymbols;var Ha=Object.prototype.hasOwnProperty,Ga=Object.prototype.propertyIsEnumerable;var Cr=Math.pow,Rr=(s,r,e)=>r in s?Va(s,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[r]=e,Re=(s,r)=>{for(var e in r||(r={}))Ha.call(r,e)&&Rr(s,e,r[e]);if(Tr)for(var e of Tr(r))Ga.call(r,e)&&Rr(s,e,r[e]);return s},qe=(s,r)=>Fa(s,ja(r));var c=(s,r,e)=>new Promise((t,i)=>{var a=p=>{try{o(e.next(p))}catch(u){i(u)}},n=p=>{try{o(e.throw(p))}catch(u){i(u)}},o=p=>p.done?t(p.value):Promise.resolve(p.value).then(a,n);o((e=e.apply(s,r)).next())});import La from"webrtc-adapter";var St=class{createJoinLink(r){return c(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(r){return c(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(r,e){return c(this,null,function*(){return""})}log(r){}prepareUserIds(r){return c(this,null,function*(){})}getCachedOkIdByExternalId(r){return null}cacheExternalId(r,e){}hangupConversation(r){}removeHistoryRecords(r){return c(this,null,function*(){})}cleanup(){}};var vt=class{log(r,e,t=!1){}destroy(){}};var ie=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(r,...e){if(this._handlers.hasOwnProperty(r))for(let t of this._handlers[r])t.apply(this,e)}addEventListener(r,e){if(typeof e!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(r)||(this._handlers[r]=[]),this._handlers[r].push(e),{dispose:this.removeEventListener.bind(this,r,e)}}removeEventListener(r,e){if(!this._handlers.hasOwnProperty(r))return;e||delete this._handlers[r];let t=this._handlers[r].indexOf(e);t>=0&&this._handlers[r].splice(t,1)}subscribe(r,e,t){let i=r.addEventListener(e,t);this._listeners.push(i)}unsubscribe(){this._listeners.forEach(r=>{r.dispose()})}};var Et=class extends ie{get ready(){return!0}setParticipantIdRegistry(r){}requestRealloc(){}setEndpoint(r){}setConversationId(r){}readyToSend(){}cleanup(){}requestTestMode(r,e){}getNextCommandSequenceNumber(){return 0}};var yr=(t=>(t.INCOMING="INCOMING",t.OUTGOING="OUTGOING",t.JOINING="JOINING",t))(yr||{}),Je=yr;var Pr=(t=>(t.USER="USER",t.GROUP="GROUP",t.CHAT="CHAT",t))(Pr||{}),We=Pr;var br=(e=>(e.ATTENDEE="ATTENDEE",e.HAND_UP="HAND_UP",e))(br||{}),Ni=br;var Mr=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t.MOVIE_SHARE="MOVIE_SHARE",t))(Mr||{}),Ui=Mr;var Ar=(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))(Ar||{}),Bi=Ar;function Dr(s,r){if(s.length!==r.length)return!1;for(let e of s)if(!r.includes(e))return!1;return!0}function kr(s,r){let e=new Set(s);for(let[t,i]of Object.entries(r))i?e.add(t):e.delete(t);return Array.from(e)}var Or=(D=>(D.CAMERA_PERMISSION="camera",D.MIC_PERMISSION="mic",D.CAMERA_ACCESS="cameralock",D.MIC_ACCESS="miclock",D.MIC_NOT_FOUND="nomic",D.SCREEN_PERMISSION="screenpermission",D.SCREEN_ACCESS="screenlock",D.CONNECTION="connection",D.NETWORK="network",D.UNKNOWN="unknown",D.UNSUPPORTED="unsupported",D.SIGNALING_FAILED="signalingfailed",D.API="api",D.AUTH="auth",D))(Or||{}),re=Or;var wr=(Y=>(Y.CANCELED="CANCELED",Y.REJECTED="REJECTED",Y.REMOVED="REMOVED",Y.HUNGUP="HUNGUP",Y.MISSED="MISSED",Y.BUSY="BUSY",Y.FAILED="FAILED",Y.NETWORK_ERROR="NETWORK_ERROR",Y.KILLED="KILLED",Y.BANNED="BANNED",Y.HAS_ACTIVE_CALL="HAS_ACTIVE_CALL",Y.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",Y.NOT_FRIENDS="NOT_FRIENDS",Y.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",Y.CALLER_IS_REJECTED="CALLER_IS_REJECTED",Y.UNKNOWN_ERROR="UNKNOWN_ERROR",Y.UNSUPPORTED="UNSUPPORTED",Y.OLD_VERSION="OLD_VERSION",Y.SERVICE_DISABLED="SERVICE_DISABLED",Y.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",Y.SOCKET_CLOSED="SOCKET_CLOSED",Y.ENDED="ENDED",Y.KILLED_WITHOUT_DELETE="KILLED_WITHOUT_DELETE",Y.ANOTHER_DEVICE="ANOTHER_DEVICE",Y))(wr||{}),O=wr;var xr=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.SCREEN_SHARING="SCREEN_SHARING",n.MOVIE_SHARING="MOVIE_SHARING",n.AUDIO_SHARING="AUDIO_SHARING",n.ANIMOJI="ANIMOJI",n))(xr||{}),de=xr;var Lr=(t=>(t.UNMUTE="UNMUTE",t.MUTE="MUTE",t.MUTE_PERMANENT="MUTE_PERMANENT",t))(Lr||{}),ke=Lr;var Nr=(i=>(i.CALLED="CALLED",i.ACCEPTED="ACCEPTED",i.REJECTED="REJECTED",i.HUNGUP="HUNGUP",i))(Nr||{}),W=Nr;var Ur=(t=>(t.UPDATE="UPDATE",t.REMOVE="REMOVE",t.ACTIVATE="ACTIVATE",t))(Ur||{}),Ut=Ur;var Br=(i=>(i.START="start",i.ACCEPT="accept",i.JOIN="join",i.RETRY="retry",i))(Br||{}),Ke=Br;var Vr=(t=>(t.NOTIFICATION="NOTIFICATION",t.FAILED="FAILED",t.RECONNECT="RECONNECT",t))(Vr||{}),Se=Vr;var Fr=(B=>(B.TRANSMITTED_DATA="transmitted-data",B.ACCEPTED_CALL="accepted-call",B.HUNGUP="hungup",B.PARTICIPANT_ADDED="participant-added",B.PARTICIPANT_JOINED="participant-joined",B.CLOSED_CONVERSATION="closed-conversation",B.MEDIA_SETTINGS_CHANGED="media-settings-changed",B.PARTICIPANT_STATE_CHANGED="participant-state-changed",B.RATE_CALL_DATA="rate-call-data",B.FEATURE_SET_CHANGED="feature-set-changed",B.TOPOLOGY_CHANGED="topology-changed",B.PRODUCER_UPDATED="producer-updated",B.CONSUMER_ANSWERED="consumer-answered",B.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",B.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",B.SETTINGS_UPDATE="settings-update",B.VIDEO_QUALITY_UPDATE="video-quality-update",B.REGISTERED_PEER="registered-peer",B.SWITCH_MICRO="switch-micro",B.RECORD_STARTED="record-started",B.RECORD_STOPPED="record-stopped",B.REALLOC_CON="realloc-con",B.AUDIO_ACTIVITY="audio-activity",B.SPEAKER_CHANGED="speaker-changed",B.STALLED_ACTIVITY="stalled-activity",B.CHAT_MESSAGE="chat-message",B.CUSTOM_DATA="custom-data",B.ROLES_CHANGED="roles-changed",B.MUTE_PARTICIPANT="mute-participant",B.PIN_PARTICIPANT="pin-participant",B.OPTIONS_CHANGED="options-changed",B.NETWORK_STATUS="network-status",B.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",B.PROMOTE_PARTICIPANT="promote-participant",B.CHAT_ROOM_UPDATED="chat-room-updated",B.PROMOTION_APPROVED="promotion-approved",B.JOIN_LINK_CHANGED="join-link-changed",B.FEEDBACK="feedback",B.MOVIE_UPDATE_NOTIFICATION="movie-update-notification",B.MOVIE_SHARE_INFO="movie-share-info",B.MOVIE_SHARE_STARTED="movie-share-started",B.MOVIE_SHARE_STOPPED="movie-share-stopped",B.ROOM_UPDATED="room-updated",B.ROOMS_UPDATED="rooms-updated",B.ROOM_PARTICIPANTS_UPDATED="room-participants-updated",B.FEATURES_PER_ROLE_CHANGED="features-per-role-changed",B.ASR_STARTED="asr-started",B.ASR_STOPPED="asr-stopped",B))(Fr||{}),w=Fr;var jr=(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))(jr||{}),R=jr;var Hr=(e=>(e.AUDIO_MIX="audio-mix",e.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",e))(Hr||{}),Oe=Hr;var Gr=(e=>(e.NO_AVAILABLE_TRACKS="no-available-tracks",e.UNKNOWN_ERROR="unknown-error",e))(Gr||{}),Wr=Gr;function Kr(s){switch(s){case 1:return"no-available-tracks";default:return"unknown-error"}}var $r=(e=>(e.CREATOR="CREATOR",e.ADMIN="ADMIN",e))($r||{}),ze=$r;function Bt(s,r){if(s.length!==r.length)return!1;for(let e of s)if(!r.includes(e))return!1;return!0}var qr=(e=>(e.USER="USER",e.GROUP="GROUP",e))(qr||{}),z=qr;var ri=class{constructor(){this._items=[]}get length(){return this._items.length}push(r){this._items.push(r)}shift(){return this._items.shift()||null}bisect(){let r=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(r)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(r,e)=>e instanceof Error?String(e):e):""}};var Jr=2*1024*1024,Wa=512*1024,Vt=100*1024,Ka=5,Fi="_okcls_logs_session_",$a=3e4,ji=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=Jr;try{let r=window.localStorage;for(let e of Object.keys(r)){if(e.indexOf(Fi)!==0)continue;let t=r.getItem(e);if(!t){zr(e);continue}let i=Qr(t);this.add(e,i)}}catch(r){console.error("Storage is blocked",r),this._storageSize=0}this._items.sort((r,e)=>r.date-e.date),this.cleanup(Vt)}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(r){this._storageSize=r}add(r,e){let t=parseInt(r.replace(Fi,""),10);this._itemsSize+=e,this._items.push({key:r,size:e,date:t})}deleteOldestItem(){let r=this._items.shift();r&&(zr(r.key),this._itemsSize-=r.size)}cleanup(r){for(;this.length&&(this.size>Jr||this.length>Ka-1||this.size+r>this.available);)this.deleteOldestItem()}};function Yr(){return`${Fi}${Date.now()}`}function Qr(s){return new Blob([s]).size}function zr(s){try{window.localStorage.removeItem(s)}catch(r){console.error("Failed to remove log from storage",r)}}function Hi(){let s=nt.toString();if(!Ie.available||!s)return;let r=Qr(s);Ie.cleanup(r);try{window.localStorage.setItem(ai,s)}catch(e){if(console.warn("Failed to write log to storage",e),Ie.storageSize=Ie.size+r,Ie.cleanup(Vt+r),Ie.available>=Vt+r){Hi();return}if(r>Vt){nt.bisect(),Hi();return}Ie.storageSize=0;return}r>Wa&&(Ie.add(ai,r),ai=Yr(),nt.clear(),Ie.cleanup(Vt))}function Gi(){!Ie.available||!nt.length||Hi()}function qa(s=!1){let r=[];try{let i=window.localStorage;for(let n of Ie.items){let o=i.getItem(n.key);r.push(o)}let a=nt.toString();a&&r.push(a)}catch(i){console.error("Storage is blocked",i)}let e=`[${r.join(",")}]`;if(s)return e;let t=`logs_${Date.now()}.json`;return Ja(e,t),t}function Ja(s,r){let e=document.createElement("a"),t=new Blob([s],{type:"text/json"});e.href=URL.createObjectURL(t),e.download=r,e.click()}function Xr(s,r){if(!Ie.available)return;let e=new Date;nt.push({t:e.getTime(),l:s,d:r,h:e.toLocaleString("ru-RU",{dateStyle:"short",timeStyle:"long"})}),Vi||(Vi=window.setTimeout(()=>{Vi=null,Gi()},$a))}function Wi(){Ie||(Ie=new ji,nt=new ri,ai=Yr(),window.addEventListener("beforeunload",Gi))}var Ie,nt,ai,Vi=null;window.__VKCallsSDKLogs__=(s=!1)=>(Ie||Wi(),Gi(),qa(s));import Zr from"@vkontakte/libvpx";var S=class extends vt{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let a={};typeof t!="undefined"&&(a.param=t),this._logInternal(e,a,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let a={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(a),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){S._instance||(S._instance=new S(e,t))}static log(e,t,i=!1){S._instance&&S._instance.log(e,t,i)}static logCustom(e,t,i=!1){S._instance&&S._instance.logCustom(e,t,i)}static destroy(){S._instance&&S._instance.destroy(),S._instance=null}};var we=class{constructor(){this._worker=null}_createWorker(n,o){return c(this,arguments,function*(r,e,t=[],i={},a=[]){return new Promise((p,u)=>{let _=t.join(","),v=new Blob([r,`exports.default(${_});`],{type:"application/javascript; charset=utf-8"}),b=window.URL.createObjectURL(v);this._worker=new Worker(b),this._worker.onmessage=k=>{switch(k.data.type){case"ready":p();break;case"error":u(k.data.error);break;case"frame":e(k.data);break;case"debug":d.debug(k.data.message);break;case"log_error":S.log(R.ERROR,k.data.message);break}},this._sendToWorker("init",i,a)})})}_removeWorker(){var r;(r=this._worker)==null||r.terminate(),this._worker=null}_sendToWorker(r,e={},t=[]){var i;(i=this._worker)==null||i.postMessage(Object.assign({type:r},e),t)}static isBrowserSupported(){throw new Error("Not implemented")}};var st=class extends we{init(r){return c(this,null,function*(){d.debug("LibVPxDecoder started"),yield this._createWorker('"use strict";var exports=(()=>{var u=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var h=(a,t)=>{for(var e in t)u(a,e,{get:t[e],enumerable:!0})},D=(a,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of x(t))!M.call(a,s)&&s!==e&&u(a,s,{get:()=>t[s],enumerable:!(o=R(t,s))||o.enumerable});return a};var V=a=>D(u({},"__esModule",{value:!0}),a);var F={};h(F,{default:()=>A});var A=(a,t)=>{let e=null,o=null,s=!0;function m(){return a({locateFile:t}).then(r=>o=r)}function b(r,g,l,y,E){if(!o){self.postMessage({type:"log_error",message:"decoder-init-fail-libvpx"}),self.postMessage({type:"frame",error:"Fatal initialization error"});return}if(s!==l&&(s=l,e&&(e=null,self.postMessage({type:"debug",message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:"debug",message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new o.VpxDecoder,e.debug(E),!e.init(l?o.VpxType.VP9:o.VpxType.VP8))){e=null,self.postMessage({type:"frame",error:"Decoder failed to create"});return}try{e.allocateBuffer(g.byteLength).set(new Uint8Array(g))}catch(n){self.postMessage({type:"debug",message:n}),e=null,self.postMessage({type:"frame",error:String(n)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:"frame",error:"Decode failed"});return}let p=e.getImageBuffer();if(!p){self.postMessage({type:"frame",error:"No decoded data"});return}let d=e.getImageWidth(),c=e.getImageHeight();e.nextImage()&&(self.postMessage({type:"debug",message:"LibVPxDecoder dropped frame"}),self.postMessage({type:"log_error",message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(p.byteLength);if(i.set(p),y){let n=new ImageData(i,d,c);createImageBitmap(n,0,0,d,c).then(f=>{self.postMessage({type:"frame",data:f},[f]),f.close()})}else self.postMessage({type:"frame",data:i.buffer,width:d,height:c},[i.buffer])}m().then(()=>{self.onmessage=r=>{switch(r.data.type){case"frame":b(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:"ready"})}).catch(r=>{self.postMessage({type:"error",error:String(r)})})};return V(F);})();\n',e=>{if(e.error)d.warn("LibVPxDecoder",e.error);else if(e.data instanceof ArrayBuffer){let t=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);r(t)}else r(e.data)},[Zr,Zr.getUrl])})}decodeFrame(r,e,t,i){let a="ImageBitmap"in window;this._sendToWorker("frame",{timestamp:r,data:e.buffer,isVP9:t,keyFrame:i,useImageBitmap:a,debug:d.enabled()},[e.buffer])}destroy(){this._removeWorker(),d.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var ea=typeof Object.fromEntries=="function"?Object.fromEntries:function(s){if(!s||!s[Symbol.iterator])throw new Error("Object.fromEntries() requires a single iterable argument");let r={};for(let[e,t]of s)r[e]=t;return r};function ta(s){return c(this,null,function*(){return new Promise((r,e)=>{let t=new FileReader;t.onload=i=>{r(i.target.result)},t.onerror=e,t.readAsArrayBuffer(s)})})}var It=":",si="d",Ya=533,Ki="a=fmtp:",Qa="sps-pps-idr-in-keyframe=1",$i;(wi=>{function s(E,T,m,A,M,U=!1,ee=!1){let se=/[\r\n]+/,Te=`\r
|
|
8
|
+
`;if(!T&&!m&&!A&&!ee&&!U&&!M)return E;function Le(K){let ue=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],fe="a=rtcp-fb:111",te=K.findIndex(Q=>Q.startsWith(fe));return~te&&(K[te]=K[te]+Te+ue.join(Te)),K}function je(K,ue,fe){let te=K.split(" "),Q=te.slice(0,3),oe;for(oe=3;oe<te.length;oe++)fe.includes(te[oe])&&Q.push(te[oe]);for(oe=3;oe<te.length;oe++)!fe.includes(te[oe])&&!ue.includes(te[oe])&&Q.push(te[oe]);return Q.join(" ")}function Me(K,ue){let fe=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),te,Q=[];for(te=0;te<K.length;++te){let oe=K[te].match(fe);oe&&oe.length===3&&oe[2]===ue&&Q.push(oe[1])}return Q}function Ae(K,ue,fe,te){let Q,oe="m="+ue;for(Q=0;Q<K.length;++Q)if(K[Q].startsWith(oe)){K[Q]=je(K[Q],fe,te);break}}function De(K,ue){let fe=new RegExp(Ki+"(\\d+)");for(let te=0;te<K.length;++te){let Q=K[te].match(fe);if(Q&&Q.length===2&&ue.includes(Q[1])){let oe=K[te].trim()===Ki+Q[1]?" ":";";K[te]+=oe+Qa}}}function Ne(K){let ue=Me(K,"H264");if(m){let fe=ue.slice(0),te=new RegExp(Ki+"(\\d+) apt=(\\d+)"),Q;for(Q=0;Q<K.length;++Q){let He=K[Q].match(te);He&&He.length===3&&fe.includes(He[2])&&fe.push(He[1])}let oe=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(Q=K.length;Q--;){let He=K[Q].match(oe);He&&He.length===3&&fe.includes(He[2])&&K.splice(Q,1)}Ae(K,"video",fe,[])}else T&&Ae(K,"video",[],ue),M&&De(K,ue)}function L(K){let ue=Me(K,"VP9");A&&Ae(K,"video",[],ue)}function B(K){let ue=Me(K,"red");ue.length>0&&Ae(K,"audio",[],ue)}let ft=E.split(se);return(m||T||M)&&Ne(ft),A&&L(ft),ee&&B(ft),U&&Le(ft),ft.join(Te)}wi.patchLocalSDP=s;function r(E){return y.browserName()==="Firefox"&&Number(y.browserVersion())<60&&(E=E.replace("m=application 9 UDP/DTLS/SCTP webrtc-datachannel","m=application 9 DTLS/SCTP 5000").replace("a=sctp-port:5000","a=sctpmap:5000 webrtc-datachannel 256")),E}wi.patchRemoteSDP=r;function e(E){return E?`${E.type||"WEB_SOCKET"}_${E.id}`:"_"}wi.getPeerIdString=e;function t(E,T){return E&&E.id===T.id&&(E.type||"WEB_SOCKET")===(T.type||"WEB_SOCKET")}wi.comparePeerId=t;function i(E){return c(this,null,function*(){return!E||!E.getStats?Promise.resolve(null):E.getStats(null).then(T=>{let m=null,A=null;if(T.forEach(M=>{M.type==="transport"&&M.selectedCandidatePairId?A=T.get(M.selectedCandidatePairId):M.type==="candidate-pair"&&M.state==="succeeded"&&!A&&(!M.hasOwnProperty("selected")||M.selected)&&(A=M)}),A&&A.localCandidateId){let M=T.get(A.localCandidateId);M&&(m={type:M.candidateType,ip:M.ip||M.ipAddress,port:M.port||M.portNumber})}return m}).catch(()=>null)})}wi.getPeerConnectionHostInfo=i;let a=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function o(E,T){let m=String(E);return n.test(m)?(d.warn(`Already composite id [${E}] type supplied [${T}]`),m):T===z.GROUP?"g"+m:T===z.USER?"u"+m:(d.warn(`Unknown type [${T}] for id [${E}]`),m.match(a)?"u"+m:m)}wi.composeUserId=o;function p(E,T,m){let A=o(E,T);return u(A,m)}wi.composeParticipantId=p;function u(E,T){return T?E+It+si+T:E}wi.compose=u;function _(E){return p(E.id,E.idType||z.USER,E.deviceIdx||0)}wi.composeId=_;function v(E){return E.participant?_(E.participant):p(E.participantId,E.participantType||z.USER,E.deviceIdx||0)}wi.composeMessageId=v;function b(E){let T=String(E),m=T.match(n);return m?{id:Number(m[2]),type:m[1]==="g"?z.GROUP:z.USER}:(d.warn(`Unsupported compositeId [${E}]`),{id:Number(T),type:z.USER})}wi.decomposeId=b;function k(E){let T=E.split(It+si);return{compositeUserId:T[0],deviceIdx:T.length>1?parseInt(T[1],10):0}}wi.decomposeParticipantId=k;function D(){var ee,se;let E=(se=(ee=window.crypto)==null?void 0:ee.randomUUID)==null?void 0:se.call(ee);if(E)return E;let T="0123456789abcdefghijklmnopqrstuvwxyz".split(""),m=new Array(36),A=0,M,U;for(U=0;U<36;U++)U===8||U===13||U===18||U===23?m[U]="-":U===14?m[U]="4":(A<=2&&(A=33554432+Math.random()*16777216|0),M=A&15,A=A>>4,m[U]=T[U===19?M&3|8:M]);return m.join("")}wi.uuid=D;function $(E,T){let m;function A(){let M=this,U=arguments;m&&window.clearTimeout(m),m=window.setTimeout(()=>{E.apply(M,U)},T)}return A}wi.throttle=$;function j(E){if(!window.BigInt)return null;let T="",m=E.split(`
|
|
9
|
+
`);for(let U of m)if(U.startsWith("a=fingerprint")){let ee=U.split(" ");if(ee.length===2){T=ee[1];break}}if(!T)return BigInt(-1);let A=T.split(":"),M=BigInt(0);for(let U=Math.min(7,A.length-1);U>=0;U--){let ee=BigInt(parseInt(A[U],16));M<<=BigInt(8),M|=ee}return BigInt.asIntN(64,M)}wi.sdpFingerprint=j;function he(E){return c(this,null,function*(){return new Promise(T=>window.setTimeout(T,E))})}wi.delay=he;function G(E,T,m){let A=[];return E.getSenders().forEach(M=>X(T,M,M.track,m,A)),A}wi.applySettings=G;function X(E,T,m,A,M){var U;if(E&&m&&m.kind==="video"){let ee=m.getSettings();if(ee){let se=E.maxBitrateK?E.maxBitrateK*1024:null,Te=ee.width,Le=ee.height,je=Te&&Le&&E.maxDimension?Math.max(1,Math.max(Te,Le)/E.maxDimension):null,Me=E.maxFramerate?E.maxFramerate:null;if(Te&&Le&&E.maxDimension&&E.maxDimension>Math.max(Te,Le)){let L=Math.round(Te*Le/256),B=(Math.round(L*Ya/1e4)+1)*1e4;se=se===null?B:Math.min(B,se)}let Ae=E.degradationPreference?E.degradationPreference:"balanced",De=A[m.id];if(De&&De.bitrate===se&&De.scaleResolutionDownBy===je&&De.maxFramerate===Me&&De.degradationPreference===Ae){M[m.id]=De;return}M[m.id]={bitrate:se,scaleResolutionDownBy:je,maxFramerate:Me,degradationPreference:Ae};let Ne=T.getParameters();Ne.encodings||(Ne.encodings=[{}]),Ne.encodings.forEach(L=>{se?L.maxBitrate=se:delete L.maxBitrate,je?L.scaleResolutionDownBy=je:delete L.scaleResolutionDownBy,Me?L.maxFramerate=Me:delete L.maxFramerate}),Ne.degradationPreference=Ae,(U=T.setParameters)==null||U.call(T,Ne)}}}wi.applyVideoTrackSettings=X;function _e(E,T){Array.isArray(T)||(T=[T]);for(let m of T)if(E.includes(m))return!0;return!1}wi.includesOneOf=_e;function Ee(E){var T;return Object.entries(((T=E.participantState)==null?void 0:T.state)||{}).reduce((m,[A,M])=>(E.participantState&&(m[A]={ts:E.participantState.stateUpdateTs[A],state:M}),m),{})}wi.mapParticipantState=Ee;function at(E){let T=E.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?T.filter(m=>!m.uid.observer):T}wi.mapSharedParticipants=at;function ii(E,T){let m=Object.keys(E),A=Object.keys(T);if(m.length!==A.length)return!1;for(let M of m)if(!A.hasOwnProperty(M)||E[M].state!==T[M].state||E[M].ts!==T[M].ts)return!1;return!0}wi.isEqualParticipantState=ii;function Y(E,T){let m=Object.keys(E),A=Object.keys(T);if(m.length!==A.length)return!1;for(let M of m)if(!T.hasOwnProperty(M)||E[M]!==T[M])return!1;return!0}wi.isObjectsEquals=Y;function Sr(E,T){if(E.length!==T.length)return!1;for(let m of E)if(T.indexOf(m)<0)return!1;return!0}wi.isArraysEquals=Sr;function vr(E){return!Object.keys(E).length}wi.isEmptyObject=vr;function ki(E,T){if(!E&&!T)return 0;if(!E||!T)return E?-1:1;return A(T.rank,E.rank)||A(E.ts,T.ts)||m(E,T);function m(M,U){let ee={[z.USER]:0,[z.GROUP]:1},{compositeUserId:se,deviceIdx:Te}=k(M.id),{compositeUserId:Le,deviceIdx:je}=k(U.id),{id:Me,type:Ae}=b(se),{id:De,type:Ne}=b(Le);return A(ee[Ae],ee[Ne])||A(Me,De)||A(Te,je)}function A(M,U){return M<U?-1:M===U?0:1}}wi.participantMarkerCompare=ki;function q(E,T){let m=Object.entries(E).filter(([,A])=>Array.isArray(T)?!T.includes(A):A!==T);return ea(m)}wi.objectFilterOutValues=q;function Er(E,T,m){let A=m;for(let M in E)E.hasOwnProperty(M)&&(A=T(A,E[M],M));return A}wi.objectReduce=Er,wi.setImmediate=(()=>{let E=1,T={},m=null;return typeof MessageChannel!="undefined"&&(m=new MessageChannel,m.port1.onmessage=A=>{let M=A.data;T[M]&&(T[M](),delete T[M])}),function(A){if(m&&document.visibilityState==="hidden"){let U=E;return E=E>=Number.MAX_SAFE_INTEGER?1:E+1,T[U]=A,m.port2.postMessage(U),()=>{T[U]&&delete T[U]}}let M=setTimeout(A,0);return()=>clearTimeout(M)}})()})($i||($i={}));var I=$i;function ia(s,r){if(s.isAudioEnabled!==r.isAudioEnabled||s.isVideoEnabled!==r.isVideoEnabled||s.isScreenSharingEnabled!==r.isScreenSharingEnabled||s.isFastScreenSharingEnabled!==r.isFastScreenSharingEnabled||s.isAudioSharingEnabled!==r.isAudioSharingEnabled||s.isAnimojiEnabled!==r.isAnimojiEnabled||s.videoStreams.length!==r.videoStreams.length)return!1;for(let e of s.videoStreams)if(!r.videoStreams.find(t=>t.id===e.id&&t.source===e.source))return!1;return!0}function me(s){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,isFastScreenSharingEnabled:!1,isAudioSharingEnabled:!1,isAnimojiEnabled:!1,videoStreams:[]},s||{})}var ra=s=>s.stop(),aa=s=>s.getTracks().forEach(ra),qi=s=>s.getVideoTracks().forEach(ra),na=s=>s.getVideoTracks()[0].clone();var V=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(O).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,V)}};var Ue=(i=>(i.audio="audio",i.video="video",i.screen="screen",i.audioshare="audioshare",i))(Ue||{}),oi=class extends ie{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._audioShareTrack=null;this._sendVideoTrack=null;this._mediaSettings=me();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._sourceBusy=!1;this._animojiEnabled=!1;this._initDeviceChangeListener(),l.audioShare&&(this._audioShareTrack=this.getSilentAudioShareTrack())}request(){return c(this,arguments,function*(e=[de.AUDIO],t=!0){if(this._stream)return;let i=e.includes(de.VIDEO),a=e.includes(de.AUDIO),n=e.includes(de.ANIMOJI);if(!y.isBrowserSupported())throw new V(re.UNSUPPORTED);try{this._stream=yield y.getUserMedia(i,a,t),this._mediaSettings.isVideoEnabled=i&&this._stream.getVideoTracks().filter(o=>o.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=a&&this._stream.getAudioTracks().filter(o=>o.enabled).length>0||!1,this._mediaSettings.isAnimojiEnabled=n&&!this._mediaSettings.isVideoEnabled||!1,this._animojiEnabled=n}catch(o){throw new V(o)}})}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}getAnimojiEnabled(){return this._animojiEnabled}addTrackToPeerConnection(e,t,i,a){let n=this.getStream(),o=this._getSendAudioTrack(),p=this.getSendVideoTrack(i);if(!n||!o&&!p&&!t)throw new Error("No local stream found");if(o&&!t){if(a){let{codecs:u}=RTCRtpSender.getCapabilities("audio"),_="audio/red",v=48e3,b=u.findIndex(k=>k.mimeType===_&&k.clockRate===v);if(b>=0){let k=[];k.push(u[b]);for(let D=0;D<u.length;D++)D!==b&&k.push(u[D]);e.getTransceivers().forEach(D=>D.setCodecPreferences(k))}}e.addTrack(o,n)}p&&!t&&e.addTrack(p,n)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return c(this,null,function*(){switch(e){case"videoinput":if(this._mediaSettings.isVideoEnabled)return this._stopAndRemoveTrackVideoStreamBackup(),this._changeVideoInput();break;case"audioinput":if(this._mediaSettings.isAudioEnabled)return this._changeAudioInput();break;default:return Promise.reject(re.UNKNOWN)}})}stopVideoTrack(){return c(this,null,function*(){var t,i;if(!this._mediaSettings.isVideoEnabled)return;let e=(i=(t=this._stream)==null?void 0:t.getVideoTracks())==null?void 0:i[0];if(e&&l.videoEffects)try{yield l.videoEffects.setEffect(null,e)}catch(a){}this._stopAndRemoveTrackVideoStreamBackup(),this._stopLocalTrack("video")})}setVideoStream(e,t){return c(this,null,function*(){return t?this._changeScreen(!1,!1,e):(this._stopAndRemoveTrackVideoStreamBackup(),this._changeVideoInput(e))})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=I.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);this._onDeviceChange=()=>c(this,null,function*(){if(!this._stream)return;let a=y.getSavedMicrophone(),n=y.getSavedCamera(),o=a==null?void 0:a.deviceId,p=n==null?void 0:n.deviceId;if(!o&&!p)return;let u=yield navigator.mediaDevices.enumerateDevices();!e&&o&&(e=!u.find(_=>_.deviceId===o)),!t&&p&&(t=!u.find(_=>_.deviceId===p)),i()}),navigator.mediaDevices.addEventListener("devicechange",this._onDeviceChange)}_destroyDeviceChangeListener(){this._onDeviceChange&&navigator.mediaDevices.removeEventListener("devicechange",this._onDeviceChange)}_changeVideoInput(e=null){return c(this,null,function*(){this._busy();try{let t=e?"stream":"video",i=e||(yield y.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(a=>a.stop());else{l.consumerScreenTrack||(yield this._disableScreenCapture());let a=this._getVideoEffectTrack(i),n=yield this._videoEffect(this._effect,a);this._stopLocalTrack("video"),S.log(R.DEVICE_CHANGED,t),d.log("Video stream changed"),yield this._replaceLocalTrack(n),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw S.log(R.ERROR,"change_video"),d.warn("Camera change failed",t),t}finally{this._free()}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=na(e)),t=this._trackVideoStreamBackup.clone(),qi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),qi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return c(this,null,function*(){return this._changeAudioInput(e)})}_busy(){if(this._sourceBusy)throw S.log(R.ERROR,"change_device"),d.warn("Device change failed: MediaSource is busy"),new Error("MediaSource is busy");this._sourceBusy=!0}_free(){this._sourceBusy=!1}_changeAudioInput(e=null){return c(this,null,function*(){this._busy();try{if(e=e||(yield y.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),S.log(R.DEVICE_CHANGED,"audio"),d.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw S.log(R.ERROR,"change_audio"),d.error("Microphone change failed",t),t}finally{this._free()}})}_changeScreen(e,t,i){return c(this,null,function*(){this._busy();try{if(i=i||(yield y.getScreenMedia(e,t)),i.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.disableScreenCapturing()},!1),!this._stream)i.getTracks().forEach(a=>a.stop());else{let a=i.getVideoTracks()[0],n=l.consumerScreenTrack?a:yield this._videoEffect(null,a);if(S.log(R.DEVICE_CHANGED,"screen"),d.log("Screen capturing started"),this._screenTrack=n,this._mediaSettings.isScreenSharingEnabled=!0,this._mediaSettings.isFastScreenSharingEnabled=e,l.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=l.consumerScreenDataChannel?y.getBlackMediaTrack(l.videoMinWidth,l.videoMinHeight):n,yield this._replaceLocalTrack(n,this._sendVideoTrack)),i.getAudioTracks().length>0){let o=i.getAudioTracks()[0];o.contentHint="music",this._audioShareTrack=o,this._stopLocalTrack("audioshare"),yield this._replaceLocalTrack(o),this._mediaSettings.isAudioSharingEnabled=!0}t&&!this._mediaSettings.isAudioSharingEnabled&&d.debug("Audio share requested but not captured"),this._triggerEvent("SCREEN_STATUS",{track:n,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(a){throw S.log(R.ERROR,"screen"),d.warn("Screen capturing failed",a),a}finally{this._free()}})}_disableScreenCapture(){return c(this,null,function*(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),yield this.stopAudioShareTrack(),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._mediaSettings.isFastScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))})}disableAudioShare(){return c(this,null,function*(){yield this.stopAudioShareTrack(),this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"audioshare",mediaSettings:this._mediaSettings})})}stopAudioShareTrack(){return c(this,null,function*(){if(this._audioShareTrack){this._audioShareTrack.stop();let e=this.getSilentAudioShareTrack();this._stopLocalTrack("audioshare"),yield this._replaceLocalTrack(e),this._mediaSettings.isAudioSharingEnabled=!1}})}getSilentAudioShareTrack(){let e=y.getSilentMediaTrack();return e.contentHint="music",e.stop(),e}_replaceLocalTrack(e,t){return c(this,null,function*(){if(!this._stream)return;let i=!1;this._stream.getTracks().forEach(a=>{var n,o;a.kind===e.kind&&a.contentHint===e.contentHint&&((n=this._stream)==null||n.removeTrack(a),(o=this._stream)==null||o.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t),i=!0)}),i||(this._stream.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})}_stopLocalTrack(e){var t;if(this._stream){if(e==="audioshare")return(t=this._stream.getTracks().find(i=>i.contentHint==="music"))==null?void 0:t.stop();this._stream.getTracks().forEach(i=>{i.kind===e&&i.contentHint!=="music"&&i.stop()})}}_videoEffect(e,t){return c(this,null,function*(){if(!l.videoEffects)return t;try{return S.log(R.DEVICE_CHANGED,`effect_${e}`),l.videoEffects.setEffect(e,t)}catch(i){return d.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&&(aa(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return c(this,null,function*(){if(e.captureScreen){yield this._changeScreen(e.fastScreenSharing,e.captureAudio);return}return l.consumerScreenTrack?this._disableScreenCapture():(e.captureAudio||(yield this.disableAudioShare()),this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1))})}disableScreenCapturing(){return c(this,null,function*(){return this.toggleScreenCapturing({captureScreen:!1,fastScreenSharing:!1,captureAudio:!1})})}toggleVideo(e){return c(this,null,function*(){if(!this._stream)return;l.consumerScreenTrack||(yield this._disableScreenCapture());let t;if(e){let i=yield y.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=y.getBlackMediaTrack(l.videoMinWidth,l.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();if(this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._animojiEnabled){this._triggerEvent("ANIMOJI_STATUS",!e);return}this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return c(this,null,function*(){if(!this._stream)return;let t;e?t=(yield y.getUserAudio()).getAudioTracks()[0]:t=y.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}toggleAnimojiCapturing(e){this._animojiEnabled=e,this._mediaSettings.isVideoEnabled||this._triggerEvent("ANIMOJI_STATUS",e)}onAnimojiSender(e){this._mediaSettings.isAnimojiEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}setResolution(e,t){return c(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 c(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks().find(t=>!t.contentHint);if(!e)throw new Error("Local audio track not found");if(e.enabled)return e.applyConstraints({noiseSuppression:l.noiseSuppression})})}videoEffect(e){return c(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 zi="_okcls_",Tt=(()=>{try{let s=Date.now().toString(),r=window.localStorage,e=!1;return r.setItem(s,s),e=r.getItem(s)===s,r.removeItem(s),e?r:null}catch(s){return null}})();function Xa(s){let r=Tt?Tt.getItem(zi+s):null;if(r===null)return null;try{return JSON.parse(r)}catch(e){return null}}function Za(s,r){try{Tt&&Tt.setItem(zi+s,JSON.stringify(r))}catch(e){}}function en(s){Tt&&Tt.removeItem(zi+s)}var Ji;(t=>{function s(i){return Xa(i)||null}t.get=s;function r(i,a){Za(i,a)}t.set=r;function e(i){en(i)}t.remove=e})(Ji||(Ji={}));var Ye=Ji;var Ct=null,Yi=null,hi=[],_i=[],ui=[],Qe=null,Xe=null,er=null,sa=null,tr=!1,gi=!1,ci,Rt,di,Qi=null,Xi="",li=[],Zi=null,oa=navigator.appVersion,tn=navigator.appName,Ce=navigator.userAgent,Ze=(e=>(e.USER="user",e.ENVIRONMENT="environment",e))(Ze||{});(r=>{function s(e){return Object.values(r).includes(e)}r.contains=s})(Ze||(Ze={}));var yt=class{constructor(r,e=!1,t=l.videoMaxWidth,i=l.videoMaxHeight){let a=!1;if(r){a={noiseSuppression:l.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let o;Xe&&(o=Xe.deviceId),typeof r=="string"&&(o=r),o&&(a.deviceId={ideal:o})}let n=!1;if(e){n={width:{min:l.videoMinWidth,max:t,ideal:t},height:{min:l.videoMinHeight,max:i,ideal:i},aspectRatio:{ideal:l.videoAspectRatio},frameRate:{ideal:l.videoFrameRate}};let o;Qe&&(o=Qe.deviceId),typeof e=="string"&&(o=e),o&&(n.deviceId={ideal:o}),l.videoFacingMode&&(n.facingMode={ideal:l.videoFacingMode},delete n.deviceId)}this.audio=a,this.video=n,this.needVideo=!!n}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 r=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||r)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},ir=class extends yt{constructor(e,t,i,a){super(!1,!0);this.captureController="CaptureController"in window?new CaptureController:null,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=i,this.video.displaySurface=l.displaySurface,Be.browserName()==="Safari"&&Number(Be.browserVersion())===16&&(delete this.video.width,delete this.video.height),a&&(this.audio={noiseSuppression:!1,echoCancellation:!1,autoGainControl:!1})}getNative(){return Object.assign(super.getNative(),{systemAudio:"exclude",controller:this.captureController})}};function ca(){return c(this,null,function*(){gi=!1,Ct=null,yield rr(),g.onDeviceChange()})}function rr(){return c(this,null,function*(){return Ct||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Yi&&navigator.mediaDevices.addEventListener&&(Yi=I.throttle(ca,1e3),navigator.mediaDevices.addEventListener("devicechange",Yi)),Ct=navigator.mediaDevices.enumerateDevices().then(s=>{hi=s.filter(i=>i.kind==="videoinput"?(i.label&&(tr=!0),!0):!1),_i=s.filter(i=>i.kind==="audioinput"?(i.label?gi=!0:Be.isMobile()&&Be.browserName()==="Firefox"&&(gi=tr),!0):!1),ui=s.filter(i=>i.kind==="audiooutput");let r=Ye.get("videoinput"),e=Ye.get("audioinput"),t=Ye.get("audiooutput");return Qe=hi.find(i=>i.deviceId===r)||null,Xe=_i.find(i=>i.deviceId===e)||null,er=ui.find(i=>i.deviceId===t)||ui[0]||null,Ct=Promise.resolve(s),s}).catch(()=>(Ct=null,[]))))})}function rn(s){if(Qe&&Xe)return;let r=(e,t)=>{var a;let i=(a=t.getSettings())==null?void 0:a.deviceId;return e.find(n=>n.deviceId===i||n.label===t.label)||null};s==null||s.getTracks().forEach(e=>{var t;if(!Xe&&e.kind==="audio")Xe=r(Be.getMicrophones(),e);else if(e.kind==="video"){Qe||(Qe=r(Be.getCameras(),e));let i=(t=e.getSettings())==null?void 0:t.facingMode;Ze.contains(i)&&(sa=i)}})}function mi(s,r){return c(this,null,function*(){d.debug("Try to get media",JSON.parse(JSON.stringify(s.getNative())));let e=Be.hasPermissions(s.isVideo());!e&&!r&&g.onPermissionsRequested();try{let t=yield navigator.mediaDevices.getUserMedia(s.getNative());return e||(yield ca()),rn(t),t}catch(t){switch(d.error("getUserMedia error",t),t.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":r=s.isVideo()?re.CAMERA_PERMISSION:re.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":r=re.UNKNOWN;break;case"AbortError":case"NotReadableError":r=s.isVideo()?re.CAMERA_ACCESS:re.MIC_ACCESS;break}if(s.canSimplify())return mi(s.simplify(),r);let i=r||re.UNKNOWN;throw g.onPermissionsError(i,t),i}})}function an(s){return c(this,null,function*(){var r;d.debug("Try to get screen",s.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(s.getNative()),t=e==null?void 0:e.getVideoTracks()[0];if(t&&(d.debug("Got display media track",t.id),t.contentHint="text",s.captureController)){let i=(r=t.getSettings())==null?void 0:r.displaySurface;(i==="browser"||i==="window")&&s.captureController.setFocusBehavior("no-focus-change")}return e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw re.SCREEN_PERMISSION;default:throw re.SCREEN_ACCESS}}})}function pi(){return li.length||(li=(()=>{let s,r=!1,e=0,t="0",i=Ce.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return s=/\brv[ :]+(\d+)/g.exec(Ce),["IE",s&&s[1]||"Unknown",r,e,t];if(i[1]==="Safari"){if(s=Ce.match(/\bEdge\/(\d+)/),s)return["Edge",s[1]||"Unknown",r,e,t];if(s=Ce.match(/\bCriOS\/(\d+)/),s)return["Chrome",s[1],!0,Number(s[1]),t];if(s=Ce.match(/\bFxiOS\/(\d+)/),s)return["Firefox",s[1],!1,e,t];if(s=Ce.match(/\bYaBrowser\/(\d+)/),s)return["Yandex",s[1],!1,e,t];if(s=Ce.match(/\bOPT\/(\d+)/),s)return["Opera",s[1],!1,e,t]}if(i[1]==="Chrome"){if(r=!0,e=Number(i[2]),s=Ce.match(/\bOPR\/(\d+)/),s)return["Opera",s[1]||"Unknown",r,e,t];if(s=Ce.match(/\bYaBrowser\/(\d+)/),s)return["Yandex",s[1]||"Unknown",r,e,t];if(s=Ce.match(/\bSferum\/((\d+)(?:\.\d+)*)/),s)return["Sferum",s[1]||"Unknown",r,e,t];if(s=Ce.match(/\bEdge?\/(\d+)/),s)return["Edge",s[1]||"Unknown",r,e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",r,e,t]}return s=Ce.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),s&&s[2]!==void 0&&(t=s[2]),[i[2]?i[1]:tn,s&&s[1]||i[2]||oa,r,e,t]})()),li}var Be;(T=>{function s(){return c(this,null,function*(){let m=()=>{G(),document.removeEventListener("click",m),document.removeEventListener("touchstart",m)};return document.addEventListener("click",m),document.addEventListener("touchstart",m),rr()})}T.init=s;function r(){return hi}T.getCameras=r;function e(){return _i}T.getMicrophones=e;function t(){return ui}T.getOutput=t;function i(){return hi.length>0}T.hasCamera=i;function a(){return _i.length>0}T.hasMicrophone=a;function n(){return Qe}T.getSavedCamera=n;function o(){return Xe}T.getSavedMicrophone=o;function p(){return er}T.getSavedOutput=p;function u(){return sa||l.videoFacingMode||null}T.getVideoFacingMode=u;function _(){return tr}T.hasCameraPermission=_;function v(){return gi}T.hasMicrophonePermission=v;function b(m=!1){return v()?i()&&m?_():!0:!1}T.hasPermissions=b;function k(m=!1,A=!0,M=!0){return c(this,null,function*(){let U=a()&&A,ee=i()&&m,se;if(!U&&!ee)se=new MediaStream;else try{se=yield mi(new yt(U,ee))}catch(Te){se=new MediaStream}return!se.getVideoTracks().length&&M&&se.addTrack(X()),!se.getAudioTracks().length&&M&&se.addTrack(G()),se})}T.getUserMedia=k;function D(m,A){return c(this,null,function*(){let M=m?l.fastScreenShareWidth:window.screen.width,U=m?l.fastScreenShareHeight:window.screen.height,ee=l.getScreenFrameRate(m);return an(new ir(M,U,ee,A))})}T.getScreenMedia=D;function $(m,A=!1){return c(this,null,function*(){let M=A?l.videoEffectMaxWidth:l.videoMaxWidth,U=A?l.videoEffectMaxHeight:l.videoMaxHeight;return mi(new yt(!1,m||!0,M,U))})}T.getUserVideo=$;function j(m){return c(this,null,function*(){return mi(new yt(m||!0,!1))})}T.getUserAudio=j;function he(m,A){return c(this,null,function*(){let U=(yield rr()).find(ee=>ee.kind===m&&ee.deviceId===A);return U?(m==="videoinput"?Qe=U:m==="audioinput"?Xe=U:m==="audiooutput"&&(er=U),Ye.set(m,A),U):null})}T.saveDeviceId=he;function G(){if(!di||di.readyState==="ended"){let m=Oi(),A=m.createMediaStreamDestination(),M=m.createGain();M.gain.value=1e-5,M.connect(A),M.connect(m.destination);let U=m.createOscillator();U.type="sine",U.frequency.value=0,U.connect(M),U.start(),di=A.stream.getAudioTracks()[0]}return Object.assign(di.clone(),{enabled:!1})}T.getSilentMediaTrack=G;function X(m=l.videoMinWidth,A=l.videoMinHeight){Rt||(Rt=document.createElement("canvas")),Rt.width=m,Rt.height=A;let M=Rt.getContext("2d");return M.rect(0,0,m,A),M.fillStyle="black",M.fill(),(!ci||ci.readyState==="ended")&&(ci=Rt.captureStream(l.videoFrameRate).getVideoTracks()[0]),Object.assign(ci.clone(),{enabled:!1})}T.getBlackMediaTrack=X;function _e(){if(ki()==="Edge"&&Number(q())<70)return!1;try{let m=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&m.RTCPeerConnection&&m.RTCIceCandidate&&m.RTCSessionDescription&&m.HTMLCanvasElement&&m.HTMLCanvasElement.prototype.captureStream&&m.RTCRtpSender&&m.RTCRtpSender.prototype.replaceTrack&&m.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(m){return!1}}T.isBrowserSupported=_e;function Ee(){return!!navigator.mediaDevices.getDisplayMedia}T.isScreenCapturingSupported=Ee;function at(){let m=T.browserName()==="Safari"&&T.browserVersion()==="15"&&T.browserSubVersion()==="1",A=T.browserName()==="Opera"&&T.os()==="Windows";return m||A}T.isBrokenH264=at;function ii(){return!(T.baseChromeVersion()&&T.isMobile())}T.canPreferH264=ii;function Y(){var m;return((m=window.RTCRtpTransceiver)==null?void 0:m.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}T.canPreferRed=Y;function Sr(){return Xi||(Xi=(()=>{let m={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 A in m)if(m.hasOwnProperty(A)&&m[A].test(Ce))return A;return"Unknown"})()),Xi}T.os=Sr;function vr(){return Qi===null&&(Qi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(oa)),Qi}T.isMobile=vr;function ki(){return pi()[0]}T.browserName=ki;function q(){return pi()[1]}T.browserVersion=q;function Er(){return pi()[3]}T.baseChromeVersion=Er;function Oi(){return Zi||(Zi=new(window.AudioContext||window.webkitAudioContext)),Zi}T.getAudioContext=Oi;function wi(){return pi()[4]}T.browserSubVersion=wi;function E(){return T.baseChromeVersion()>=105&&!T.isMobile()}T.isAudioShareSupported=E})(Be||(Be={}));var y=Be;var Ve=class extends we{init(r){return c(this,null,function*(){d.debug("WebCodecsDecoder started"),yield this._createWorker('"use strict";var exports=(()=>{var s=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var E=(o,e)=>{for(var t in e)s(o,t,{get:e[t],enumerable:!0})},g=(o,e,t,c)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of m(e))!b.call(o,r)&&r!==t&&s(o,r,{get:()=>e[r],enumerable:!(c=f(e,r))||c.enumerable});return o};var D=o=>g(s({},"__esModule",{value:!0}),o);var V={};E(V,{default:()=>R});var R=o=>{let e=null,t=!0;function c(){self.postMessage({type:"ready"})}function r(d,l,a,i=!1){if(!e||t!==a){if(!i){self.postMessage({type:"debug",message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}t=a,e?self.postMessage({type:"debug",message:`WebCodecsDecoder codec changed to ${a?"VP9":"VP8"}`}):(self.postMessage({type:"debug",message:`WebCodecsDecoder codec ${a?"VP9":"VP8"}`}),e=new VideoDecoder({output:n=>{let u=o?[n]:[];self.postMessage({type:"frame",data:n},u),n.close()},error:n=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:"frame",error:"WebCodecsDecoder failed, reinitialize: "+String(n)})}})),e.configure({codec:a?"vp09.00.50.08":"vp8"})}let p=new EncodedVideoChunk({type:i?"key":"delta",timestamp:d,data:l});e.decode(p)}self.onmessage=d=>{switch(d.data.type){case"init":c();break;case"frame":r(d.data.timestamp,d.data.data,d.data.isVP9,d.data.keyFrame);break}}};return D(V);})();\n',e=>{e.error?d.warn("WebCodecsDecoder",e.error):r(e.data)},[y.baseChromeVersion()>=92])})}decodeFrame(r,e,t,i=!1){this._sendToWorker("frame",{timestamp:r,data:e.buffer,isVP9:t,keyFrame:i},[e.buffer])}destroy(){this._removeWorker(),d.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window}};import{BitStream as nn}from"bit-buffer";var sn=65536,et=class{constructor(r,e){this._chunks=[];this._participantId=r,this._onStream=e}appendChunk(r){let e=this._chunks.length;if(r.start)e&&(d.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!e||(this._chunks[e-1].sequence+1)%sn!==r.sequence){d.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(r),r.end){let t=this._processFrameData(),{width:i,height:a}=et.getFrameSize(t);this._processFrame({timestamp:r.timestamp,frameData:t,isVP9:r.isVP9,keyframe:r.keyframe,width:i,height:a})}}destroy(){this._chunks=[]}_processFrameData(){let r=this._chunks;this._chunks=[];let e=r.reduce((a,n)=>a+n.data.byteLength,0),t=new Uint8Array(e),i=0;for(let a of r)t.set(new Uint8Array(a.data),i),i+=a.data.byteLength;return t}static getFrameSize(r){let e={width:0,height:0},t=new nn(r.buffer);t.bigEndian=!0,t.index+=2;let i=t.readBits(1),n=t.readBits(1)<<1|i;return n===3&&t.index++,t.readBits(1)===1||t.readBits(1)!==0||(t.index++,t.index++,t.index+=24,n>=2&&t.index++,t.readBits(3)!==7?(t.index++,(n===1||n===3)&&(t.index+=3)):(n===1||n===3)&&t.index++,e.width=t.readBits(16)+1,e.height=t.readBits(16)+1),e}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var ot=class{constructor(r){this._onStream=r}drawFrame(r){return c(this,null,function*(){throw new Error("Method `drawFrame` is not supported by this implementation")})}drawImage(r){throw new Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Pt=class extends ot{constructor(e){super(e);this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;d.debug("CanvasRenderer started"),this._useImageBitmap="ImageBitmap"in window}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}drawFrame(e){return c(this,null,function*(){let t="createImageBitmap"in e?yield e.createImageBitmap():yield createImageBitmap(e);this.drawImage(t),t.close()})}drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}destroy(){this._removeStream(),d.debug("CanvasRenderer destroyed")}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(y.browserName()==="Safari"&&Number(y.browserVersion())===15)&&!(y.browserName()==="Firefox"&&Number(y.browserVersion())<60)}};var ct=class extends ot{constructor(e){super(e);d.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:"video"}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}drawFrame(e){return c(this,null,function*(){yield this._writer.write(e)})}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),d.debug("TrackGeneratorRenderer destroyed")}static isBrowserSupported(){return"VideoFrame"in window&&"MediaStreamTrackGenerator"in window&&Ve.isBrowserSupported()}};var bt=class extends et{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];d.debug(`StreamBuilder started for participant [${e}]`),ct.isBrowserSupported()?this._renderer=new ct(t):this._renderer=new Pt(t),Ve.isBrowserSupported()?this._decoder=new Ve:this._decoder=new st;let i=a=>c(this,null,function*(){"VideoFrame"in window&&a instanceof VideoFrame?yield this._renderer.drawFrame(a):this._renderer.drawImage(a)});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(),d.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return Pt.isBrowserSupported()||ct.isBrowserSupported()}};function da(s,r,e,t,i,a,n){let o=0;r&&(o|=1),e&&(o|=2),t&&(o|=4),n||(o|=8);let p=new ArrayBuffer(11),u=new DataView(p);if(u.setUint8(0,1),u.setUint16(1,i),u.setUint32(3,s),u.setUint8(7,a?1:0),u.setUint16(8,0),u.setUint8(10,o),!n)return p;let _=new Uint8Array(p.byteLength+n.byteLength);return _.set(new Uint8Array(p),0),_.set(new Uint8Array(n),p.byteLength),_.buffer}function la(s){let r=new DataView(s),e=r.getUint8(0),t=r.getUint16(1),i=r.getUint32(3),a=r.getUint8(7)===1,n=r.getUint16(8),o=r.getUint8(10),p=!!(o&1),u=!!(o&2),_=!!(o&4),v=!!(o&8);if(e!==1)throw new Error(`Unexpected protocol version. Got ${e}, expected 1`);return{timestamp:i,start:p,end:u,keyframe:_,sequence:t,isVP9:a,ssrc:n,eos:v,data:s.slice(11)}}function pa(s){if(!s||!s.byteLength||s.byteLength!==4)return!1;let r=new DataView(s);return!(r.getUint8(0)!==1||r.getUint8(1)!==1||r.getUint16(2)!==0)}function ua(s){if(!s||!s.byteLength||s.byteLength!==10)return null;let r=new DataView(s);if(r.getUint8(0)!==1||r.getUint8(1)!==2||r.getUint16(2)!==0)return null;let a=r.getUint16(4),n=r.getUint32(6);return{seq:a,ts2:n}}import*as C from"simple-ebml-builder";var on=Cr(2,15)-1,ar=1,cn=5,dn=5;var Ft=class{constructor(r){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=r;let e=()=>{this._mediaSource.removeEventListener("sourceopen",e),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",e,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let t=this._sourceBuffer.buffered.start(0);t<this._clearBufferTill&&(this._sourceBuffer.remove(t,this._clearBufferTill),d.debug(`[WebmBuilder] SourceBuffer cleanup from ${t} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let r=this._queue;this._queue=[];let e=Ft._buildQueue(r);this._sourceBuffer.appendBuffer(e)}static _buildQueue(r){if(r.length){if(r.length===1)return C.build(r[0])}else return new Uint8Array;let e=r.reduce((a,n)=>a+n.countSize(),0),t=new Uint8Array(e),i=0;for(let a of r){let n=C.build(a);t.set(n,i),i+=n.byteLength}return t}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(r){var e;return this._codec=r,(e=this._sourceBuffer)==null?void 0:e.changeType(r)}append(r,e=!1){this._queue.push(r),e&&this._handleQueue()}cleanup(){var a,n,o;((a=this._mediaSource)==null?void 0:a.readyState)==="open"&&((n=this._sourceBuffer)==null||n.abort());let r=(o=this._sourceBuffer)==null?void 0:o.buffered,e=r==null?void 0:r.length;if(!e)return;let t=r.start(0),i=Math.max(0,r.end(e-1)-cn);i-t>dn&&(this._clearBufferTill=i)}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 r;return(r=this._sourceBuffer)==null?void 0:r.buffered}},ye=class extends et{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;d.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 a=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))],o=C.element(C.ID.Tracks,C.element(C.ID.TrackEntry,[C.element(C.ID.TrackNumber,C.number(ar)),C.element(C.ID.TrackUID,C.number(ar)),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,[a,o])}static _genClusterHeader(e){return C.unknownSizeElement(C.ID.Cluster,[C.element(C.ID.Timecode,C.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new Ft(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){d.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=()=>d.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,d.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(),d.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let o=ye._genWebmHeader();this._mediaBuffer.append(o);let p=ye._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(p)}let a=Math.round(i-this._clusterStartTime);if(a>on&&(this._clusterStartTime=i,a=0),a===0){d.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let o=ye._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(o)}let n=C.element(C.ID.SimpleBlock,[C.vintEncodedNumber(ar),C.bytes(ye._intToU16BE(a)),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),d.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 dt=class{constructor(r,e,t,i){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};d.debug("ScreenCaptureReceiver started"),this._datachannel=r,this._participantIdRegistry=e,this._onStream=t,this._onEos=i,this._datachannel.onmessage=a=>this._onDataChannelMessage(a.data)}_onDataChannelMessage(r){var a,n;let e=la(r),t=(n=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(e.ssrc))==null?void 0:n.participantId;if(!t){d.warn(`Participant id for ssrc ${e.ssrc} not found in registry`);return}if(e.eos){this.close(t),this._onEos(t);return}let i=this._streamBuilders[t];if(!i){let o=p=>this._onStream(t,p);l.screenShareWebmBuilder&&ye.isBrowserSupported()?i=new ye(t,o):i=new bt(t,o),this._streamBuilders[t]=i}i.appendChunk(e)}close(r){let e=this._streamBuilders[r];e&&(e.destroy(),delete this._streamBuilders[r])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(r=>r.destroy()),this._streamBuilders={},this._participantIdRegistry=null,d.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(Ve.isBrowserSupported()||st.isBrowserSupported())&&(bt.isBrowserSupported()||ye.isBrowserSupported())}};import ma from"@vkontakte/libvpx";var ln=1e3,Mt=class extends we{constructor(e,t,i,a){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=a,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return c(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let a=this._video;a.srcObject=new MediaStream([e]),a.onloadeddata=p=>t(),a.onerror=()=>i(new Error("Video element error"));let n=a.play(),o=()=>i(new Error("Autoplay is disabled"));n?n.catch(o):o()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");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 c(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var a;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(),(a=this._canvasCtx)==null?void 0:a.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return c(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;d.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`"use strict";var exports=(()=>{var b=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var V=(a,r)=>{for(var s in r)b(a,s,{get:r[s],enumerable:!0})},h=(a,r,s,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of x(r))!y.call(a,e)&&e!==s&&b(a,e,{get:()=>r[e],enumerable:!(i=R(r,e))||i.enumerable});return a};var M=a=>h(b({},"__esModule",{value:!0}),a);var F={};V(F,{default:()=>A});var A=(a,r,s,i)=>{let e;function m(t,o){return a({locateFile:r}).then(n=>{if(e=new n.VpxEncoder,e.debug(o),!e.init(t?n.VpxType.VP9:n.VpxType.VP8))throw self.postMessage({type:"log_error",message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");if(s){let d=Math.round(i/1e3);e.setTargetBitrate(d)}else e.setMaxQuantizer(10),e.setTargetBitrate(1024)})}function E(t,o,n,p){let d=e.allocateImage(t,o);if(!d){self.postMessage({type:"frame",error:"No buffer data"});return}d.set(new Uint8Array(n));let f=Math.round(performance.now()),u=150;if(!e.encode(f,u,p)){self.postMessage({type:"frame",error:"Encode failed"});return}let c=e.readFrame();if(!c){self.postMessage({type:"frame",error:"No encoded data"});return}e.readFrame()&&(self.postMessage({type:"debug",message:"LibVPxEncoder dropped frame"}),self.postMessage({type:"log_error",message:"LibVPxEncoder-drop"}));let l=new Uint8Array(c.byteLength);l.set(c),self.postMessage({type:"frame",frameType:p?"key":"delta",timestamp:f,duration:u,width:t,height:o,data:l.buffer},[l.buffer])}function g(t,o){let n=Math.round(t/1e3);e.setTargetBitrate(n)}self.onmessage=t=>{switch(t.data.type){case"init":m(t.data.isVP9,t.data.debug).then(()=>self.postMessage({type:"ready"})).catch(o=>self.postMessage({type:"error",error:String(o)}));break;case"frame":E(t.data.width,t.data.height,t.data.imageData,t.data.keyFrame);break;case"set_bitrate":g(t.data.bitrate,t.data.useCbr);break}}};return M(F);})();
|
|
10
|
+
`,i=>{var a;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(a=i.data)==null?void 0:a.byteLength,width:i.width,height:i.height})},[ma,ma.getUrl,this._useCongestionControl,this._maxBitrate],{isVP9:this.isVP9(),debug:d.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker("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)},ln),this._getFrameBitmap().then(t=>{var a;window.clearTimeout(this._frameReadTimeout),(a=this._lastFrame)==null||a.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("set_bitrate",{bitrate:e,useCbr:t})}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),d.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var lt=class extends we{constructor(e,t,i,a,n,o){super();this._sourceTrack=e,this._onFrame=t,this._useCongestionControl=i,this._maxBitrate=a,this._useCbr=n,this._frameRate=o,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return c(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;d.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`"use strict";var exports=(()=>{var b=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var _=(a,t)=>{for(var n in t)b(a,n,{get:t[n],enumerable:!0})},x=(a,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of T(t))!B.call(a,r)&&r!==n&&b(a,r,{get:()=>t[r],enumerable:!(i=C(t,r))||i.enumerable});return a};var I=a=>x(b({},"__esModule",{value:!0}),a);var O={};_(O,{default:()=>M});var M=()=>{let t,n,i,r,R,E,l=null,p=0,s=!1,d=0,g,V,c=!1;function h(e){t=e.readable,n=t.getReader(),i=e.width,r=e.height,R=e.isVP9,E=e.framerate,g=e.useCongestionControl,V=e.maxBitrate,g&&(d=V,c=e.useCbr),u(),self.postMessage({type:"ready"})}function y(e){p=self.setTimeout(()=>{l&&A(l,e)},1e3),!s&&(s=!0,n.read().finally(()=>{s=!1,self.clearTimeout(p)}).then(({done:o,value:m})=>{if(l==null||l.close(),l=null,!(o||!m)){if(!f){n.releaseLock(),t.cancel();return}l=m,A(m,e)}}))}function A(e,o){(e.codedWidth!==i||e.codedHeight!==r)&&(i=e.codedWidth,r=e.codedHeight,u()),f.encode(e,{keyFrame:o})}function u(){let e={framerate:E,codec:R?"vp09.00.50.08":"vp8",width:i,height:r,latencyMode:"realtime",bitrateMode:c?"constant":"variable"};d>0&&(e.bitrate=d),f.configure(e)}function F(e,o=!1){d=e,c=o,u()}let f=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:"frame",frameType:e.type,timestamp:e.timestamp,duration:e.duration,width:i,height:r,data:o},[o])},error:e=>{self.postMessage({type:"frame",error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case"init":h(e.data);break;case"frame":y(e.data.keyFrame);break;case"set_bitrate":F(e.data.bitrate,e.data.useCbr);break}}};return I(O);})();
|
|
11
|
+
`,a=>{var n;a.error?this._onFrame(null,a.error):this._onFrame({type:a.frameType,timestamp:a.timestamp,duration:a.duration,data:a.data,byteLength:(n=a.data)==null?void 0:n.byteLength,width:a.width,height:a.height})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:this._frameRate,useCongestionControl:this._useCongestionControl,maxBitrate:this._maxBitrate,useCbr:this._useCbr},[i])})}requestFrame(e=!1){this._sendToWorker("frame",{keyFrame:e})}setBitrate(e,t){this._sendToWorker("set_bitrate",{bitrate:e,useCbr:t})}isVP9(){return!0}destroy(){this._removeWorker(),d.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var pn=1.2,ha=.8,un=2e3,mn=8e3,nr=8e3,hn=16e3,_n=4,gn=2e3,fi=(t=>(t[t.NONE=0]="NONE",t[t.UP=1]="UP",t[t.DOWN=2]="DOWN",t))(fi||{}),jt=class{constructor(r,e,t,i,a){this._upPenalty=0;this._delayAvgShort=-1;this._delayAvgLong=-1;this._minDelay=Number.MAX_VALUE;this._maxDelay=0;this._largeDelayDuration=0;this._onCongestion=r,this._ccEnabled=i,this._minBitrate=e,this._maxBitrate=t,this._fastSharing=a,this._targetBitrate=this._maxBitrate,this._probing=!1;let n=Date.now();this._lastDown=0,this._lastUp=n,this._lastProbing=n,this._lastCheckDelay=0}checkDelay(r,e,t){let i=Date.now();if(this._calcDelay(e,i),this._delayAvgShort<=0||this._delayAvgLong<=0||!this._ccEnabled)return;let a=0,n=this._delayAvgShort-this._delayAvgLong,o=Math.round(Math.abs(n)*100/this._delayAvgLong),p=this._fastSharing?200:700,u=n>40&&o>30&&this._delayAvgShort>p,_=this._delayAvgShort>2e3;u||_?a=2:Math.abs(n)<40&&o<10&&this._delayAvgShort<2e3&&(a=1);let v=Math.round(this._targetBitrate/1e3),b=t;r%10===0&&d.debug(`#${r}: cc: delay=${e} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${n} percent=${o} -> ${fi[a]} tr=${v} br=${t}`);let k=i-this._lastDown;if(a===2&&k>un){this._probing&&(this._upPenalty=Math.min(++this._upPenalty,_n),this._probing=!1);let G=ha*b*1e3;if(G>=this._targetBitrate&&(G=this._targetBitrate*ha),G=Math.max(G,this._minBitrate),G<this._targetBitrate){let X=Math.round(G/1e3),_e=Math.round(this._upPenalty*nr/1e3);d.log(`#${r}: cc: delay=${e} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${n} percent=${o} -> ${fi[a]}`),d.log(`#${r}: cc: DOWN delay=${e} bitrate=${b} target=${v} -> newBitrate=${X} penalty=${_e}s`),this._setBitrate(G,!0),this._targetBitrate=G}this._lastDown=i}let D=i-this._lastUp,$=mn+this._upPenalty*nr;if(a===1&&D>$&&k>$){let G=Math.min(this._targetBitrate*pn,this._maxBitrate);if(G>this._targetBitrate){let X=Math.round(G/1e3),_e=Math.round(this._targetBitrate/1e3),Ee=Math.round(this._upPenalty*nr/1e3);d.log(`#${r}: cc: delay=${e} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${n} percent=${o} -> ${fi[a]}`),d.log(`#${r}: cc: UP bitrate=${b} target=${_e} -> newBitrate=${X} penalty=${Ee}s`),this._setBitrate(G,!1),this._targetBitrate=G,this._probing=!0,this._lastProbing=i,this._lastUp=i}}let j=i-this._lastProbing;this._probing&&j>hn&&(this._probing=!1);let he=i-this._lastDown;this._upPenalty>0&&he>3*$&&(d.log(`#${r}: cc: UP reset penalty: oldPenalty=${this._upPenalty}`),this._upPenalty=0)}_setBitrate(r,e){this._fastSharing&&(e=!0),this._onCongestion(r,e)}_calcDelay(r,e){if(!(r<=0)){if(this._delayAvgShort===-1&&(this._delayAvgShort=r,this._delayAvgLong=r),this._delayAvgShort=Math.round((this._delayAvgShort*3+r)/4),this._delayAvgLong=Math.round((this._delayAvgLong*23+r)/24),r>0&&r<this._minDelay?this._minDelay=r:r>this._maxDelay&&(this._maxDelay=r),this._lastCheckDelay===0&&(this._lastCheckDelay=e),r>gn){let t=e-this._lastCheckDelay;this._largeDelayDuration+=t}this._lastCheckDelay=e}}reconfigure(r,e){this._minBitrate=r,this._maxBitrate=e}getStat(){if(this._minDelay===Number.MAX_VALUE||this._maxDelay===0||this._delayAvgLong<=0)return null;let r={minDelay:this._minDelay,maxDelay:this._maxDelay,avgDelay:this._delayAvgLong,largeDelayDuration:this._largeDelayDuration};return this._minDelay=Number.MAX_VALUE,this._maxDelay=0,this._largeDelayDuration=0,r}};var Ht=class{constructor(r){this._size=0;this._head=0;this._tail=0;this._maxSize=r,this._buffer=new Array(r)}add(r,e,t,i,a){this._tail===this._head&&this._size>0&&(this._head=++this._head%this._maxSize);let n=this._tail;return this._buffer[this._tail]={seq:r,ts:e,size:t,sent:Date.now(),start:i,end:a,ts2:-1,recv:-1},this._tail=++this._tail%this._maxSize,this._size++,n}update(r,e){let t=this.get(r);return t===null?null:(t.ts2=e,t.recv=Date.now(),t)}get(r){let e=this._head;for(let t=0;t<this._maxSize;t++){if(r===this._buffer[e].seq)return this._buffer[e];if(e=++e%this._maxSize,e===this._tail)break}return null}getServerBitrateK(r){let e=0,t=0,i=-1,a=-1,n=this._tail;for(let o=0;o<this._maxSize;o++){n>0?--n:n=this._maxSize-1;let p=this._buffer[n];if(p===null||(a===-1&&(a=p.ts2,t=0),a>=0&&(t+=p.size),i=p.ts2,a-i>=r)||n===this._head)break}if(i>=0&&a>=0){let o=a-i;e=Math.round(o>0?t*8/o:0)}return e}getCurrentDelay(){let r=this._tail;for(let e=0;e<this._maxSize;e++){r>0?--r:r=this._maxSize-1;let t=this._buffer[r];if(t===null)break;if(t.recv>=0&&t.sent>=0)return t.recv-t.sent;if(r===this._head)break}return 0}getMaxBandwidth(){let r=0,e=0,t=-1,i=-1,a=this._tail;for(let n=0;n<this._maxSize;n++){if(a>0?--a:a=this._maxSize-1,i===-1&&this._buffer[a].end&&!this._buffer[a].start&&(i=this._buffer[a].ts2,e=0),t===-1&&i>=0&&this._buffer[a].start&&!this._buffer[a].end&&(t=this._buffer[a].ts2),t>=0&&i>=0){let o=i-t;r=o>0?e*8/o:0;break}if(i>=0&&(e+=this._buffer[a].size),a===this._head)break}return Math.round(r)}};var Sn=65536,vn=50,En=400,In=1e6,Tn=3e4,Si=0,pt=class{constructor(r,e,t,i){this._destroyed=!1;this._needKeyframe=!0;this._frameNum=0;this._feedback=new Ht(1024);this._lastSharingStat=Date.now();this._congestionControlEnabled=!1;d.debug("ScreenCaptureSender started"),this.DATA_SIZE=l.consumerScreenDataChannelPacketSize-11,this._datachannel=e,this._signaling=t,this._fastSharing=i,this._congestionControlEnabled=l.screenShareCongestionControl||this._fastSharing,this._width=r.getSettings().width,this._height=r.getSettings().height;let{minBitrate:a,maxBitrate:n}=this._calcMinMaxBitrate(this._width,this._height),o=this._onCongestionCallback.bind(this);d.log(`ScreenCaptureSender: CongestionControl: enabled=${this._congestionControlEnabled} minBitrate=${Math.round(a/1e3)}k maxBitrate=${Math.round(n/1e3)}k`),this._congestionControl=new jt(o,a,n,this._congestionControlEnabled,this._fastSharing);let p=(u,_)=>{if(!this._destroyed){if(!u){d.warn("requestFrame failed, keyFrame: "+this._needKeyframe,_),this._needKeyframe=!0,this._requestFrame();return}(u.width!==this._width||u.height!==this._height)&&(this._width=u.width,this._height=u.height,this._onResize(this._width,this._height)),this._send(u).catch(v=>{d.warn("sendFrame failed",v),this._needKeyframe=!0}).finally(()=>{this._frameNum++,u.type==="key"&&d.debug(`#${this._frameNum}: sharing: send keyframe size=${Math.round(u.byteLength/1e3)}k`);let v=this._feedback.getCurrentDelay(),b=this._feedback.getServerBitrateK(2e3);v>0&&this._congestionControl.checkDelay(this._frameNum,v,b),this._requestFrame()}),this._sendSharingStat()}};if(lt.isBrowserSupported()){let u=this._fastSharing,_=l.getScreenFrameRate(this._fastSharing);this._encoder=new lt(r,p,this._congestionControlEnabled,n,u,_)}else this._encoder=new Mt(r,p,this._congestionControlEnabled,n);this._datachannel.onmessage=u=>{pa(u.data)&&(d.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0);let _=ua(u.data);_!==null&&this._checkCcFeedback(_)},this._encoder.init().then(()=>this._requestFrame()).catch(u=>d.warn("ScreenCaptureSender init failed",u))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(r,e,t,i,a){let n=da(r,e,t,i,Si,this._encoder.isVP9(),a);return Si=(Si+1)%Sn,n}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(r){return c(this,null,function*(){return new Promise((e,t)=>{this._sendChunk(r,0,e,t)})})}_sendChunk(r,e,t,i){if(!this._datachannel||this._datachannel.readyState!=="open"){i();return}let a=r.data.slice(e,e+this.DATA_SIZE),n=r.data.byteLength<=e+a.byteLength;this._feedback.add(Si,r.timestamp,a.byteLength,!e,n);let o=this._wrapHeader(r.timestamp,!e,n,r.type==="key",a);this._datachannel.onbufferedamountlow=n?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&t()}:null;try{this._datachannel.send(o)}catch(p){d.warn("Error send data to DataChannel",p),i();return}n||I.setImmediate(()=>this._sendChunk(r,e+this.DATA_SIZE,t,i))}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),d.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return lt.isBrowserSupported()||Mt.isBrowserSupported()}_onCongestionCallback(r,e){this._encoder.setBitrate(r,e)}_onResize(r,e){let{minBitrate:t,maxBitrate:i}=this._calcMinMaxBitrate(r,e),a=Math.round(t/1e3),n=Math.round(i/1e3);d.log(`cc: resize to ${r}x${e}, minBitrate=${a} maxBitrate=${n}`),this._congestionControl.reconfigure(t,i)}_calcMinMaxBitrate(r,e){(r===void 0||r<640)&&(r=640),(e===void 0||e<360)&&(e=360);let t=r*e/256,i=Math.min(In,Math.round(t*vn)),a=Math.round(t*En);return{minBitrate:i,maxBitrate:a}}_checkCcFeedback(r){this._feedback.update(r.seq,r.ts2)===null&&d.debug(`cc: update failed, seq=${r.seq}`)}_sendSharingStat(){let r=Date.now();if(r-this._lastSharingStat>Tn){let t=this._congestionControl.getStat();t!==null&&(d.debug(`cc: send stats: ${JSON.stringify(t)}`),this._signaling.reportSharingStat(t)),this._lastSharingStat=r}}};var ae=class{static get sessionKey(){return ae._sessionKey}static set sessionKey(r){ae._sessionKey=r}static get sessionSecretKey(){return ae._sessionSecretKey}static set sessionSecretKey(r){ae._sessionSecretKey=r}static get accessToken(){return ae._accessToken}static set accessToken(r){ae._accessToken=r}static isEmpty(){return!ae._sessionKey||!ae._sessionSecretKey}};var f=class{static set(r){r.hasOwnProperty("voiceParams")&&(Object.assign(f._params.voiceParams,r.voiceParams),delete r.voiceParams),r.hasOwnProperty("specListenerParams")&&(Object.assign(f._params.specListenerParams,r.specListenerParams),delete r.specListenerParams),r.hasOwnProperty("apiAuth")&&(ae.accessToken=r.apiAuth.accessToken,ae.sessionKey=r.apiAuth.sessionKey,ae.sessionSecretKey=r.apiAuth.sessionSecretKey),r.hasOwnProperty("api")&&(Object.assign(f._params.api,r.api),delete r.api),Object.assign(f._params,I.objectFilterOutValues(r,void 0))}static get(r){return f._params[r]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.6.3-dev.dea4ecd.0"}static get debug(){}static get protocolVersion(){return f._params.joinFromMultipleDevices?6:5}static get platform(){return f._params.platform}static set platform(r){f._params.platform=r}static get clientType(){return f._params.clientType}static set clientType(r){f._params.clientType=r}static get externalUserType(){return f._params.externalUserType}static set externalUserType(r){f._params.externalUserType=r}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(r){f._params.authToken=r}static get anonymToken(){return f._params.anonymToken}static set anonymToken(r){f._params.anonymToken=r}static get domain(){return f._params.domain}static get externalDomain(){return f._params.externalDomain}static get iceServers(){return f._params.iceServers}static set iceServers(r){f._params.iceServers=r}static get wssBase(){return f._params.wssBase}static set wssBase(r){f._params.wssBase=r}static get wssToken(){return f._params.wssToken}static set wssToken(r){f._params.wssToken=r}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(r){f._params.forceRelayPolicy=r}static get videoMinWidth(){return f._params.videoMinWidth}static get videoMaxWidth(){return f._params.videoMaxWidth}static set videoMaxWidth(r){f._params.videoMaxWidth=r}static get videoMinHeight(){return f._params.videoMinHeight}static get videoMaxHeight(){return f._params.videoMaxHeight}static set videoMaxHeight(r){f._params.videoMaxHeight=r}static get videoAspectRatio(){return f._params.videoAspectRatio}static get videoFrameRate(){return f._params.videoFrameRate}static get videoFacingMode(){return f._params.videoFacingMode||(y.isMobile()?"user":null)}static set videoFacingMode(r){f._params.videoFacingMode=r}static get displaySurface(){return f._params.displaySurface}static get videoEffects(){return f._params.videoEffects}static set videoEffects(r){f._params.videoEffects=r}static get videoEffectMaxWidth(){return f._params.videoEffectMaxWidth}static set videoEffectMaxWidth(r){f._params.videoEffectMaxWidth=r}static get videoEffectMaxHeight(){return f._params.videoEffectMaxHeight}static set videoEffectMaxHeight(r){f._params.videoEffectMaxHeight=r}static get useVmoji(){var r;return((r=f._params.vmoji)==null?void 0:r.isBrowserSupported())||!1}static get vmoji(){return f._params.vmoji}static set vmoji(r){f._params.vmoji=r}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(r){f._params.statisticsInterval=r}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&&pt.isBrowserSupported()}static get producerScreenDataChannel(){return f._params.producerScreenDataChannel&&f.producerNotificationDataChannel&&dt.isBrowserSupported()}static get asrDataChannel(){return f._params.asrDataChannel&&f.producerNotificationDataChannel}static get consumerScreenDataChannelPacketSize(){return f._params.consumerScreenDataChannelPacketSize}static get screenShareWebmBuilder(){return f._params.screenShareWebmBuilder}static get noiseSuppression(){return f._params.noiseSuppression}static set noiseSuppression(r){f._params.noiseSuppression=r}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 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 useRooms(){return f._params.useRooms}static get participantListChunkInitIndex(){var r;return(r=f._params.participantListChunkInitIndex)!=null?r:0}static get participantListChunkInitCount(){var r;return(r=f._params.participantListChunkInitCount)!=null?r:null}static get serverAudioRed(){return f._params.serverAudioRed&&y.canPreferRed()}static get p2pAudioRed(){return f._params.p2pAudioRed&&y.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}static get audioShare(){return y.isAudioShareSupported()&&f._params.audioShare}static get screenShareCongestionControl(){return f._params.screenShareCongestionControl}static get api(){return f._params.api}static get fastScreenShareWidth(){return f._params.fastScreenShareWidth}static get fastScreenShareHeight(){return f._params.fastScreenShareHeight}static getScreenFrameRate(r){return r?f._params.fastScreenShareFrameRate:f._params.screenFrameRate}},l=f;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,videoFacingMode:null,displaySurface:"monitor",videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,vmoji:null,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},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,asrDataChannel:!1,consumerScreenDataChannelPacketSize:64*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:!0,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1,audioShare:!1,screenShareCongestionControl:!1,api:{userIdsByOkBatchedTimeout:1e3},fastScreenShareFrameRate:24,fastScreenShareWidth:1280,fastScreenShareHeight:720};var or=(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))(or||{});function F(s,...r){let e=l.get(s);e&&setTimeout(e,0,...r)}function ce(s,r,...e){if(l.filterObservers){if(Array.isArray(r)){if(r=r.filter(t=>!t.observer),!r.length)return}else if(r.observer)return}F(s,r,...e)}function ve(s){return Object.assign({},s)}function ut(s){return s.slice()}var sr;(ws=>{function s(h,P){F("onLocalStream",h,ve(P))}ws.onLocalStream=s;function r(h,P){F("onScreenStream",h,ve(P))}ws.onScreenStream=r;function e(h,P){F("onVmojiStream",h,ve(P))}ws.onVmojiStream=e;function t(h,P){F("onLocalStreamUpdate",ve(h),P)}ws.onLocalStreamUpdate=t;function i(h){F("onLocalStatus",h)}ws.onLocalStatus=i;function a(h,P){ce("onRemoteStream",h,P)}ws.onRemoteStream=a;function n(h,P){ce("onRemoteLive",h,P)}ws.onRemoteLive=n;function o(h,P){ce("onLocalLive",h,P)}ws.onLocalLive=o;function p(h,P){ce("onRemoteLiveUpdate",h,P)}ws.onRemoteLiveUpdate=p;function u(h,P){ce("onLocalLiveUpdate",h,P)}ws.onLocalLiveUpdate=u;function _(h,P){ce("onRemoteScreenStream",h,P)}ws.onRemoteScreenStream=_;function v(h,P){ce("onRemoteVmojiStream",h,P)}ws.onRemoteVmojiStream=v;function b(h,P,Z,Ge,Nt){ce("onConversation",h,ve(P),ve(Z),Ge,Nt)}ws.onConversation=b;function k(h){h&&F("onConversationParticipantListChunk",h)}ws.onConversationParticipantListChunk=k;function D(h,P,Z){ce("onRemoteMediaSettings",h,ve(P),Z)}ws.onRemoteMediaSettings=D;function $(h,P){ce("onLocalMediaSettings",h,ve(P))}ws.onLocalMediaSettings=$;function j(h,P){ce("onRemoteSharedMovieInfo",h,ve(P))}ws.onRemoteSharedMovieInfo=j;function he(h,P){ce("onRemoteSharedMovieStoppedInfo",h,ve(P))}ws.onRemoteSharedMovieStoppedInfo=he;function G(h,P){ce("onLocalSharedMovieInfo",h,ve(P))}ws.onLocalSharedMovieInfo=G;function X(h,P){ce("onLocalSharedMovieStoppedInfo",h,ve(P))}ws.onLocalSharedMovieStoppedInfo=X;function _e(h,P){ce("onParticipantAdded",h,P)}ws.onParticipantAdded=_e;function Ee(h,P){ce("onParticipantJoined",h,P)}ws.onParticipantJoined=Ee;function at(h,P,Z){ce("onRemoteParticipantState",h,ve(P),Z)}ws.onRemoteParticipantState=at;function ii(h,P,Z=null){ce("onRemoteStatus",h,P,Z)}ws.onRemoteStatus=ii;function Y(h,P,Z=null){ce("onParticipantStatus",h,P,Z)}ws.onParticipantStatus=Y;function Sr(){F("onPermissionsRequested")}ws.onPermissionsRequested=Sr;function vr(h,P){F("onPermissionsError",h,P)}ws.onPermissionsError=vr;function ki(h,P){ce("onRemoteRemoved",h,P)}ws.onRemoteRemoved=ki;function q(h,P,Z){F("onCallState",h,P,ve(Z))}ws.onCallState=q;function Er(h,P){F("onDeviceSwitched",h,P)}ws.onDeviceSwitched=Er;function Oi(h,P,Z,Ge=!1,Nt=!1,xi=null,Li=null,Na,Ir,Ua=null){let Ba=Ir?ut(Ir):void 0;F("onMuteStates",ve(h),ut(P),ut(Z),Ge,Nt,xi,Li,Na,Ba,Ua)}ws.onMuteStates=Oi;function wi(h,P){ce("onRolesChanged",h,ut(P))}ws.onRolesChanged=wi;function E(h){F("onLocalRolesChanged",ut(h))}ws.onLocalRolesChanged=E;function T(h,P,Z){ce("onPinnedParticipant",h,P,Z)}ws.onPinnedParticipant=T;function m(h){F("onLocalPin",h)}ws.onLocalPin=m;function A(h){F("onOptionsChanged",ut(h))}ws.onOptionsChanged=A;function M(){F("onCallAccepted")}ws.onCallAccepted=M;function U(){F("onRateNeeded")}ws.onRateNeeded=U;function ee(h){ce("onSpeakerChanged",h)}ws.onSpeakerChanged=ee;function se(h){F("onVolumesDetected",ut(h))}ws.onVolumesDetected=se;function Te(h,P){F("onLocalVolume",h,P)}ws.onLocalVolume=Te;function Le(h,P){F("onJoinStatus",h,P)}ws.onJoinStatus=Le;function je(h,P){F("onHangup",h,P)}ws.onHangup=je;function Me(h){F("onMultipartyChatCreated",ve(h))}ws.onMultipartyChatCreated=Me;function Ae(){F("onDeviceChange")}ws.onDeviceChange=Ae;function De(h){F("onFingerprintChange",h)}ws.onFingerprintChange=De;function Ne(){F("onTokenExpired")}ws.onTokenExpired=Ne;function L(h,P,Z=!1){F("onChatMessage",h,P,Z)}ws.onChatMessage=L;function B(h,P,Z=!1){F("onCustomData",h,P,Z)}ws.onCustomData=B;function ft(h,P,Z,Ge,Nt,xi,Li=null){F("onRecordStarted",h,P,Z,Ge,Nt,xi,Li)}ws.onRecordStarted=ft;function K(h=null){F("onRecordStopped",h)}ws.onRecordStopped=K;function ue(h){F("onLocalNetworkStatusChanged",h)}ws.onLocalNetworkStatusChanged=ue;function fe(h){F("onNetworkStatusChanged",h)}ws.onNetworkStatusChanged=fe;function te(h,...P){F("onDebugMessage",h,...P)}ws.onDebugMessage=te;function Q(h,P){let Z=Object.assign({},h,{memory:P});F("onStatistics",Z)}ws.onStatistics=Q;function oe(){F("onAutoplayError")}ws.onAutoplayError=oe;function He(h,P,Z){F("onChatRoomUpdated",h,P,Z)}ws.onChatRoomUpdated=He;function Is(h){F("onRemoteMixedAudioStream",h)}ws.onRemoteMixedAudioStream=Is;function Ts(h){F("onJoinLinkChanged",h)}ws.onJoinLinkChanged=Ts;function Rs(h){F("onRoomsUpdated",h)}ws.onRoomsUpdated=Rs;function Cs(h,P,Z,Ge){F("onRoomUpdated",h,P,Z,Ge)}ws.onRoomUpdated=Cs;function ys(h){F("onRoomParticipantsUpdated",h)}ws.onRoomParticipantsUpdated=ys;function Ps(h){F("onRoomSwitched",h)}ws.onRoomSwitched=Ps;function bs(h){F("onRoomStart",h)}ws.onRoomStart=bs;function Ms(h,P=null){F("onFeedback",h,P)}ws.onFeedback=Ms;function As(h){F("onFeaturesPerRoleChanged",h)}ws.onFeaturesPerRoleChanged=As;function Ds(h,P){F("onAsrStarted",h,P)}ws.onAsrStarted=Ds;function ks(){F("onAsrStopped")}ws.onAsrStopped=ks;function Os(h,P,Z,Ge){F("onAsrTranscription",h,P,Z,Ge)}ws.onAsrTranscription=Os})(sr||(sr={}));var g=sr;var _a=(i=>(i.DEBUG="DEBUG",i.LOG="LOG",i.WARN="WARN",i.ERROR="ERROR",i))(_a||{}),cr;(X=>{let s="📞",r=(_e,...Ee)=>{g.onDebugMessage(_e,...Ee)},e=!1,t=(_e,Ee)=>(...at)=>{_e(...at),Xr(Ee,at)},i=console.debug.bind(console,s),a=console.log.bind(console,s),n=console.warn.bind(console,s),o=console.error.bind(console,s),p=r.bind(null,"DEBUG"),u=r.bind(null,"LOG"),_=r.bind(null,"WARN"),v=r.bind(null,"ERROR");X.debug=p,X.log=u,X.warn=_,X.error=v;function j(){return e}X.enabled=j;function he(_e){e=_e,l.debugLog&&Wi(),_e?(X.debug=l.debugLog?t(i,"DEBUG"):i,X.log=l.debugLog?t(a,"LOG"):a,X.warn=l.debugLog?t(n,"WARN"):n,X.error=l.debugLog?t(o,"ERROR"):o):(X.debug=l.debugLog?t(p,"DEBUG"):p,X.log=l.debugLog?t(u,"LOG"):u,X.warn=l.debugLog?t(_,"WARN"):_,X.error=l.debugLog?t(v,"ERROR"):v)}X.toggle=he;function G(_e,...Ee){switch(_e){case"DEBUG":(0,X.debug)(...Ee);break;case"LOG":(0,X.log)(...Ee);break;case"WARN":(0,X.warn)(...Ee);break;case"ERROR":(0,X.error)(...Ee);break}}X.send=G})(cr||(cr={}));var d=cr;var dr=(t=>(t.USER="USER",t.ANONYM="ANONYM",t.GROUP="GROUP",t))(dr||{}),ge;(o=>{function s(p){return p.length?typeof p[0]=="object"?p:p.map(u=>r(u)):[]}o.fromIds=s;function r(p,u="USER"){return{id:p,type:u}}o.fromId=r;function e(p){return{id:p.id,type:p.type==="ANONYM"?"ANONYM":"USER"}}o.fromSignaling=e;function t(p){return`{"id":"${p.id}","type":"${p.type}"}`}o.toString=t;function i(p,u="USER"){return t(r(p,u))}o.fromIdToString=i;function a(p){try{return JSON.parse(p)}catch(u){throw new Error(`Failed to parse ExternalId from string '${p}'`)}}o.fromString=a;function n(p,u){return p.id===u.id&&p.type===u.type}o.compare=n})(ge||(ge={}));var le;(i=>{function s(a,n="USER",o=0){return{id:a,type:n,deviceIdx:o}}i.fromId=s;function r(a){return`{"id":"${a.id}","type":"${a.type}","deviceIdx":"${a.deviceIdx}"}`}i.toString=r;function e(a,n){return Object.assign({deviceIdx:n},ge.fromSignaling(a))}i.fromSignaling=e;function t(a){return a&&typeof a=="object"?a.deviceIdx:0}i.getDeviceIdx=t})(le||(le={}));var Rn="kf";function Gt(s){return s.stopStream}function lr(s){return s.keyFrameRequested}function ga(s){if(Gt(s))return"ss";if(lr(s))return Rn;let r="";return s.priority!==void 0&&(r+="p="+s.priority),s.width!==void 0&&s.height!==void 0&&(r!==""&&(r+=":"),r+="sz="+Math.round(s.width)+"x"+Math.round(s.height)),s.fit!==void 0&&(r!==""&&(r+=":"),r+="fit="+s.fit),r}var Wt=(n=>(n.CAMERA="CAMERA",n.SCREEN="SCREEN",n.STREAM="STREAM",n.MOVIE="MOVIE",n.AUDIOSHARE="AUDIOSHARE",n.ANIMOJI="ANIMOJI",n))(Wt||{}),fa="s",Sa="m";function Fe(s){return s.participantId+(s.mediaType?It+fa+s.mediaType:"")+(s.streamName?It+Sa+s.streamName:"")}function Kt(s){let r=s.split(It),e=r.shift();if(!e)throw new Error("Illegal stream description: "+s);let t=null,i,a=0;for(let o of r)switch(o.charAt(0)){case fa:t=Cn(o.slice(1));break;case Sa:i=o.slice(1);break;case si:a=Number.parseInt(o.slice(1),10);break;default:throw new Error("Unexpected parameter type "+o.charAt(0)+" in stream description "+s)}return{participantId:I.compose(e,a),mediaType:t,streamName:i}}function Cn(s){for(let r of Object.keys(Wt))if(r===s)return Wt[r];return null}function pr(s,r){return s===null||r===null?s===null&&r===null:!(s.maxDimension!==r.maxDimension||s.maxBitrateK!==r.maxBitrateK||s.maxFramerate!==r.maxFramerate||s.degradationPreference!==r.degradationPreference)}function vi(s,r){return!(!pr(s.camera,r.camera)||!pr(s.screenSharing,r.screenSharing))}function ur(s,r){return{camera:Object.assign({},s.camera,r.camera),screenSharing:Object.assign({},s.screenSharing,r.screenSharing)}}function va(s){try{return btoa(JSON.stringify(s))}catch(r){d.warn("WaitingParticipant: failed convert to string",s,r)}return null}function Ea(s){try{return JSON.parse(atob(s))}catch(r){d.warn("WaitingParticipant: failed convert from string",s,r)}return null}var At=(s,r)=>I.objectReduce(s,(e,t,i)=>(t===r&&e.push(i),e),[]);var Dt=class{constructor(r){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=r}_fixAudioDeviceNoPackets(r){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,S.log(R.ERROR,`audio_device_recover_${r.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!r.bandwidth&&(this._fixNoPacketsApplied=!0,S.log(R.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(r){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let e=75,t=Date.now();if(!this._lastPacketsSentTime)r.packetsSent>0&&(this._lastPacketsSentTime=t,this._lastPacketsSent=r.packetsSent);else if(t-this._lastPacketsSentTime>500){let i=(r.packetsSent-this._lastPacketsSent)*1e3/(t-this._lastPacketsSentTime);this._lastPacketsSentTime=t,this._lastPacketsSent=r.packetsSent,this._fixTooManyPacketsApplied?i>e?(d.log("Failed to fix RV"),S.log(R.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):t-this._fixTooManyPacketsTime>6e4&&(d.log("Fixed RV"),S.log(R.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):i>e&&(this._fixTooManyPacketsApplied=!0,d.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=t)}}fix(r){if(!this._mediaSource)return;let e=r.find(t=>t.kind==="audio");e&&(this._fixAudioDeviceNoPackets(e),this._fixAudioDeviceTooManyPackets(e))}};var $t=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(r){this.destroy(),this._output={},this._output.audioTrack=r,this._initAudioElement()}remove(r){!this._output||this._output.audioTrack!==r||this.destroy()}get volume(){return this._volume}set volume(r){this._volume=Math.max(0,Math.min(1,r)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var n;if(l.muteMode||!((n=this._output)!=null&&n.audioTrack))return;let r=y.browserName()!=="Safari"||y.isMobile(),e=document.createElement(r?"audio":"video");e.muted=!1,e.volume=this._volume,e.preload="auto";let t=()=>{d.warn("Error on play audio"),g.onAutoplayError()},i=o=>{e.srcObject=new MediaStream([o]),e.load();let p=e.play();p&&p.catch(t)},a=()=>{var p;d.debug("Recover audio playback");let o=(p=this._output)==null?void 0:p.audioTrack;o?i(o):d.warn("Broken audio track")};e.onpause=a,e.onstalled=a,e.onerror=a,i(this._output.audioTrack),this._output.audioElement=e}_stopAudioElement(){var r,e,t;(r=this._output)!=null&&r.audioElement&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(t=(e=this._output)==null?void 0:e.audioTrack)==null||t.stop()}destroy(){this._output&&(this._stopAudioElement(),this._output=null)}changeOutput(){return c(this,null,function*(){var r,e,t;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((r=this._output)!=null&&r.audioElement))throw new Error("Audio Element is not initialized");let i=y.getSavedOutput();i&&(yield(t=(e=this._output.audioElement).setSinkId)==null?void 0:t.call(e,i.deviceId))}catch(i){throw S.log(R.ERROR,"change_output"),d.error("Output change failed",i),i}})}};var yn=90,Pn=3,qt=class extends ie{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let a=typeof i.userId=="string"&&t[i.userId]||null;i.userId=a==null?void 0:a.externalId}),g.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var a;let e=(a=window==null?void 0:window.performance)==null?void 0:a.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>yn?d.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Pn)&&(d.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var bn=44100,kt=class{constructor(r,e){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=r,this._stream=e;try{let t=y.getAudioContext();this._gainNode=t.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(t.destination),this._analyser=t.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=t.createMediaStreamSource(e),this._mediaStreamSource.connect(this._analyser)}catch(t){}}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 r=bn/this._fftBins.length,e=Math.ceil(l.voiceParams.minFreq/r),t=Math.floor(l.voiceParams.maxFreq/r);return this._fftBins.subarray(e,t)}getLevel(){let r=this._getBins(),t=r.reduce((a,n)=>a+n,0)/r.length/255,i=this._lastSmoothedLevel*l.voiceParams.smoothing+t*(1-l.voiceParams.smoothing);return this._lastSmoothedLevel=i,{real:t,smoothed:i}}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 Jt=class extends ie{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 a=e.getStream();a&&this.init(a)};this.subscribe(e,"SOURCE_CHANGED",a=>{a.kind==="audio"&&a.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks().find(i=>!i.contentHint);t&&(this._track=t.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 Ia=(n=>(n.producerNotification="producerNotification",n.producerCommand="producerCommand",n.consumerScreenShare="consumerScreenShare",n.producerScreenShare="producerScreenShare",n.asr="asr",n.animoji="animoji",n))(Ia||{}),$e=Ia;var Ta="videochat-epi",Mn=5e3,An=3e4,tt=class extends ie{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,"REMOTE_DATA_STATS",this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Ta)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return c(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&l.perfStatReportEnabled&&this._previousTimestamp+Mn<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),l.callStatReportEnabled&&this._previousCallStatReportTimestamp+An<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return c(this,null,function*(){let t=e.inbound.rtps.reduce((i,a)=>(a.kind==="video"&&(i.framesDecoded+=a.framesDecoded||0,i.framesReceived+=a.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(Ta,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((a,n)=>(n.kind==="video"?(n.framesReceived&&(a.jitter_video=a.jitter_video*a.inbound_video_count/(a.inbound_video_count+1)+n.jitter*1e3/(a.inbound_video_count+1),a.interframe_delay_variance=a.interframe_delay_variance*a.inbound_video_count/(a.inbound_video_count+1)+n.interframeDelayVariance*1e6/(a.inbound_video_count+1),a.inbound_video_count++),a.frames_dropped+=n.framesDropped,a.nack_sent+=n.nackCount,a.pli_sent+=n.pliCount,a.fir_sent+=n.firCount):(n.totalSamplesReceived&&(a.jitter_audio=a.jitter_audio*a.inbound_audio_count/(a.inbound_audio_count+1)+n.jitter*1e3/(a.inbound_audio_count+1),a.total_audio_energy=a.total_audio_energy*a.inbound_audio_count/(a.inbound_audio_count+1)+n.totalAudioEnergy/(a.inbound_audio_count+1),a.inbound_audio_count++),a.total_audio_samples_received+=n.totalSamplesReceived,a.inserted_audio_samples_for_deceleration+=n.insertedSamplesForDeceleration,a.removed_audio_samples_for_acceleration+=n.removedSamplesForAcceleration,a.concealed_audio_samples+=n.concealedSamples,a.silent_concealed_audio_samples+=n.silentConcealedSamples,a.audio_concealment_events+=n.concealmentEvents),a),t),e.outbound.rtps.reduce((a,n)=>(n.kind==="video"&&(a.nack_received+=n.nackCount,a.pli_received+=n.pliCount,a.fir_received+=n.firCount),a),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 a=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,n=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,o=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,p=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,u=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,_=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=n/a*1e3,i.removed_audio_samples_for_acceleration=o/a*1e3,i.concealed_audio_samples=p/a*1e3,i.concealed_silent_audio_samples=u/a*1e3,i.concealment_audio_avg_size=p/_,i.total_audio_energy=t.total_audio_energy}S.logCustom("callStat",i),d.log("Sent call stats",i),this._previousCallStatReport=t}};var Dn=1e3;function pe(s,r,e=0){return r in s&&s[r]?s[r]:e}function Ra(...s){return r=>{for(let e of s)if(e(r))return!0;return!1}}function it(s,r){return e=>e[s]===r}function kn(s){return(r,e)=>r[s]-e[s]}function Ei(s,r){return r.reduce((e,t)=>(e[t[s]]=t,e),{})}function On(s){let r={},e=[];for(let t of s)r[t.id]||(r[t.id]=!0,e.push(t));return e}function wn(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}function hr(s){return Object.keys(s).filter(r=>s[r]!==void 0).map(r=>[r,s[r]]).reduce((r,e)=>(r[e[0]]=wn(e[1])?hr(e[1]):e[1],r),{})}function xn(s){let r=[];for(let e of s)e.forEach(t=>r.push(t));return r}function Ln(s){return c(this,null,function*(){let r=[];return RTCRtpReceiver.prototype.getStats?(r.push(...s.getReceivers().map(e=>e.getStats())),r.push(...s.getSenders().map(e=>e.getStats()))):r.push(s.getStats()),Promise.all(r).then(xn).then(On)})}function Nn(s){let r=s.filter(it("type","candidate-pair")).sort(kn("priority")).find(Ra(it("nominated",!0),it("selected",!0)));if(!r)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let e={totalRoundTripTime:r.totalRoundTripTime||0,currentRoundTripTime:r.currentRoundTripTime||0,bytesSent:r.bytesSent,bytesReceived:r.bytesReceived},t=s.find(it("id",r.remoteCandidateId));t&&(e=Object.assign({},e,{remote:{type:t.candidateType,address:t.ip||t.address,port:t.port,protocol:t.protocol}}));let i=s.find(it("id",r.localCandidateId));return i&&(e=Object.assign({},e,{local:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol,relayProtocol:i.relayProtocol,networkType:i.networkType}})),hr(e)}function Un(s,r){let e=Ei("id",s),t=s.filter(Ra(it("type","inbound-rtp"),it("type","outbound-rtp")));y.browserName()==="Firefox"&&(t=Object.values(t.reduce((a,n)=>{if(!a[n.ssrc])a[n.ssrc]=n;else{let o=Object.assign({},a[n.ssrc],n),p=a[n.ssrc].isRemote?n:a[n.ssrc];o.id=p.id,o.type=p.type,delete o.isRemote,delete o.remoteId,a[o.ssrc]=o}return a},{})));let i={};if(y.browserName()==="Safari"){let a=s.filter(it("type","track"));i=Ei("trackIdentifier",a)}return t.map(a=>{let n=Number(a.ssrc),o=a.mediaType||a.kind,p=a.trackId,u=a.type,_=a.codecId;if(y.browserName()==="Safari"){let b=/^.+_([\d]+)$/.exec(a.id);if(b&&(n=parseInt(b[1],10)),o=a.id.indexOf("Audio")>0?"audio":"video",r[n]){let k=o+"-"+r[n];i[k]&&(p=i[k].id)}}if(!u||!n||!o)return null;let v={ssrc:n,type:u,kind:o,bytesReceived:pe(a,"bytesReceived"),bytesSent:pe(a,"bytesSent"),jitter:pe(a,"jitter"),packetsLost:pe(a,"packetsLost"),packetsReceived:pe(a,"packetsReceived"),packetsSent:pe(a,"packetsSent"),fractionLost:pe(a,"fractionLost"),pliCount:pe(a,"pliCount"),firCount:pe(a,"firCount"),nackCount:pe(a,"nackCount"),userId:r[n]};if(o==="video"){let b=pe(a,"framesDecoded"),k=pe(a,"totalInterFrameDelay"),D=pe(a,"totalSquaredInterFrameDelay");v.interframeDelayVariance=(D-k*k/b)/b}if(o==="audio"&&(v.totalSamplesReceived=pe(a,"totalSamplesReceived"),v.concealedSamples=pe(a,"concealedSamples"),v.insertedSamplesForDeceleration=pe(a,"insertedSamplesForDeceleration"),v.removedSamplesForAcceleration=pe(a,"removedSamplesForAcceleration"),v.silentConcealedSamples=pe(a,"silentConcealedSamples"),v.concealmentEvents=pe(a,"concealmentEvents"),v.totalAudioEnergy=pe(a,"totalAudioEnergy")),_&&e[_]){let b=e[_];v.clockRate=b.clockRate,v.mimeType=b.mimeType}if(p&&e[p]){let b=e[p];v.frameHeight=b.frameHeight,v.frameWidth=b.frameWidth,v.framesDecoded=b.framesDecoded,v.framesReceived=b.framesReceived,v.framesDropped=b.framesDropped}return hr(v)}).filter(a=>!!a)}function Bn(s,r){if(!r||!r.rtps||!s.rtps)return s;let e=Ei("ssrc",s.rtps),t=Ei("ssrc",r.rtps),i=(s.timestamp-r.timestamp)/1e3;return!e||!t||Object.keys(e).forEach(a=>{let n=e[a],o=t[a];if(!(!n||!o)){if(n.bytesReceived&&n.bytesReceived>o.bytesReceived&&(n.bandwidth=Math.round((n.bytesReceived-o.bytesReceived)/i)),n.bytesSent&&n.bytesSent>o.bytesSent&&(n.bandwidth=Math.round((n.bytesSent-o.bytesSent)/i)),n.packetsReceived)if(n.packetsReceived>o.packetsReceived||n.packetsLost>o.packetsLost){let p=n.packetsLost-o.packetsLost,u=n.packetsReceived-o.packetsReceived;n.packetLoss=parseFloat((100*p/(p+u)).toFixed(2))}else n.packetLoss=0;n.framesDropped&&o.framesDropped&&n.framesDropped>o.framesDropped&&(n.framesDroppedDelta=parseFloat(((n.framesDropped-o.framesDropped)/i).toFixed(0)))}}),s}function zt(t,i){return c(this,arguments,function*(s,r,e={}){let a=yield Ln(s),n={timestamp:Date.now(),transport:Nn(a),rtps:Un(a,e)};return r?Bn(n,r):(yield I.delay(Dn),zt(s,n,e))})}var Ii=.8,rt=class extends ie{constructor(e,t,i,a,n,o={}){super();this._remoteSDP={};this._remoteCandidates={};this._state="IDLE";this._animojiDataChannel=null;this._animojiReceiver=null;this._animojiSender=null;this._animojiSvgDataByParticipantId={};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=a,this._participantId=e,this._isMaster=t,this._serverSettings=n,this._animojiSvgDataByParticipantId=o,this._perfStatReporter=new tt(this,i,!0),this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,"TRACK_REPLACED",this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,"SOURCE_CHANGED",this._applySettings.bind(this)),this.subscribe(this._mediaSource,"ANIMOJI_STATUS",this._onAnimojiStatus.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={},l.useVmoji&&this._createDataChannel(this._pc,$e.animoji,p=>{this._animojiDataChannel=p,this._animojiDataChannel.binaryType="arraybuffer",this._createAnimojiReceiver(),this._mediaSource.getAnimojiEnabled()&&this._createAnimojiSender()}),this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,l.p2pAudioRed),this._applySettings()}catch(p){S.log(R.ERROR,"addTrack-direct"),d.error("Unable to add media source tracks",p,{participantId:this._participantId}),this._failedOnCreate=p;return}this._createOffer(!1).catch(p=>{this._state==="IDLE"?this._failedOnCreate=p:this.close(p)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!=="IDLE"&&e!=="CLOSED"&&e!=="FAILED"&&this._startStatInterval()}open(e=null){return c(this,null,function*(){if(this._isOpen){d.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(d.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){S.log(R.ERROR,"addTrack-direct"),d.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState("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){vi(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._removeAnimojiReceiver(),this._removeAnimojiSender(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent("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?(d.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState("FAILED")):(d.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState("CLOSED")),this._triggerEvent("PEER_CONNECTION_CLOSED")}setAnimojiSvg(e,t){var i;(i=this._animojiReceiver)==null||i.setParticipantSvg(e,t)}_setState(e){this._state!==e&&(d.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent("STATE_CHANGED",e))}_onSignalingNotification(e){var t,i,a,n;switch(e.notification){case w.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case w.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case w.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((a=e.data.sdk)==null?void 0:a.rtt)||0,this._remoteNetworkStat.loss=((n=e.data.sdk)==null?void 0:n.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=I.getPeerIdString(e.peerId);I.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){d.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw S.log(R.ERROR,"addIceCandidate-direct"),d.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else d.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return c(this,null,function*(){if(!this._remoteCandidates[e]){d.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(a){}})}_setRemoteDescription(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){d.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 S.log(R.ERROR,"setRemoteDescription-direct"),d.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){d.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("REMOTE_TRACK_REMOVED",this._remoteStream,t.track)}),this._triggerEvent("REMOTE_TRACK_ADDED",this._remoteStream,e.track)}_handleIceCandidate(e){return c(this,null,function*(){e.candidate&&this._signaling.ready&&(d.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(d.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>c(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(d.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e==="IDLE"||e==="OPENED"?this._setState("CONNECTING"):this._setState("RECONNECTING");break}}_onConnectionStateChange(){switch(d.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),S.log(R.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState("CONNECTED"),this._stopReconnection(),I.getPeerConnectionHostInfo(this._pc).then(e=>{e&&S.log(R.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState("RECONNECTING"),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(d.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&&(d.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology("SERVER"))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(S.log(R.ICE_RESTART),d.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):d.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,d.error("Ice restart failed",{participantId:this._participantId}),S.log(R.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},l.iceRestartWaitTime)}_createOffer(e){return c(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return d.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw d.error("Unable to create offer",i,{participantId:this._participantId}),S.log(R.ERROR,"createOffer-direct"),i}).then(i=>c(this,null,function*(){return d.debug("Created offer",{participantId:this._participantId,offer:i}),i=rt._patchDescription(i),d.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw d.error("Unable to set local description",i,{participantId:this._participantId}),S.log(R.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return c(this,null,function*(){return d.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw d.error("Unable to create answer",e,{participantId:this._participantId}),S.log(R.ERROR,"createAnswer-direct"),e}).then(e=>c(this,null,function*(){return d.debug("Created answer",{participantId:this._participantId,answer:e}),e=rt._patchDescription(e),d.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw d.error("Unable to set local description",e,{participantId:this._participantId}),S.log(R.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=I.patchLocalSDP(e.sdp,l.preferH264&&y.canPreferH264(),y.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=>{d.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),S.log(R.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_onAnimojiStatus(e){e?this._createAnimojiSender():this._removeAnimojiSender(),this._mediaSource.onAnimojiSender(e)}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}zt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:"DIRECT",transport:t.transport,rtps:t.rtps.filter(a=>a.type==="inbound-rtp"?(a.userId=this._participantId,!0):!1)},outbound:{topology:"DIRECT",transport:t.transport,rtps:t.rtps.filter(a=>a.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent("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=G=>G.rtt<=this._networkLimits.goodNet.rtt&&G.loss<=this._networkLimits.goodNet.loss,i=G=>G.rtt>=this._networkLimits.badNet.rtt||G.loss>=this._networkLimits.badNet.loss,a=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((G,X)=>Math.max(G,X.packetLoss||0),0),o={rtt:this._lastNetworkStat.rtt*(1-Ii)+a*Ii,loss:this._lastNetworkStat.loss*(1-Ii)+n*Ii},p=i(o),u=t(o),_=i(this._remoteNetworkStat),v=t(this._remoteNetworkStat),b=i(this._lastNetworkStat),k=t(this._lastNetworkStat),j=p||_?.2:u&&v?1:0,he=Date.now();if((b!==p||k!==u||he-this._lastNetworkStat.date>l.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},o)},null).catch(G=>{d.warn("Unable to send [bad-net]",G)})),j){let G={};G[this._participantId]=G[""]=j,this._triggerEvent("NETWORK_STATUS",G)}this._lastNetworkStat.rtt=o.rtt,this._lastNetworkStat.loss=o.loss}_startSettingsInterval(){if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,2e3)};this._settingsInterval=window.setTimeout(t,2e3)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=I.sdpFingerprint(e);if(t===null){d.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;if(e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=I.applySettings(this._pc,e,this._prevConsumerSettings)),this._animojiSender){let i=this._mediaSource.getStream();i&&this._animojiSender.setStream(i)}}_createDataChannel(e,t,i){d.debug(`[${t}] data channel opening`);let a=e.createDataChannel(t,{negotiated:!0,id:1});a.onopen=()=>{let n=a.readyState;n==="open"?(d.debug(`[${t}] data channel opened`),a.onerror=o=>{d.error(`[${t}] data channel error`,o)},i(a)):d.error(`[${t}] data channel open failed, state [${n}]`)}}_createAnimojiReceiver(){!l.useVmoji||!this._animojiDataChannel||!this._participantId||(this._animojiReceiver&&this._removeAnimojiReceiver(),this._animojiReceiver=new l.vmoji.AnimojiReceiver(this._animojiDataChannel,this._participantId,(e,t)=>{this._triggerEvent("ANIMOJI_STREAM",e,t)},e=>{this._triggerEvent("ANIMOJI_STREAM",e,null)}),Object.entries(this._animojiSvgDataByParticipantId).forEach(([e,t])=>{this._animojiReceiver.setParticipantSvg(e,t)}))}_removeAnimojiReceiver(){var e;(e=this._animojiReceiver)==null||e.destroy(),this._animojiReceiver=null}_createAnimojiSender(){if(!l.useVmoji||!this._animojiDataChannel)return;let e=this._mediaSource.getStream();e&&(this._animojiSender&&this._removeAnimojiSender(),this._animojiSender=new l.vmoji.AnimojiSender(this._animojiDataChannel,e))}_removeAnimojiSender(){var e;(e=this._animojiSender)==null||e.destroy(),this._animojiSender=null}};var Vn=16,wt=class{constructor(r,e,t){d.debug("AsrReceiver started"),this._datachannel=r,this._participantIdRegistry=e,this._asrCallback=t,this._textDecoder=new TextDecoder,this._datachannel.onmessage=i=>this._onDataChannelMessage(i.data)}static parse(r){let e=new DataView(r),t=e.getUint8(0),i=e.getUint8(1);if(i!==0)throw new Error(`Unsupported message type. Message type: ${i}`);let a=e.getUint16(2),n=e.getUint32(4),o=e.getUint32(8),p=e.getUint32(12);if(t!==1)throw new Error(`Unexpected protocol version. Got ${t}, expected 1`);return{sequence:a,ssrc:n,timestamp:o,duration:p,data:r.slice(Vn)}}_onDataChannelMessage(r){var a,n;let e=wt.parse(r),t=(n=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(e.ssrc))==null?void 0:n.participantId;if(!t){d.warn(`Participant id for ssrc ${e.ssrc} not found in registry`);return}let i={participantId:t,text:this._textDecoder.decode(e.data),timestamp:e.timestamp,duration:e.duration};this._asrCallback(i)}destroy(){this._datachannel.onmessage=null}};import{decode as ht}from"messagepack";var Ti=class{constructor(){this.streamDescriptionByCompactId=new Map;this.compactIdByStreamDescription=new Map}getStreamDescription(r){return this.streamDescriptionByCompactId.get(r)}getCompactId(r){return this.compactIdByStreamDescription.get(r)}handleMessage(r){var a,n;let e=new Uint8Array(r),t=e[0],i=e.subarray(1);switch(t){case 1:let o=ht(i);return Object.entries(o).forEach(([D,$])=>{let j=Kt(D);this.streamDescriptionByCompactId.set($,j),this.compactIdByStreamDescription.set(D,$)}),null;case 2:case 4:let p=ht(i),u=[];for(let D of p){let $=this.getStreamDescription(D);$&&u.push($.participantId)}return t===2?{type:"notification",notification:w.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:w.STALLED_ACTIVITY,stalledParticipants:u};case 3:let _=ht(i);return{type:"notification",notification:w.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(_))==null?void 0:a.participantId};case 5:let v=ht(i);return{type:"notification",notification:w.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:v[0],maxDimension:v[1]}};case 6:let b=ht(i),k={};for(let[D,$]of Object.entries(b)){let j=(n=this.getStreamDescription(Number(D)))==null?void 0:n.participantId;j&&(k[j]=$/100)}return{type:"notification",notification:w.NETWORK_STATUS,statuses:k};case 7:return this._createParticipantSourcesUpdateNotification(i);case 8:{let $=ht(i).map(j=>{var Y;let[he,G,X,_e,Ee,at,ii]=j;return{participantId:(Y=this.getStreamDescription(he))==null?void 0:Y.participantId,gain:G,pause:X,offset:_e,mute:Ee,liveStatus:at,startTimeMs:ii}});return{type:"notification",notification:w.MOVIE_UPDATE_NOTIFICATION,data:$}}default:return d.debug("unsupported message type: "+t),null}}_createParticipantSourcesUpdateNotification(r){let e=ht(r),t=[];for(let[i,a]of Object.entries(e)){let n=a[0],o=a[1],p=a[2],u;if(n!==null){if(u=this.getStreamDescription(n),!u){d.error(`could not uncompress participant ID ${n}`);continue}}else u=null;if(p===null){d.error("unexpected null sequenceNumber",i,a);continue}let _=Oe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+i,v=o?o>>>0:null;t.push({participantStreamDescription:u,streamId:_,rtpTimestamp:v,sequenceNumber:p})}return{type:"notification",notification:w.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:t}}};var Fn=90,jn=4294967295,Pe=class extends ie{constructor(e,t,i,a={}){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._asr=null;this._animojiDataChannel=null;this._animojiReceiver=null;this._animojiSender=null;this._animojiSvgDataByParticipantId={};this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state="IDLE";this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._asrTrack=null;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.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,"TRACK_REPLACED",this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,"SOURCE_CHANGED",this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,"SCREEN_STATUS",this._onScreenSharingStatus.bind(this)),this.subscribe(this._mediaSource,"ANIMOJI_STATUS",this._onAnimojiStatus.bind(this)),this._perfStatReporter=new tt(this,e),this._serverSettings=i,this._animojiSvgDataByParticipantId=a,d.debug("ServerTransport: Created")}getState(){return this._state||"IDLE"}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!=="IDLE"&&e!=="CLOSED"&&e!=="FAILED"&&this._startStatInterval()}open(e=!1){if(this._isOpen){d.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(d.error("ServerTransport: Closed",e),this._setState("FAILED")):(d.debug("ServerTransport: Closed"),this._setState("CLOSED"))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){vi(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}setAnimojiSvg(e,t){var i;(i=this._animojiReceiver)==null||i.setParticipantSvg(e,t)}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeAsrTrack(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._removeAnimojiReceiver(),this._removeAnimojiSender(),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,Pe._closeDataChannel(this._producerNotification),Pe._closeDataChannel(this._producerCommand),Pe._closeDataChannel(this._producerScreen),Pe._closeDataChannel(this._consumerScreen),Pe._closeDataChannel(this._asr),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent("PEER_CONNECTION_CLOSED")}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){d.debug(`[${t}] data channel opening`);let a=e.createDataChannel(t,{ordered:!0});a.onopen=()=>{let n=a.readyState;n==="open"?(d.debug(`[${t}] data channel opened`),i(a)):d.error(`[${t}] data channel open failed, state [${n}]`)},a.onerror=n=>{let o=n.error;d.error(`[${t}] data channel error`,o==null?void 0:o.errorDetail,o==null?void 0:o.message)}}_openConnection(e=!1){d.debug("ServerTransport: Open single connection"),this._pc=new RTCPeerConnection({},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=I.throttle(t=>{this._pc&&this._onConnectionStateChange(this._pc,t)},500),this._pc.onsignalingstatechange=Pe._onSignalingStateChange.bind(this,this._pc),this._participantIdRegistry=new Ti,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),l.producerNotificationDataChannel&&this._createDataChannel(this._pc,$e.producerNotification,t=>{this._producerNotification=t,this._producerNotification.binaryType="arraybuffer",this._signaling.setProducerNotificationDataChannel(t)}),l.producerCommandDataChannel&&(this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,$e.producerCommand,t=>{this._producerCommand=t,this._signaling.setProducerCommandDataChannel(t)})),l.producerScreenDataChannel&&this._createDataChannel(this._pc,$e.producerScreenShare,t=>{this._producerScreen=t,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()}),l.asrDataChannel&&this._createDataChannel(this._pc,$e.asr,t=>{this._asr=t,this._asr.binaryType="arraybuffer",this._removeAsrTrack(),this._asrTrack=new wt(t,this._participantIdRegistry,i=>{this._onAsrTranscription(i)}),this._signaling.setAsrDataChannel(t)}),l.useVmoji&&this._createDataChannel(this._pc,$e.animoji,t=>{this._animojiDataChannel=t,this._animojiDataChannel.binaryType="arraybuffer",this._createAnimojiReceiver(),this._mediaSource.getAnimojiEnabled()&&this._createAnimojiSender()}),this._newAudioShareTrack=this._mediaSource.getAudioShareTrack();try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,l.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(t){d.error("ServerTransport: Unable to add media source tracks",t),S.log(R.ERROR,"addTrack-single"),this.close(t);return}l.consumerScreenDataChannel&&this._createDataChannel(this._pc,$e.consumerScreenShare,t=>{this._consumerScreen=t,this._consumerScreen.binaryType="arraybuffer";let i=this._mediaSource.getScreenTrack();i&&this._createCaptureSender(i)}),e||this._allocateConsumer(),this._setState("OPENED"),this._startStatInterval(),this._startSettingsInterval()}_removeAsrTrack(){var e;(e=this._asrTrack)==null||e.destroy(),this._asrTrack=null}_reconnect(){this.getState()!=="OPENED"&&(this._setState("RECONNECTING"),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_signalStalledParticipants(e){this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_signalSpeakerChanged(e){this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_signalNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_updateSSRCMap(e){e&&e.sdp.split(`
|
|
12
|
+
`).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Oe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,a=new RegExp(i).exec(t);a&&(this._ssrcMap[a[1]]=a[3])})}_createCaptureSender(e){let t=this._mediaSource.getMediaSettings();!e||!l.consumerScreenDataChannel||!this._consumerScreen||!t.isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new pt(e,this._consumerScreen,this._signaling,t.isFastScreenSharingEnabled))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!l.producerScreenDataChannel||!this._producerScreen||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new dt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent("REMOTE_STREAM_SECOND",e,t)},e=>{this._triggerEvent("REMOTE_STREAM_SECOND",e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_createAnimojiSender(){if(!l.useVmoji||!this._animojiDataChannel)return;let e=this._mediaSource.getStream();e&&(this._animojiSender&&this._removeAnimojiSender(),this._animojiSender=new l.vmoji.AnimojiSender(this._animojiDataChannel,e))}_removeAnimojiSender(){var e;(e=this._animojiSender)==null||e.destroy(),this._animojiSender=null}_createAnimojiReceiver(){!l.useVmoji||!this._animojiDataChannel||!this._participantIdRegistry||(this._animojiReceiver&&this._removeAnimojiReceiver(),this._animojiReceiver=new l.vmoji.AnimojiReceiver(this._animojiDataChannel,this._participantIdRegistry,(e,t)=>{this._triggerEvent("ANIMOJI_STREAM",e,t)},e=>{this._triggerEvent("ANIMOJI_STREAM",e,null)}),Object.entries(this._animojiSvgDataByParticipantId).forEach(([e,t])=>{this._animojiReceiver.setParticipantSvg(e,t)}))}_removeAnimojiReceiver(){var e;(e=this._animojiReceiver)==null||e.destroy(),this._animojiReceiver=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!=="video")return;let a=!this._disabledSenders.has(i),n=e.maxDimension!==0;if(a&&!n){d.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(y.getBlackMediaTrack()).catch(p=>{d.error("Could not disable video upload",p)});return}let o=this._mediaSource.getSendVideoTrack();if(!a&&n&&o){d.log("Enabling video upload"),this._disabledSenders.delete(i);let p=i.track;p.enabled=o.enabled,i.replaceTrack(o).then(()=>p.stop()).catch(u=>{d.error("Could not enable video upload",u)})}I.applyVideoTrackSettings(e,i,o!=null?o:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}if(this._animojiSender){let t=this._mediaSource.getStream();t&&this._animojiSender.setStream(t)}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_onAnimojiStatus(e){e?this._createAnimojiSender():this._removeAnimojiSender(),this._mediaSource.onAnimojiSender(e)}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent("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(){if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,2e3)};this._settingsInterval=window.setTimeout(t,2e3)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return c(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield zt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent("REMOTE_DATA_STATS",{inbound:{topology:"SERVER",transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:"SERVER",transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(o=>o.type==="inbound-rtp"&&o.kind==="audio"&&this._ssrcMap[o.ssrc]==="mix");if(!t)return;let i=Oe.AUDIO_MIX,a=this._statBytes[i],n=!1;if(a){let o=t.bytesReceived-a.bytesReceived;o>=0&&o<=5&&(n=!0),a.stalled!==n&&this._triggerEvent("REMOTE_ALL_STALL",n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:tt.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,asrDataChannelVersion:l.asrDataChannel?1:0,animojiDataChannelVersion:l.useVmoji?1:0,onDemandTracks:!0,unifiedPlan:!0,singleSession:!0,videoTracksCount:l.videoTracksCount,red:l.serverAudioRed,audioShare:l.audioShare};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return c(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,d.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:I.patchRemoteSDP(e)});if(d.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw d.error("[single] unable to set remote offer",i),S.log(R.ERROR,"setRemoteDescription-single"),i}).then(()=>c(this,null,function*(){if(d.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this.handleTracks(),this._pc.createAnswer()})).catch(i=>{throw d.error("[single] unable to create answer",i),S.log(R.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=I.patchLocalSDP(i.sdp,!1,y.isBrokenH264(),!1,l.h264spsPpsIdrInKeyframe),i)).then(i=>c(this,null,function*(){if(d.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw d.error("[single] unable to set local answer",i),S.log(R.ERROR,"setLocalDescription-single"),i}).then(i=>c(this,null,function*(){d.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),d.debug("[single] remote offer has been processed")})).catch(i=>{d.warn("[single] unable to send local answer",i),S.log(R.ERROR,"acceptProducer")}).then(()=>c(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){d.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&&d.warn("Unexpected track assigned to audioshare"),e.direction="sendonly",e.sender.replaceTrack(this._newAudioShareTrack).catch(t=>{d.error("ServerTransport: Unable to replace track",t),S.log(R.ERROR,"replaceTrack-single")}),this._newAudioShareTrack=null)}),this._newAudioShareTrack&&d.warn("Cannot find audioshare transceiver"))}_onSignalingNotification(e){return c(this,null,function*(){if(this._isOpen)switch(e.notification){case w.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case w.REALLOC_CON:this._reconnect();break;case w.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case w.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case w.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case w.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onAsrTranscription(e){this._triggerEvent("ASR_TRANSCRIPTION",e)}_onProducerUpdated(e){return c(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),l.breakVideoPayloadTypes&&(d.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes",null)),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){d.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent("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("REMOTE_TRACK_ADDED",i.id,i,t.track)):d.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){d.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(d.debug("[single] connection state changed",{state:e.connectionState},t),S.log(R.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==="IDLE"||i==="OPENED"?this._setState("CONNECTING"):e.iceConnectionState==="checking"&&this._setState("RECONNECTING");break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState("RECONNECTING");break;case"connected":this._setState("CONNECTED"),I.getPeerConnectionHostInfo(e).then(a=>{a&&S.log(R.ICE_CONNECTION_TYPE,a.type)});break}}_onReplacedTrack(e,t){if(this._pc){l.consumerScreenDataChannel&&t&&(e=t);let i=!1;this._pc.getSenders().forEach(a=>{a.track&&a.track.kind===e.kind&&!this._disabledSenders.has(a)&&a.track.contentHint===e.contentHint&&(a.track.enabled=e.enabled,a.replaceTrack(e).catch(n=>{d.error("ServerTransport: Unable to replace track",n),S.log(R.ERROR,"replaceTrack-single")}),i=!0)}),!i&&e.kind==="audio"&&e.contentHint==="music"&&(this._newAudioShareTrack=e)}this._applyConsumerSettings()}getStreamWaitingTimeMs(e,t){if(!this._pc)return S.log(R.PAT_WAITING_TIME_ERROR,"noConnection"),d.error("Cannot get stream waiting time, peer connection is not initialized"),0;if(!RTCRtpReceiver.prototype.getSynchronizationSources)return S.log(R.PAT_WAITING_TIME_ERROR,"oldBrowser"),d.error("Cannot get stream waiting time, RTCRtpReceiver.getSynchronizationSources is not supported"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return S.log(R.PAT_WAITING_TIME_ERROR,"noReceiver"),d.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let a=i.getSynchronizationSources();if(!a||!a.length)return d.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let o=a[0].rtpTimestamp;if(!Number.isInteger(o))return S.log(R.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),d.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${o}`),0;let p=t-o&jn,u=Math.ceil(p/Fn);return Math.min(100,Math.max(0,u))}};var mt=(e=>(e.DIRECT="DIRECT",e.SERVER="SERVER",e))(mt||{}),Ri=class extends ie{constructor(e,t,i,a){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._animojiSvgDataByParticipantId={};this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=a,this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){d.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(d.log(`Trying allocate participant [${e}]`),this._allocated.indexOf(e)!==-1){d.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,a=!1){d.log("Trying open participant",{participantIds:e});let n=a;for(let o of e){if(this._opened.indexOf(o)!==-1){d.warn(`The participant [${o}] has already had opened transport`);continue}if(this._allocated.indexOf(o)===-1){d.warn(`The participant [${o}] has no allocated transport`);continue}this._opened.push(o),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())),d.debug("The transport has been opened",e))}close(e){var a;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&d.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((a=this._serverTransport)==null||a.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()}setAnimojiSvg(e,t){this._animojiSvgDataByParticipantId[e]=t,(!(t.svg instanceof ArrayBuffer)||t.svg.byteLength!==0)&&(this._topology==="DIRECT"&&this._directTransport?this._directTransport.setAnimojiSvg(e,t):this._topology==="SERVER"&&this._serverTransport&&this._serverTransport.setAnimojiSvg(e,t))}_setStates(e,t){let i=e.filter(a=>this._states[a]!==t?(this._states[a]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===w.TOPOLOGY_CHANGED)return this._onTopologyChanged(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(d.log(`Topology changed ${this._topology} -> ${e.topology}`),S.log(R.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||[],a=e.offerToTypes||[],n=e.offerToDeviceIdxs||[],o=i.length&&a.length?I.composeParticipantId(i[0],a[0],n[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){d.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&d.warn("Topology changed to DIRECT, but the allocated participants count more then one");let p=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let u=o===p;this._directTransport=this._createDirectTransport(p,u)}this._opened.indexOf(p)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_createDirectTransport(e,t=!1){let i=new rt(e,t,this._signaling,this._mediaSource,this._serverSettings,this._animojiSvgDataByParticipantId);return this._dtListeners&&this._dtListeners.length>0&&d.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.addEventListener("ANIMOJI_STREAM",this._onAnimojiStream.bind(this))),i}_createServerTransport(){let e=new Pe(this._signaling,this._mediaSource,this._serverSettings,this._animojiSvgDataByParticipantId);return this._stListeners&&this._stListeners.length>0&&d.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.addEventListener("ASR_TRANSCRIPTION",this._onAsrTranscription.bind(this)),e.addEventListener("ANIMOJI_STREAM",this._onAnimojiStream.bind(this))),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 a=this._allocated.indexOf(e);a>=0&&this._allocated.splice(a,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)}_onAsrTranscription(e){this._triggerEvent("ASR_TRANSCRIPTION",e)}_onAnimojiStream(e,t){this._triggerEvent("ANIMOJI_STREAM",e,t)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(S.log(R.PAT_WAITING_TIME_ERROR,"wrongTopology"),d.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(S.log(R.PAT_WAITING_TIME_ERROR,"noTransport"),d.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Ci=class extends ie{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,"REMOTE_TRACK_ADDED",this._onRemoteTrackAdded.bind(this)),this.subscribe(e,"REMOTE_TRACK_REMOVED",this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,"SIGNALLED_ACTIVE_PARTICIPANTS",this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,"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 a;if(i.kind==="audio"&&((a=this._detector)==null||a.destroy(),this._detector=new kt(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,l.voiceParams.interval)};this._interval=window.setTimeout(n,l.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind==="audio"&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===Oe.AUDIO_MIX){if(this._activeParticipants)for(let a of this._activeParticipants)e[a]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e==="DIRECT"&&(this._activeParticipants=null)}};var yi=class extends ie{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i==="SERVER",this.subscribe(e,"VOLUMES_DETECTED",this._onVolumesDetected.bind(this)),this.subscribe(t,"SIGNALLED_SPEAKER_CHANGED",this._onServerSpeakerChanged.bind(this)),this.subscribe(t,"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(a=>{let n=e[a].smoothed;n>t&&n>l.voiceParams.threshold&&(t=n,i=a)}),i&&i!==this._speakerId){let a=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>a*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==="SERVER"}};var Yt=class extends ie{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,"STATE_CHANGED",this._onTransportStateChanged.bind(this)),this.subscribe(t,"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==="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==="FAILED"&&this._connectionTimeout&&(d.warn("Transport failed, send callSpecError"),S.log(R.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!=="CONNECTED";(()=>Object.values(this._states).filter(e).length>0)()&&(d.warn("There is not connected transport, send callSpecError"),S.log(R.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",a=this._participants[t];a&&a.platform&&(i=a.platform),e.indexOf(i)<0&&(e.push(i),S.log(R.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&d.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Hn=1e3,Gn=1e4;var Wn=15,H=class extends ie{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._myLastRequestedLayouts={};this._state="IDLE";this._participantState=W.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;S.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),S.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new $t,l.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Hn))}static current(){return H._current}static hangupAfterInit(){H._activationMutex&&!H._current&&(H._delayedHangup=!0)}static id(){var e,t;return((t=(e=H._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,a="",n=!1,o=!1,p){return c(this,null,function*(){if(H._activationMutex)throw S.log(R.ERROR,"startCall"),d.warn("Conversation: there is already running activation"),new V(O.FAILED);H._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let u=this._mediaSource.getMediaSettings();t===We.CHAT||e.length>1?this._logWithMediaSettings(R.OUTGOING_MULTIPARTY_CALL,u):this._logWithMediaSettings(R.OUTGOING_CALL,u);let _=yield this._startConversation(e,t,Je.OUTGOING,i,a,n,o,p);if(!this._conversation)throw new V(O.UNKNOWN_ERROR);if(this._participantState=W.ACCEPTED,this._signaling.changeMediaSettings(u),yield this._processConnection(_),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),H._delayedHangup)throw new V(O.CANCELED);d.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let v=Object.values(this._participants),b;return l.batchParticipantsOnStart&&(b=I.mapSharedParticipants(v)),yield this._processConnectionSharedMovieInfo(_),g.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),b),this._onConversationParticipantListChunk(_),g.onLocalStatus("WAITING"),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),H._current=this,this._conversation.concurrent?yield this._acceptConcurrent():l.batchParticipantsOnStart||this._setParticipantsStatus(v,"WAITING"),this._conversation}catch(u){throw this._close(u,"Unable to start conversation"),u}finally{H._activationMutex=!1}})}onJoin(e){return c(this,null,function*(){var t;if(H._activationMutex)throw S.log(R.ERROR,"joinCall"),d.warn("Conversation: there is already running activation"),new V(O.FAILED);H._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)!=null&&t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let a=this._mediaSource.getMediaSettings();this._logWithMediaSettings(R.JOIN_CONVERSATION,a);let n=yield this._joinConversation(e);if(!this._conversation)throw new V(O.UNKNOWN_ERROR);return this._conversation.observer=i,g.onLocalStream(this._mediaSource.getStream(),a),this._conversation.waitingHall?(d.log("In waiting hall"),H._current=this,H._activationMutex=!1,this._signaling.readyToSend(),g.onLocalStatus("WAITING_HALL"),this._conversation):this._onJoinPart2(n)}catch(i){throw H._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return c(this,null,function*(){var t,i,a,n,o,p,u;d.debug("Join conversation part 2"),H._activationMutex=!0;try{if(this._participantState=W.ACCEPTED,!this._conversation||!this._mediaSource)throw new V(O.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._processConnection(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),H._delayedHangup)throw new V(O.CANCELED);let _=Object.values(this._participants),v;l.batchParticipantsOnStart&&(v=I.mapSharedParticipants(_.filter(D=>!D.isInRoom)));let b=[];if((i=(t=e==null?void 0:e.rooms)==null?void 0:t.rooms)!=null&&i.length)for(let D of e.rooms.rooms)b.push({id:D.id,name:D.name,participantCount:D.participantCount,participantIds:yield Promise.all(((n=(a=D==null?void 0:D.participantIds)==null?void 0:a.map)==null?void 0:n.call(a,this._getExternalIdByParticipantId.bind(this)))||[]),participants:(o=D==null?void 0:D.participants)!=null&&o.participants?this._participantListChunkToExternalChunk(D.participants):void 0,active:D.active,muteStates:D.muteStates});let k=(u=(p=e==null?void 0:e.rooms)==null?void 0:p.roomId)!=null?u:null;return yield this._processConnectionSharedMovieInfo(e),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),v,{rooms:b,roomId:k}),this._onConversationParticipantListChunk(e),g.onLocalStatus("WAITING"),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),H._current=this,l.batchParticipantsOnStart||this._setParticipantsStatus(_,"WAITING"),this._openTransport(_,!1),this._conversation}catch(_){throw this._close(_,"Unable to join conversation"),_}finally{H._activationMutex=!1}})}onPush(a){return c(this,arguments,function*(e,t=z.USER,i){if(H._activationMutex)throw d.warn("Conversation: there is already running activation"),new V(O.REJECTED);H._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new V(O.UNKNOWN_ERROR);if(!n.conversation.participants.find(p=>{var u;return p.state===W.CALLED&&p.id===((u=this._conversation)==null?void 0:u.userId)}))throw d.log("Push rejected (there is an active call)"),S.log(R.PUSH,"rejected"),new V(O.REJECTED);if(yield this._processConnection(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),S.log(R.PUSH,"accepted"),H._current=this,H._delayedHangup)throw new V(O.CANCELED);H._activationMutex=!1}catch(n){throw H._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Bi.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>I.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return c(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new V(O.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(R.ACCEPT_CONCURRENT,e),d.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),g.onCallAccepted(),this._state="ACTIVE",this._participantState=W.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return c(this,null,function*(){var t;if(this._state!=="IDLE")throw S.log(R.ERROR,"acceptIncoming"),d.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new V(O.UNKNOWN_ERROR);this._state="PROCESSING",d.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let i=this._mediaSource.getMediaSettings();this._logWithMediaSettings(R.ACCEPT_INCOMING,i),this._signaling.changeMediaSettings(i),yield this._signaling.acceptCall(i),this._participantState=W.ACCEPTED;let a=Object.values(this._participants),n;if(l.batchParticipantsOnStart&&(n=I.mapSharedParticipants(a)),g.onCallAccepted(),g.onLocalStream(this._mediaSource.getStream(),i),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),n),l.useParticipantListChunk){let u=yield this._getInitialParticiapntListChunk();(t=u==null?void 0:u.participants)==null||t.forEach(_=>{let v=I.composeId(_),b=this._participants[v];b&&(b.movieShareInfos=_.movieShareInfos)}),this._onConversationParticipantListChunk({participants:u})}g.onLocalStatus("WAITING"),this._toggleJoinAvailability(),this._changeNeedRate();let o=At(this._getMuteStatesForCurrentRoom(),ke.MUTE),p=At(this._getMuteStatesForCurrentRoom(),ke.MUTE_PERMANENT);for(let u of[o,p])u.length&&(yield this._processMuteState({mediaOptions:u,stateUpdated:!0}));return this._state="ACTIVE",this._changeFeatureSet(),l.batchParticipantsOnStart||this._setParticipantsStatus(a,"WAITING"),this._openTransport(a,!0),this._conversation}catch(i){throw this._close(i,"Unable to accept call"),i}})}decline(){return c(this,null,function*(){var e;if(this._state!=="IDLE")throw S.log(R.ERROR,"declineIncoming"),d.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",d.debug("Decline incoming call"),this._logWithMediaSettings(R.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=W.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(O.REJECTED)),this._close(new V(O.REJECTED))})}hangup(){return c(this,null,function*(){d.debug("Hangup");let e=this._state==="ACTIVE"?O.HUNGUP:O.CANCELED;S.log(R.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new V(e))):g.onHangup(new V(O.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return c(this,null,function*(){if(!this._signaling.ready){this._close(new V(O.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),a=null;i.type==="error"&&(i.error==="call-unfeasible"?a=i.status:a=O.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(I.composeId(n),n,a)})}removeParticipant(e,t=!1){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var a;if(!this._transport)return;let i=[];for(let n of e)(n.state===W.CALLED||n.state===W.ACCEPTED)&&(this._transport.isAllocated(n.id)||this._transport.allocate(n.id,t)),n.state===W.ACCEPTED&&i.push(n.id);i.length&&this._transport.open(i,null,!!((a=this._conversation)!=null&&a.observer))}_close(e,t){t&&d.error(t,e),d.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(O.FAILED):S.log(R.ERROR,e.hangup),H._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([O.CANCELED,O.NOT_FRIENDS,O.CALLEE_IS_OFFLINE,O.CALLER_IS_BLOCKED,O.CALLER_IS_REJECTED].indexOf(e.hangup)!==-1||e.hangup===O.REJECTED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===O.HUNGUP&&(!e.remote||this._participantState===W.CALLED)){g.onHangup(e,i),this.destroy();return}if(e.hangup===O.MISSED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===O.SOCKET_CLOSED&&H._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===O.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=W.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),S.destroy(),this._conversation=null,this._myLastRequestedLayouts={},H._current=null,H._delayedHangup=!1,g.onHangup(e||new V(O.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;d.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),S.destroy(),this._conversation=null,this._myLastRequestedLayouts={},H._current=null,H._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return c(this,null,function*(){let t=yield this._api.getConversationParams(e);d.debug("Api.getConversationParams",t);let i=[],{turn_server:a,stun_server:n}=t;if(n&&i.push(n),a){let o=a.urls.filter((p,u,_)=>_.indexOf(p)===u);o.push(`${o[o.length-1]}?transport=tcp`),i.push({urls:o,username:a.username,credential:a.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,a,n="",o=!1,p=!1,u){return c(this,null,function*(){let _=I.uuid();d.debug("Conversation: start",{conversationId:_,opponentIds:e,opponentType:t,direction:i});let v=a.includes(de.VIDEO),b=yield this._api.startConversation(_,e,t,v,n,o,p,{onlyAdminCanShareMovie:u});d.debug("Api.startConversation",b);let k=yield this._getConversationParams(b.id);b.endpoint=this._addGeoParamsToEndpoint(b.endpoint,k);let D=yield this._connectSignaling(Ke.START,b);return yield this._setConversation(b,D,i),D})}_joinConversation(e){return c(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:a,joinLink:n,observedIds:o,payload:p}=e;d.debug("Conversation: join",{conversationId:t,joinLink:n,observedIds:o});let u=i.includes(de.VIDEO),_;if(t)_=yield this._api.joinConversation(t,u,a);else if(n)_=yield this._api.joinConversationByLink(n,u,o,p);else throw new V(O.UNKNOWN_ERROR);d.debug("Api.joinConversation",_),yield this._getConversationParams(_.id);let v=yield this._connectSignaling(Ke.JOIN,_);return yield this._setConversation(_,v,Je.JOINING),v})}_prepareConversation(a){return c(this,arguments,function*(e,t=z.USER,i){d.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let n=this._api.getUserId();if(!n)throw new V(O.UNKNOWN_ERROR);let o=yield this._getConversationParams(e),p=o.device_idx||0,u=`${l.wssBase}?userId=${n}&entityType=${t}&deviceIdx=${p}&conversationId=${e}&token=${l.wssToken}`;u=this._addGeoParamsToEndpoint(u,o);let _={id:e,peerId:i,endpoint:u,is_concurrent:!1,p2p_forbidden:!1,device_idx:p},v=yield this._connectSignaling(Ke.ACCEPT,_);return H._current&&(H._current._participantState===W.ACCEPTED||H._current._participantState===W.CALLED)?(d.log("Push rejected (busy)"),S.log(R.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(O.BUSY),Promise.reject({hangup:O.BUSY})):(H._current&&(H._current.destroy(),H._current=null),yield this._setConversation(_,v,Je.INCOMING,t),v)})}_createParticipant(e){return c(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:me(),participantState:{},state:W.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[],isInRoom:!1},e);if(e.externalId){let a=I.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(a,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return(i=t.observedIds)!=null&&i.length&&(t.externalId.observer=!0),this._setParticipantMarkers(t,t.markers),t})}_getParticipantId(e){return c(this,null,function*(){try{let t=I.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new V(O.NETWORK_ERROR),t),t}})}_setConversation(n,o,p){return c(this,arguments,function*(e,t,i,a=z.USER){yield this._prepareParticipants(t.conversation.participants);let u=this._api.getUserId(),_=e.device_idx||0;if(!u){let k=(t.conversation.participants||[]).find(D=>I.comparePeerId(D.peerId,t.peerId));if(!k)throw new V(O.UNKNOWN_ERROR);u=Number(k.id),k.idType&&(a=k.idType),k.deviceIdx&&(_=k.deviceIdx),this._api.setUserId(u)}let v=I.composeParticipantId(u,a,_),b=yield this._getParticipantId(v);this._conversation={userId:u,compositeUserId:v,externalId:b,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||"DIRECT",direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordsInfoByRoom:new Map,muteStates:new Map,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1,asrInfo:null,roomId:null},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(l.forceRelayPolicy=e.p2p_forbidden),S.log(R.RELAY_POLICY,l.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new V(O.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||"DIRECT",this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new oi;return this.subscribe(e,"SOURCE_CHANGED",this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,"SCREEN_STATUS",this._onScreenSharingStatus.bind(this)),this._audioFix=new Dt(e),e}_connectSignaling(e,t){return c(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,Se.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,Se.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,Se.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_processConnection(e){return c(this,null,function*(){yield this._registerConnectionParticipants(e),this._processConnectionData(e)})}_prepareParticipants(e){return c(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 Re(Re({},{participants:[],countBefore:0,countAfter:0,markerFound:!1}),e)}_participantListChunkToExternalChunk(e){let t=I.mapSharedParticipants(e.participants.map(i=>{let a=I.composeId(i);return this._participants[a]}));return qe(Re({},e),{participants:t})}_registerConnectionParticipants(e){return c(this,null,function*(){var i,a,n,o,p,u;yield this._registerParticipants(e.conversation.participants),(i=e.participants)!=null&&i.participants&&(yield this._registerParticipants((a=e.participants)==null?void 0:a.participants));let t=(o=(n=e==null?void 0:e.rooms)==null?void 0:n.rooms)!=null?o:[];for(let _ of t)yield this._registerParticipants((u=(p=_==null?void 0:_.participants)==null?void 0:p.participants)!=null?u:[],!0)})}_registerParticipants(e,t=!1){return c(this,null,function*(){if(this._conversation)for(let i of e){let a=I.composeId(i);if(this._isMe(a)){this._conversation.roles=i.roles||[],this._conversation.roles.length&&(d.debug(`Local roles changed: ${i.roles}`),g.onLocalRolesChanged(this._conversation.roles)),yield this._registerParticipantLocalMuteState(i);continue}if(i.state===W.HUNGUP||i.state===W.REJECTED){this._participants[i.id]&&this._removeParticipant(this._participants[i.id],O.HUNGUP);continue}this._registerParticipantInCache(yield this._createParticipant({id:a,externalId:i.externalId&&le.fromSignaling(i.externalId,i.deviceIdx||0),mediaSettings:me(i.mediaSettings),participantState:I.mapParticipantState(i),state:i.state,roles:i.roles||[],status:l.batchParticipantsOnStart?"WAITING":null,muteStates:i.muteStates||{},unmuteOptions:i.unmuteOptions||[],observedIds:i.observedIds||[],markers:this._denormalizeMarkers(a,i.markers),movieShareInfos:i.movieShareInfos,isInRoom:t})),i.roles&&i.roles.length&&(d.debug(`Roles for participant [${a}] changed: ${i.roles}`),g.onRolesChanged(this._participants[a].externalId,i.roles))}})}_registerParticipantLocalMuteState(e){return c(this,null,function*(){if(!e.muteStates)return Promise.resolve();let t=At(e.muteStates,ke.MUTE),i=At(e.muteStates,ke.MUTE_PERMANENT);for(let a of[t,i])a.length&&(yield this._onMuteParticipant({muteStates:e.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:a,stateUpdated:!0}))})}_getStatusByTransportState(e){let t;return e==="CONNECTED"?t="CONNECTED":e==="CONNECTING"||e==="OPENED"?t="CONNECTING":e==="RECONNECTING"&&(t="RECONNECT"),t}_registerParticipantInCache(e){return this._participants[e.id]=e}_getExistedParticipantByIdOrCreate(e){return c(this,null,function*(){return this._participants[e]||this._createParticipant({id:e})})}_getExternalIdByParticipantId(e){return c(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&&t.externalId)return this._participants[e].externalId;{let i=yield this._getParticipantId(e);return this._api.cacheExternalId(e,i),i}})}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){return c(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){d.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(a=>"ts"in a&&"rank"in a);return Object.entries(t).reduce((a,[n,o])=>(a[n]=qe(Re(Re({},i),o),{id:e}),a),{})}_processConnectionData(e){return c(this,null,function*(){this._processRooms(e),this._processMuteStates(e),e.conversation.pinnedParticipantId&&(yield this._onPinParticipant(e.conversation.pinnedParticipantId)),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Ni.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)})}_processRooms(e){var i,a;let t=(a=(i=e.rooms)==null?void 0:i.roomId)!=null?a:null;this._onRoomSwitched(t,!0)}_processMuteStates(e){var i,a,n;this._setMuteStatesForRoomId((i=e.conversation)==null?void 0:i.muteStates,null);for(let o of(n=(a=e.rooms)==null?void 0:a.rooms)!=null?n:[])this._setMuteStatesForRoomId(o.muteStates,o.id);let t=this._getMuteStatesForCurrentRoom();this._onMuteParticipant({muteStates:t,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(t),muteAll:!0,stateUpdated:!0,roomId:this._conversation.roomId})}_processRecordInfos(e){var t,i,a,n;this._onRecordInfo((t=e.conversation.recordInfo)!=null?t:null);for(let o of(a=(i=e.rooms)==null?void 0:i.rooms)!=null?a:[])this._onRecordInfo((n=o.recordInfo)!=null?n:null,o.id)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Ri(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new qt,this.subscribe(this._transport,"STATE_CHANGED",this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,"LOCAL_STATE_CHANGED",this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,"REMOTE_TRACK_ADDED",this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,"REMOTE_TRACK_REMOVED",this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,"REMOTE_ALL_STALL",this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,"REMOTE_DATA_STATS",this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,"SIGNALLED_STALLED_PARTICIPANTS",this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,"TOPOLOGY_CHANGED",this._onTopologyChanged.bind(this)),this.subscribe(this._transport,"NETWORK_STATUS",this._onNetworkStatus.bind(this)),this.subscribe(this._transport,"REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,"PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this)),this.subscribe(this._transport,"ASR_TRANSCRIPTION",this._onAsrTranscription.bind(this)),this.subscribe(this._transport,"ANIMOJI_STREAM",this._onAnimojiStream.bind(this));let e=this._conversation.direction===Je.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===W.ACCEPTED||t.state===W.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new Ci(this._transport),this.subscribe(this._volumesDetector,"VOLUMES_DETECTED",this._onVolumesDetected.bind(this)),this._speakerDetector=new yi(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,"SPEAKER_CHANGED",this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Jt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Yt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=y.getCameras().length,t=y.getMicrophones().length;d.debug("Cameras: "+e+(y.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(y.hasMicrophonePermission()?"✔":"✖")),S.log(R.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){S.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===W.CALLED||e.state===W.ACCEPTED||this._state==="CLOSE"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),this._participants[e.id]&&(t===O.HUNGUP?this._setParticipantsStatus([e],"HANGUP"):this._setParticipantsStatus([e],"ERROR",t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:"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,a;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(a=e.mediaSource)==null||a.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){d.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return c(this,null,function*(){d.debug(`Add new participant [${e}]`);let a=this._participants[e];if(a&&(a.state===W.ACCEPTED||a.state===W.CALLED)){d.warn(`Participant [${a.id}:${a.state}] is already in conversation`);return}a||(a=this._registerParticipantInCache(yield this._createParticipant({id:e,externalId:t.externalId&&le.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:me(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}))),this._setParticipantsStatus([a],"WAITING"),i?(a.state=W.HUNGUP,this._removeParticipant(a,i)):this._transport&&(a.state=W.CALLED,this._transport.allocate(a.id,!0),S.log(R.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(a))})}_onRemoveParticipant(e){d.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=Wn;i++){let a=I.compose(e,i),n=this._participants[a];n&&t.push(n)}if(!t.length){this._warnParticipantNotInConversation(e);return}if(this._transport)for(let i of t)this._transport.close(i.id);S.log(R.REMOVE_PARTICIPANT)}changeDevice(e){return c(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new Dt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(re.UNKNOWN)})}stopVideoTrack(){return c(this,null,function*(){return this._mediaSource.stopVideoTrack()})}toggleScreenCapturing(e){return c(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(re.UNKNOWN)})}disableScreenCapturing(){return c(this,null,function*(){return this._mediaSource?this._mediaSource.disableScreenCapturing():Promise.reject(re.UNKNOWN)})}toggleAnimojiCapturing(e){this._mediaSource&&this._mediaSource.toggleAnimojiCapturing(e)}setAnimojiSvg(e,t=null,i=null){if(!this._transport)return;let a=!t,n=t!=null?t:this._conversation.compositeUserId;if(e instanceof ArrayBuffer){let o=i!=null?i:this._conversation.externalId.id;this._transport.setAnimojiSvg(n,{svg:e,userId:o,isMe:a});return}this._transport.setAnimojiSvg(n,{svg:e,isMe:a})}setVideoStream(e,t=!1){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return c(this,null,function*(){if(this._mediaSource)return S.log(R.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return c(this,null,function*(){if(this._mediaSource)return S.log(R.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return c(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let a of e){let n=typeof a.uid=="object"?a.uid:le.fromId(a.uid),o=le.toString(n);i[o]=a.priority}for(let a of Object.values(this._participants)){let n=le.toString(a.externalId);i.hasOwnProperty(n)&&(t[a.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return c(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return c(this,null,function*(){let t={};return t[Fe(e)]={keyFrameRequested:!0},this._signaling.updateDisplayLayout(t)})}requestTestMode(e,t){return c(this,null,function*(){return this._signaling.requestTestMode(e,t)})}updateDisplayLayout(e){return c(this,null,function*(){if(e.length<1||!this._signaling.ready)return;d.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let a of e){let n=typeof a.uid=="object"?a.uid:le.fromId(a.uid),o=this._api.getCachedOkIdByExternalId(n);if(!o){let v=le.toString(n);d.log(`Unknown participant external ID ${v}`);continue}let p=I.compose(o,n.deviceIdx),u=Fe({participantId:p,mediaType:a.mediaType,streamName:a.streamName}),_=this._participants[p];_?_.lastRequestedLayouts[u]=a:this._isMe(p)&&(this._myLastRequestedLayouts[u]=a),Gt(a)?(this._isMe(p)&&delete this._myLastRequestedLayouts[u],this._streamIdByStreamDescription.has(u)&&!this._cooldownTimestampByStreamDescription.has(u)&&this._cooldownTimestampByStreamDescription.set(u,Date.now())):(this._cooldownTimestampByStreamDescription.delete(u),!this._streamIdByStreamDescription.has(u)&&l.videoTracksCount>0&&this._streamIdByStreamDescription.set(u,null),t[u]=a)}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>l.videoTracksCount;){let a=i.next();if(a.done){d.error("Cannot accommodate all streaming requests: tracks available "+l.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(a.value),t[a.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)&&(d.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=Kt(e),a=this._participants[i.participantId],{externalId:n}=this._conversation,o=this._isMe(i.participantId);if(a){if(i.streamName&&(i.mediaType==="STREAM"||i.mediaType==="MOVIE")){let p={stream:null,streamName:i.streamName,mediaType:i.mediaType};o?g.onLocalLive(n,p):g.onRemoteLive(a.externalId,p)}else o||g.onRemoteStream(a.externalId,null);S.log(R.PAT_DEALLOCATED)}else d.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return c(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[a,n]of Object.entries(t.errorCodeByParticipantId||{})){let o=Kt(a),p=this._participants[o.participantId];if(p){let u;typeof n!="number"?(d.warn(`Unexpected error code ${n} received for participant ${o.participantId}`),u=Wr.UNKNOWN_ERROR):u=Kr(n),i.push({externalId:p.externalId,errorReason:u})}}if(i&&i.length)throw new Qt("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 a=i.value;if(a[1]+Gn>Date.now())break;let o=a[0];this._stopStreaming(o),e[o]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e)}_onParticipantSourcesUpdate(e){if(this._conversation){d.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return c(this,null,function*(){d.log("Promoted in waiting hall",!e.demote),e.demote?(d.log("Kicked from waiting hall"),this._close(new V(O.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(a){return c(this,arguments,function*(e,t=0,i=[]){d.log(`Chat room updated: ${e}`);let n=[],o=[];i.length&&(i.forEach(p=>{if(p.externalId){let u=ge.fromSignaling(p.externalId);n.push(u),this._api.cacheExternalId(p.id.id,u)}else o.push(I.decomposeId(p.id.id).id)}),o.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(o))),g.onChatRoomUpdated(e,t,n)})}_onSharedMovieUpdate(e){return c(this,null,function*(){let{externalId:t}=this._conversation,{data:i}=e;for(let a of i)if(this._isMe(a.participantId))g.onLocalLiveUpdate(t,a);else{let o=yield this._getExternalIdByParticipantId(a.participantId);o&&g.onRemoteLiveUpdate(o,a)}})}_onSharedMovieInfoStarted(e){return c(this,null,function*(){d.log(`Shared movie started data received: ${e.notification}`),yield this._processSharedMovieInfo(e.movieShareInfo)})}_processSharedMovieInfos(e){return c(this,null,function*(){e&&(yield Promise.all(e.map(t=>this._processSharedMovieInfo(t))))})}_processSharedMovieInfo(e){return c(this,null,function*(){var a;if(!e)return;let{externalId:t}=this._conversation;if(this._isMe(e.initiatorId))g.onLocalSharedMovieInfo(t,e);else{let n=yield this._getExternalIdByParticipantId(e.initiatorId);n&&g.onRemoteSharedMovieInfo(n,e)}this._transport.getTopology()==="SERVER"&&this._transport.getState()==="IDLE"&&this._participantState!==W.CALLED&&this._transport.open(this._transport.allocated(),null,!!((a=this._conversation)!=null&&a.observer),!0)})}_processConnectionSharedMovieInfo(e){return c(this,null,function*(){let t=e.conversation.participants.find(i=>this._isMe(I.composeId(i)));yield this._processSharedMovieInfos(t==null?void 0:t.movieShareInfos)})}_onSharedMovieInfoStopped(e){return c(this,null,function*(){d.log(`Shared movie stopped data received: ${e.notification}`);let{externalId:t}=this._conversation,{initiatorId:i,movieId:a,source:n}=e,o={initiatorId:i,movieId:a,source:n};if(this._isMe(i))g.onLocalSharedMovieStoppedInfo(t,o);else{let u=yield this._getExternalIdByParticipantId(i);u&&g.onRemoteSharedMovieStoppedInfo(u,o)}})}_onFeaturesPerRoleChanged(e){d.log(`Features per role changed: ${e.notification}`),g.onFeaturesPerRoleChanged(e.featuresPerRole)}_waitForStreamIfNeeded(e){var p,u;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||l.producerScreenDataChannel&&t.mediaType==="SCREEN"||t.mediaType==="ANIMOJI")return;let i=Fe(t),a=this._sequenceNumberByStreamDescription.get(i);if(a&&a>e.sequenceNumber){d.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${a}`),S.log(R.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,o=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(o<=0){this._streamWaitTimerByStreamDescription.delete(i);let _=t.participantId,v=this._participants[_],{externalId:b}=this._conversation,k=this._isMe(_);if(!v&&!k){S.log(R.PAT_ERROR,"participantMissing"),d.error(`Could not find participant by ID: ${_}`);return}let D=k?b:v.externalId,$=this._streamByStreamId.get(n);if(!$){S.log(R.PAT_ERROR,"streamNotFound"),d.error(`Could not find stream by ID: ${n}`);return}S.log(R.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let j=(p=e.participantStreamDescription)==null?void 0:p.mediaType;if(j==="STREAM"||j==="MOVIE"){if((u=e.participantStreamDescription)!=null&&u.streamName){let he={streamName:e.participantStreamDescription.streamName,stream:$,mediaType:j};k?g.onLocalLive(D,he):g.onRemoteLive(D,he)}}else if(l.producerScreenTrack&&j==="SCREEN")g.onRemoteScreenStream(v.externalId,$);else if(!k){let he=(l.producerScreenTrack?null:v.secondStream)||$;g.onRemoteStream(v.externalId,he)}}else{d.debug(`Waiting for ${o} until stream ${n} for ${i} is switched`);let _=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),o);this._streamWaitTimerByStreamDescription.set(i,_)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Fe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Fe(i)))return i}else{let i={participantId:t,mediaType:"CAMERA"};if(this._streamIdByStreamDescription.has(Fe(i)))return i;let a={participantId:t,mediaType:"SCREEN"};if(this._streamIdByStreamDescription.has(Fe(a)))return a}return d.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?I.includesOneOf(this._conversation.roles,[ze.ADMIN,ze.CREATOR]):!1}_checkAdminRole(){if(this._conversation&&!I.includesOneOf(this._conversation.roles,[ze.ADMIN,ze.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}startAsr(){return c(this,null,function*(){yield this._signaling.startAsr()})}stopAsr(){return c(this,null,function*(){yield this._signaling.stopAsr()})}requestAsr(e){return c(this,null,function*(){yield this._signaling.requestAsr(e)})}muteParticipant(){return c(this,arguments,function*(e=null,t,i=[],a=null){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i,a)})}enableFeatureForRoles(e,t){return c(this,null,function*(){yield this._signaling.enableFeatureForRoles(e,t)})}pinParticipant(e,t){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return c(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return c(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=kr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return c(this,null,function*(){if(!this._signaling)return Promise.reject();let a=null;e&&(a=Ea(e));let n=yield this._signaling.getWaitingHall(a,t,i);if(n.error)return Promise.reject(n.message);let o=n.participants||[],p=[],u=[],_=null;return o.length&&(o.forEach(v=>{if(v.externalId){let b=ge.fromSignaling(v.externalId);p.push(b),this._api.cacheExternalId(v.id.id,b)}else u.push(I.decomposeId(v.id.id).id)}),u.length&&!p.length&&(p=yield this._api.getExternalIdsByOkIds(u)),n.hasMore&&(_=va(o[o.length-1].id))),{participants:p,pageMarker:_,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return c(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return c(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let a=t.messages[i];yield this._onChatMessage(a)}}})}customData(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return c(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return c(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(a){return c(this,arguments,function*({movieId:e,gain:t,metadata:i}){let n={movieId:e};(t||t===0)&&(n.gain=t),i&&(n.metadata=i);let o=yield this._signaling.addMovie(n);if(o.error)throw new Error(o.error);return{movieId:o.movieId,streamType:o.streamType}})}updateMovie(e){return c(this,null,function*(){let t=yield this._signaling.updateMovie(e);if(t.error)throw new Error(t.error)})}removeMovie(e){return c(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 c(this,null,function*(){let i=yield this._signaling.updateRooms(e,t);if(i.error)throw new Error(i.error)})}activateRooms(e,t){return c(this,null,function*(){let i=yield this._signaling.activateRooms(e,t);if(i.error)throw new Error(i.error)})}switchRoom(e,t){return c(this,null,function*(){let i=yield this._signaling.switchRoom(e,t);if(i.error)throw new Error(i.error)})}removeRooms(e){return c(this,null,function*(){let t=yield this._signaling.removeRooms(e);if(t.error)throw new Error(t.error)})}startStream(e=!1,t=null,i=null,a="DIRECT_LINK",n=null,o=null){return c(this,null,function*(){let p={movieId:i,name:t,privacy:a,groupId:n,roomId:o,streamMovie:!e},u=yield this._signaling.startStream(p);return u.error?Promise.reject(u.message):u})}stopStream(e=null){return c(this,null,function*(){let t=yield this._signaling.stopStream({roomId:e});return t.error?Promise.reject():t})}recordSetRole(e,t,i=null){return c(this,null,function*(){let a=yield this._signaling.recordSetRole(e,t,i);if(a.error)throw new Error(a.error)})}getStreamInfo(){return c(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return c(this,null,function*(){var a;if(e<l.videoMinWidth||t<l.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i!=null&&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,(a=this._mediaSource)==null?void 0:a.setResolution(e,t)})}videoEffect(e){return c(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}getParticipants(e){return c(this,null,function*(){let t=e.externalIds.map(o=>({id:o.id,type:l.externalUserType})),i=yield this._signaling.getParticipants(t);if(i.error)throw new Error(i.error);let a=i.participants,n=this._transport.getState();return Promise.all(a.map(o=>c(this,null,function*(){var u;let p=I.composeId(o);return this._createParticipant({id:p,externalId:o.externalId&&le.fromSignaling(o.externalId,o.deviceIdx||0),mediaSettings:me(o.mediaSettings),participantState:I.mapParticipantState(o),state:o.state,roles:o.roles||[],status:(u=this._getStatusByTransportState(n))!=null?u:"WAITING",muteStates:o.muteStates||{},unmuteOptions:o.unmuteOptions||[],observedIds:o.observedIds||[],markers:this._denormalizeMarkers(p,o.markers)})}))).then(I.mapSharedParticipants)})}getParticipantListChunk(e){return c(this,null,function*(){var p;d.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),a=i.participants.filter(u=>{let _=I.composeId(u);return!this._participants[_]});yield this._registerParticipants(a);let n=(p=this._transport)==null?void 0:p.getState();return i.participants.forEach(u=>{var b,k;let _=I.composeId(u),v=this._participants[_];v.status=(b=this._getStatusByTransportState(n))!=null?b:"WAITING",v.movieShareInfos=u.movieShareInfos,Object.assign(v.mediaSettings,me(u.mediaSettings)),Object.assign(v.muteStates,u.muteStates),v.unmuteOptions=(k=u.unmuteOptions)!=null?k:v.unmuteOptions,this._openTransport([v],!0)}),this._participantListChunkToExternalChunk(i)})}_getInitialParticiapntListChunk(){return c(this,null,function*(){let e=l.participantListChunkInitIndex,t=l.participantListChunkInitCount,i="GRID",a=yield this._signaling.getParticipantListChunk({listType:i,fromIdx:e,count:t});return d.debug("Get initial participant list chunk",a.chunk),a.chunk})}_onLocalMediaStreamChanged(e){return c(this,null,function*(){var t,i;this._conversation&&(d.debug("Local media stream changed",e.mediaSettings),g.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)!=null&&t.waitingHall)&&!((i=this._conversation)!=null&&i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return c(this,null,function*(){var t,i;if(d.log("Screen sharing changed",e.track,e.mediaSettings),l.consumerScreenTrack){let a=e.track?new MediaStream([e.track]):null;g.onScreenStream(a,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)!=null&&t.waitingHall)&&!((i=this._conversation)!=null&&i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){d.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){d.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&&(d.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),g.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case w.ACCEPTED_CALL:return this._onAcceptedCall(e);case w.HUNGUP:return this._onHungup(e);case w.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case w.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case w.CLOSED_CONVERSATION:return this._onClosedConversation(e);case w.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case w.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case w.RATE_CALL_DATA:return this._onNeedRate();case w.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case w.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case w.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case w.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case w.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case w.REGISTERED_PEER:return this._onPeerRegistered(e);case w.SWITCH_MICRO:return this._onMicSwitched(e);case w.CHAT_MESSAGE:return this._onChatMessage(e);case w.CUSTOM_DATA:return this._onCustomData(e);case w.RECORD_STARTED:return this._onRecordInfo(e.recordInfo,e.roomId);case w.RECORD_STOPPED:return this._onRecordInfo(null,e.roomId);case w.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case w.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case w.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin,e.markers);case w.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case w.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case w.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case w.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants);case w.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e);case w.FEEDBACK:return this._onFeedback(e);case w.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e);case w.MOVIE_SHARE_STARTED:return this._onSharedMovieInfoStarted(e);case w.MOVIE_SHARE_STOPPED:return this._onSharedMovieInfoStopped(e);case w.ROOMS_UPDATED:return this._onRoomsUpdated(e);case w.ROOM_UPDATED:return this._onRoomUpdated(e);case w.ROOM_PARTICIPANTS_UPDATED:return this._onRoomParticipantsUpdated(e);case w.FEATURES_PER_ROLE_CHANGED:return this._onFeaturesPerRoleChanged(e);case w.ASR_STARTED:return this._onAsrInfo(e.asrInfo);case w.ASR_STOPPED:return this._onAsrInfo(null)}}_onSignalingReconnect(e){return c(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._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),a=[];for(let n of e.conversation.participants){let o=I.composeId(n),p=n.roles||[];if(this._isMe(o)){t=me(n.mediaSettings),Bt(this._conversation.roles,p)||this._onRolesChanged(o,p);continue}a.push(o);let u=this._participants[o];if(!u)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let _=me(n.mediaSettings);ia(_,u.mediaSettings)||this._changeRemoteMediaSettings(o,_);let v=I.mapParticipantState(n),b=u.participantState;I.isEqualParticipantState(v,b)||this._changeRemoteParticipantState(o,v),Bt(p,u.roles)||this._onRolesChanged(u.id,p)}}for(let n of i)a.indexOf(n)<0&&this._removeParticipant(this._participants[n],O.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){d.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return c(this,null,function*(){let t=I.composeMessageId(e),i=I.getPeerIdString(e.peerId);if(d.debug(`Participant accepted call [${t}]`),this._conversation&&this._isMe(t)){this._close(new V(O.MISSED),"Call accepted on other device");return}let a=this._participants[t];a||(a=this._registerParticipantInCache(yield this._createParticipant({id:t,mediaSettings:me(e.mediaSettings)}))),a.state=W.ACCEPTED,a.mediaSettings=me(e.mediaSettings),this._logWithMediaSettings(R.ACCEPTED_OUTGOING,a.mediaSettings),this._conversation&&this._conversation.direction===Je.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([a.id],i),this._changeRemoteMediaSettings(t,a.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){return c(this,null,function*(){d.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=I.composeMessageId(e);if(this._conversation&&this._isMe(t)){this._close(new V(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===O.REJECTED?W.REJECTED:W.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,O.HUNGUP)})}_onAddedParticipant(e){return c(this,null,function*(){var a,n;d.debug(`Participant added [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state!==W.HUNGUP&&i.state!==W.REJECTED){d.debug(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&le.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:me(e.participant.mediaSettings),state:e.participant.state,participantState:I.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}))),i.state=W.CALLED,i.mediaSettings=me((a=e.participant)==null?void 0:a.mediaSettings),i.participantState=I.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],"WAITING"),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),g.onParticipantAdded(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return c(this,null,function*(){var a,n;d.debug(`Participant joined [${e.participantId}]`);let t=I.composeMessageId(e),i=this._participants[t];if(i&&i.state===W.ACCEPTED){d.warn(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&le.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:me(e.participant.mediaSettings),state:e.participant.state,participantState:I.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===Je.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=W.ACCEPTED,i.mediaSettings=me(e.mediaSettings),i.participantState=I.mapParticipantState(e.participant),i.roles=e.participant.roles||[],(a=this._transport)!=null&&a.isAllocated(i.id)?this._setParticipantsStatus([i],"CONNECTED"):this._setParticipantsStatus([i],"WAITING"),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((n=this._conversation)!=null&&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),yield this._processSharedMovieInfos(i.movieShareInfos)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new V(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){return c(this,null,function*(){let t=I.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,me(e.mediaSettings))})}_onParticipantStateChanged(e){return c(this,null,function*(){let t=I.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteParticipantState(t,I.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 c(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=me(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),l.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing({captureScreen:i.isScreenSharingEnabled,fastScreenSharing:i.isFastScreenSharingEnabled,captureAudio:i.isAudioSharingEnabled}))})}_onSettingsUpdate(e){d.debug("Got settings update notification",e);let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=ur(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){d.debug("Got video quality update notification",e);let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,a={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=ur(this._serverSettings,a),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=I.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return c(this,null,function*(){g.onDeviceSwitched(de.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return c(this,null,function*(){let t=I.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 c(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=I.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,t=null){return c(this,null,function*(){var n;if(!this._conversation)return;let i=this._conversation.recordsInfoByRoom.get(t),a=!1;if(!i!=!e?a=!0:i&&e&&(a=i.recordMovieId!==e.recordMovieId),a)if(this._conversation.recordsInfoByRoom.set(t,e),e){let o=yield this._getParticipantId(e.initiator);g.onRecordStarted(o,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId,t)}else g.onRecordStopped(t);e&&this._transport.getTopology()==="SERVER"&&this._participantState!==W.CALLED&&this._transport.open(this._transport.allocated(),null,!!((n=this._conversation)!=null&&n.observer),!0)})}_changeRecordInfoForRoom(){return c(this,null,function*(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.recordsInfoByRoom.get(e);if(t){let i=yield this._getParticipantId(t.initiator);g.onRecordStarted(i,t.recordMovieId,t.recordStartTime,t.recordType,t.recordExternalMovieId,t.recordExternalOwnerId,e)}else g.onRecordStopped(e)})}_onAsrInfo(e){return c(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})}_onAsrTranscription(e){return c(this,null,function*(){if(!this._conversation)return;let t=yield this._getParticipantId(e.participantId);g.onAsrTranscription(t,e.text,e.timestamp,e.duration)})}_onRolesChanged(e,t){if(this._conversation&&this._isMe(e)&&!Bt(this._conversation.roles,t)){d.debug(`Local roles changed: ${t}`),this._conversation.roles=t,g.onLocalRolesChanged(t),this._processMuteState({mediaOptions:At(this._getMuteStatesForCurrentRoom(),ke.MUTE_PERMANENT),stateUpdated:!0}),I.includesOneOf(t,[ze.ADMIN,ze.CREATOR])&&this._refreshRooms(!0);return}let i=this._participants[e];i&&!Bt(i.roles,t)&&(d.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,g.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return c(this,null,function*(){var _;if(!this._conversation)return;let i=(_=e.roomId)!=null?_:null,a=e.muteStates||{},n=e.unmuteOptions||[],o=e.mediaOptions||[],p=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&!this._isMe(e.participantId)){if(!this._isCallAdmin()){d.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let v=this._participants[e.participantId];v&&(d.debug(`Mute states for participant [${e.participantId}] changed`,a),g.onMuteStates(a,n,o,e.muteAll,e.unmute,v.externalId,p==null?void 0:p.externalId,e.stateUpdated,e.requestedMedia,e.roomId));return}let u=this._getMuteStatesForRoomId(i);if(!(I.isObjectsEquals(u,a)&&I.isArraysEquals(this._conversation.unmuteOptions,n)&&!o.length)){if(this._setMuteStatesForRoomId(a,i),this._conversation.unmuteOptions=n,this._isMe(e.adminId)){e.muteAll&&g.onMuteStates(a,n,o,e.muteAll,e.unmute,null,this._conversation.externalId,e.stateUpdated,e.requestedMedia,e.roomId);return}yield this._processMuteState({mediaOptions:o,muteAll:e.muteAll,unmute:e.unmute,serverSettings:t,admin:p,stateUpdated:e.stateUpdated,requestedMedia:e.requestedMedia,roomId:e.roomId})}})}_changeMuteStatesForRoom(e,t){if(!this._conversation)return;this._conversation.unmuteOptions=[];let i=this._getMuteStatesForRoomId(t),a=this._getMuteStatesForRoomId(e),n=Object.keys(i),o=Object.keys(a);this._processMuteState({mediaOptions:Array.from(new Set([...n,...o])),roomId:e,muteAll:!0,stateUpdated:!0})}_processMuteState(_){return c(this,arguments,function*({mediaOptions:e=[],muteAll:t=!1,unmute:i=!1,serverSettings:a=null,admin:n=null,stateUpdated:o,requestedMedia:p,roomId:u=null}){if(!this._conversation||!this._mediaSource||this._participantState!==W.ACCEPTED)return;let v=Object.assign({},this._getMuteStatesForRoomId(u)),b=this._conversation.unmuteOptions,k=this._mediaSource.getMediaSettings(),D=Object.entries(v);for(let[$,j]of D)if(!(j!==ke.MUTE&&j!==ke.MUTE_PERMANENT)&&(this._isCallAdmin()&&j===ke.MUTE_PERMANENT&&!t&&(v[$]=ke.MUTE),!(!e.includes($)||i)))switch($){case de.VIDEO:k.isVideoEnabled&&!(a!=null&&a.isVideoEnabled)&&(g.onDeviceSwitched(de.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case de.AUDIO:k.isAudioEnabled&&!(a!=null&&a.isAudioEnabled)&&(g.onDeviceSwitched(de.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case de.SCREEN_SHARING:k.isScreenSharingEnabled&&!(a!=null&&a.isScreenSharingEnabled)&&(g.onDeviceSwitched(de.SCREEN_SHARING,!1),yield this.disableScreenCapturing());break;case de.AUDIO_SHARING:k.isAudioSharingEnabled&&!(a!=null&&a.isAudioSharingEnabled)&&(g.onDeviceSwitched(de.AUDIO_SHARING,!1),yield this.toggleScreenCapturing({captureScreen:k.isScreenSharingEnabled,fastScreenSharing:k.isFastScreenSharingEnabled,captureAudio:!1}));break}g.onMuteStates(v,b,e,t,i,null,n==null?void 0:n.externalId,o,p,u)})}_onPinParticipant(e,t=!1,i){return c(this,null,function*(){if(!this._conversation)return;let a=this._conversation.pinnedParticipantId;if(a&&a!==e)if(this._isMe(a))g.onLocalPin(!0);else{let n=yield this._getExternalIdByParticipantId(a);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&&!Dr(this._conversation.options,e)&&(this._conversation.options=e,g.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,a]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!==a)if(this._isMe(i)||i==="")this._conversation.networkRating=a,g.onLocalNetworkStatusChanged(a);else{let o=this._participants[i];o.networkRating=a,t.push({uid:o.externalId,rating:a})}}if(t.length===0)return;d.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 a=e;if(!this._streamIdByStreamDescription.has(a)){d.error("Received remote stream notification for a participant that has no track associated with it",a);return}let n=this._streamIdByStreamDescription.get(a);if(!n||this._streamWaitTimerByStreamDescription.has(a)){d.log("Delaying secondary stream start/stop until main stream becomes available",a);return}let o=this._streamByStreamId.get(n);if(!o){S.log(R.PAT_ERROR,"streamNotFound"),d.error(`Could not find stream by ID: ${n}`);return}g.onRemoteStream(i.externalId,i.secondStream||o)}else{let a=t||i.remoteStream;a&&g.onRemoteStream(i.externalId,a)}}}_onAnimojiStream(e,t){if(this._isMe(e)){g.onVmojiStream(t,this._mediaSource.getMediaSettings());return}let i=this._participants[e];i&&g.onRemoteVmojiStream(i.externalId,t)}_onPeerConnectionClosed(e){e==="SERVER"&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Ui.ADD_PARTICIPANT);g.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&g.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,a]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:a.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 c(this,null,function*(){d.debug(`Transport state has changed: ${t}`,e);let i=this._getStatusByTransportState(t);if(!i)return;let a=e.reduce((n,o)=>{if(o in this._participants){let p=this._participants[o];n.push(p),t==="CONNECTED"&&(p.remoteStream||(p.mediaSettings&&this._changeRemoteMediaSettings(o,p.mediaSettings),this._changeRemoteParticipantState(o,p.participantState)),this._updateDisplayLayoutFromCache(o))}else this._warnParticipantNotInConversation(o);return n},[]);a.length&&this._setParticipantsStatus(a,i)})}_onTransportLocalStateChanged(e){return c(this,null,function*(){var t;if(d.debug(`Local transport state has changed: ${e}`),e==="CONNECTED"&&(g.onLocalStatus("CONNECTED"),((t=this._transport)==null?void 0:t.getTopology())==="SERVER")){let i=Object.values(this._myLastRequestedLayouts);yield this.updateDisplayLayout(i)}e==="CONNECTING"&&g.onLocalStatus("CONNECTING"),e==="RECONNECTING"&&g.onLocalStatus("RECONNECT"),e==="FAILED"&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(O.FAILED)),this._close(new V(O.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return c(this,null,function*(){if(e.endsWith(Oe.AUDIO_MIX))d.debug("Remote audio mix track added"),this._audioOutput.add(i),g.onRemoteMixedAudioStream(t);else if(e.startsWith(Oe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))d.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{d.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let a=this._participants[e];if(a||(d.warn(`Conversation: track added before participant [${e}]`),a=this._registerParticipantInCache(yield this._createParticipant({id:e})),this._setParticipantsStatus([a],"WAITING"),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(a.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(a.id)&&this._transport.allocate(a.id,!1),i.kind==="audio"&&(this._audioOutput.add(i),l.preserveAudioTracks||t.removeTrack(i)),a.remoteStream!==t){if(a.remoteStream=t,a.secondStream)return;g.onRemoteStream(a.externalId,t)}a.mediaSettings&&this._changeRemoteMediaSettings(e,a.mediaSettings),l.batchParticipantsOnStart||this._changeRemoteParticipantState(e,a.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(d.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case"audio":this._removeAudioTrack(e,t,i);break;case"video":case"screen":this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Oe.AUDIO_MIX){let a=this._participants[e];if(!a||a.remoteStream&&a.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e==="DIRECT"&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let a in this._participants)if(this._participants.hasOwnProperty(a)){let n=this._participants[a];e||this._lastStalled[a]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,"RECONNECT"),i.length&&this._setParticipantsStatus(i,"CONNECTED")}_onRemoteSignalledStall(e){let t={},i=[],a=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let o=this._participants[n];o&&!this._remoteAllStalled&&i.push(o)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let o=this._participants[n];o&&!this._remoteAllStalled&&a.push(o)}),i.length&&this._setParticipantsStatus(i,"RECONNECT"),a.length&&this._setParticipantsStatus(a,"CONNECTED"),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!y.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)!=null&&t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(d.debug("Toggle join availability",{available:t,chatId:e}),g.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return c(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!=="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 a=e.reduce((n,o)=>(o.status!==t&&(o.status=t,l.batchParticipantsOnStart?n.push(o.externalId):g.onParticipantStatus(o.externalId,t,i)),n),[]);a.length&&l.batchParticipantsOnStart&&g.onRemoteStatus(a,t,i)}_onJoinLinkChanged(e){g.onJoinLinkChanged(e.joinLink)}_onRoomsUpdated(e){return c(this,null,function*(){var i,a;let t={};for(let n of Object.keys(Ut)){let o=e.updates[n];o&&(t[n]={rooms:yield Promise.all(((a=(i=o==null?void 0:o.rooms)==null?void 0:i.map)==null?void 0:a.call(i,this._convertRoomToExternal.bind(this)))||[]),roomIds:o==null?void 0:o.roomIds,deactivated:o==null?void 0:o.deactivated})}g.onRoomsUpdated(t)})}_onRoomUpdated(e){return c(this,null,function*(){let t=yield this._convertRoomToExternal(e.room);e.events.some(i=>i===Ut.UPDATE)&&(e.muteStates!==void 0&&this._setMuteStatesForRoomId(e.muteStates,e.roomId),e.recordInfo!==void 0&&this._conversation.recordsInfoByRoom.set(e.roomId,e.recordInfo)),g.onRoomUpdated(e.events,e.roomId,t,e.deactivate)})}_convertRoomToExternal(e){return c(this,null,function*(){var n,o,p,u,_,v;if(!e)return null;let[t,i,a]=yield Promise.all([Promise.all(((o=(n=e==null?void 0:e.participantIds)==null?void 0:n.map)==null?void 0:o.call(n,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((u=(p=e==null?void 0:e.addParticipantIds)==null?void 0:p.map)==null?void 0:u.call(p,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((v=(_=e==null?void 0:e.removeParticipantIds)==null?void 0:_.map)==null?void 0:v.call(_,this._getExternalIdByParticipantId.bind(this)))||[])]);return{id:e.id,name:e.name,participantCount:e.participantCount,participantIds:t,addParticipantIds:i,removeParticipantIds:a,participants:e.participants,active:e.active,muteStates:e.muteStates}})}_onRoomParticipantsUpdated(e){return c(this,null,function*(){var v,b,k,D,$;let t=this._transport.getState(),i=(v=e.roomId)!=null?v:null,[a,n]=yield Promise.all([Promise.all(((k=(b=e.addedParticipantIds)==null?void 0:b.map)==null?void 0:k.call(b,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all((($=(D=e==null?void 0:e.addedParticipants)==null?void 0:D.map)==null?void 0:$.call(D,j=>c(this,null,function*(){var G;let he=I.composeId(j);return this._createParticipant({id:he,externalId:j.externalId&&le.fromSignaling(j.externalId,j.deviceIdx||0),mediaSettings:me(j.mediaSettings),participantState:I.mapParticipantState(j),state:j.state,roles:j.roles||[],status:(G=this._getStatusByTransportState(t))!=null?G:"WAITING",muteStates:j.muteStates||{},unmuteOptions:j.unmuteOptions||[],observedIds:j.observedIds||[],markers:this._denormalizeMarkers(he,j.markers)})})))||[])]),o=!1;for(let j of n)j.id===this._conversation.compositeUserId&&(o=!0),this._registerParticipantInCache(j);this._openTransport(n,!0);let p=[],u=[];if(e!=null&&e.removedParticipantMarkers){for(let j of e.removedParticipantMarkers)j.GRID&&u.push(this._getExternalIdByParticipantId(j.GRID.id));p=yield Promise.all(u)}o&&(yield this._onRoomSwitched(i));let _={roomId:i,participantCount:e.participantCount,addedParticipantIds:a,addedParticipants:I.mapSharedParticipants(n),removedParticipantMarkers:e==null?void 0:e.removedParticipantMarkers,removedParticipantIds:p};g.onRoomParticipantsUpdated(_)})}_onRoomSwitched(e,t=!1){return c(this,null,function*(){if(!this._conversation||this._conversation.roomId===e)return;let i=this._conversation.roomId;if(this._conversation.roomId=e,t){g.onRoomStart(e);return}g.onRoomSwitched(e),e!==null&&!this._isCallAdmin()&&(yield this._refreshRooms(!1)),this._changeRecordInfoForRoom(),this._changeMuteStatesForRoom(e,i)})}_refreshRooms(e){return c(this,null,function*(){var a,n;let i=(n=(a=(yield this._signaling.getRooms(e)).rooms)==null?void 0:a.rooms)!=null?n:[];for(let o of i)this._setMuteStatesForRoomId(o.muteStates,o.id),this._conversation.recordsInfoByRoom.set(o.id,o.recordInfo);e&&g.onRoomsUpdated({[Ut.UPDATE]:{rooms:yield Promise.all(i.map(this._convertRoomToExternal.bind(this)))}})})}_onFeedback(e){return c(this,null,function*(){let t=n=>c(this,null,function*(){return(yield this._registerParticipantAndSetMarkersIfChunkEnabled(n)).externalId}),i=e.feedback.map(n=>c(this,null,function*(){let o=n.items.map(u=>c(this,null,function*(){if(u.participantId===this._conversation.compositeUserId)return Promise.resolve(qe(Re({},u),{participantId:this._conversation.externalId}));let _=yield t(u.participantId);return qe(Re({},u),{participantId:_})})),p=yield Promise.all(o);return qe(Re({},n),{items:p})})),a=yield Promise.all(i);g.onFeedback(a,e.roomId)})}_isMe(e){var t;return e===((t=this._conversation)==null?void 0:t.compositeUserId)}_getMuteStatesForRoomId(e=null){var i;return(i=this._conversation.muteStates.get(e))!=null?i:{}}_getMuteStatesForCurrentRoom(){return this._getMuteStatesForRoomId(this._conversation.roomId)}_setMuteStatesForRoomId(e={},t=null){this._conversation.muteStates.set(t,e)}},N=H;N._delayedHangup=!1;var Qt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Qt.prototype),this.participantErrors=t}};var xt,Xt=null;function Kn(){return c(this,null,function*(){var s;if(l.apiEnv!=="AUTO")return l.apiEndpoint;try{let r=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),t=yield(yield fetch(r,{method:"GET",mode:"cors",cache:"no-cache"})).json(),i=(s=t==null?void 0:t.Answer[0])==null?void 0:s.data;if(!i)throw new Error("Wrong DNS response");return d.debug("Resolved API endpoint",i),i}catch(r){return d.warn("Failed to resolve API endpoint using DNS, default is used",r),l.apiEndpoint}})}function ya(){return c(this,null,function*(){return xt||Xt||(Xt=Kn(),xt=yield Xt,Xt=null,xt)})}function Pa(){if(!l.apiKey)throw new V(re.API,{message:"Required argument apiAppKey not passed"})}function gr(t){return c(this,arguments,function*(s,r={},e=!1){if(!window.Blob||!window.navigator.sendBeacon)return;yield ya();let i=Ma(s,r,e),a=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${xt}/fb.do`,a)})}function ba(t){return c(this,arguments,function*(s,r={},e=!1){yield ya();let i=Ma(s,r,e);return $n(i)})}function $n(s){return c(this,null,function*(){return new Promise((r,e)=>{let t=new XMLHttpRequest;t.open("POST",`${xt}/fb.do`,!0),t.setRequestHeader("Content-type","application/x-www-form-urlencoded"),t.onreadystatechange=()=>{if(t.readyState!==XMLHttpRequest.DONE)return;let i;try{i=JSON.parse(t.responseText)}catch(a){i={result:t.responseText}}t.status!==200||i.hasOwnProperty("error_msg")?e(i):r(i)},t.send(s)})})}function Ma(s,r={},e=!1){r.method=s,r.format="JSON",r.application_key||(r.application_key=l.apiKey),e||(ae.sessionKey?r.session_key=ae.sessionKey:ae.accessToken&&(r.access_token=ae.accessToken));for(let[i,a]of Object.entries(r))typeof a=="object"&&(r[i]=JSON.stringify(a));let t="";for(let[i,a]of Object.entries(r))t&&(t+="&"),t+=`${i}=${encodeURIComponent(a)}`;return t}var Jn=10,zn=700,Yn=3e3,Zt=class extends St{constructor(){super(...arguments);this._userId=null;this._externalUidsCache=new Map;this._extrnalUidsBatch=new Set;this._extrnalUidsBatchTimeout=null}_callUnsafe(a){return c(this,arguments,function*(e,t={},i=!1){let n=o=>c(this,null,function*(){try{return yield ba(e,t,i)}catch(p){if(!p.hasOwnProperty("error_msg")&&(o++,d.debug(`${e} network error, attempt ${o}...`),o<Jn))return yield I.delay(Math.min(o*zn,Yn)),n(o);throw d.warn(e,"error",p),p}});return n(0)})}_call(a){return c(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){d.warn("Api call error",n);let o=re.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:o=O.SERVICE_DISABLED;break;case 1102:o=O.CALLEE_IS_OFFLINE;break;case 1103:o=O.NOT_FRIENDS;break;case 1104:case 1106:o=O.EXTERNAL_API_ERROR;break;case 1113:o=O.CALLER_IS_REJECTED;break}throw new V(o,{message:n.error_msg,code:n.error_code})}})}userId(e){return c(this,null,function*(){let t=I.decomposeId(e).id;return ae.isEmpty()?ge.fromId(String(t)):(yield this._prepareUserIdsByOkIdsBatched([t]),ge.fromString(this._externalUidsCache.get(t)))})}prepareUserIds(e){return c(this,null,function*(){ae.isEmpty()||(yield this._prepareUserIdsByOkIdsBatched(e))})}_prepareUserIdsByOkIdsBatched(e){return e.some(i=>!this._externalUidsCache.has(i))?(e.forEach(i=>this._extrnalUidsBatch.add(i)),this._extrnalUidsBatchTimeout||(this._extrnalUidsBatchPromise=new Promise(i=>{this._extrnalUidsBatchTimeout=window.setTimeout(()=>{if(this._extrnalUidsBatch.size>0){let a=[...this._extrnalUidsBatch];this._extrnalUidsBatch.clear(),this._getExternalIdsByOkIds(a).then(n=>{for(let o in n)n.hasOwnProperty(o)&&this._externalUidsCache.set(parseInt(o,10),n[o]);i()})}this._extrnalUidsBatchTimeout=null},l.api.userIdsByOkBatchedTimeout)})),this._extrnalUidsBatchPromise):Promise.resolve()}authorize(){return c(this,null,function*(){if(!this._uuid){let t=Ye.get("uuid");t||(t=I.uuid(),Ye.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)),ae.sessionKey=t.session_key,ae.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&g.onTokenExpired(),new V(re.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})};gr("log.externalLog",t)}init(){Pa()}joinConversation(e,t=!1,i){return c(this,null,function*(){let a={conversationId:e,isVideo:t,protocolVersion:l.protocolVersion};return i&&(a.chatId=i),this._call("vchat.joinConversation",a)})}createConversation(n){return c(this,arguments,function*(e,t="",i=!1,{onlyAdminCanShareMovie:a}={}){let o=this._preareStartConversationData({conversationId:e,isVideo:!1,joiningAllowed:!0,payload:t,requireAuthToJoin:i,onlyAdminCanShareMovie:a});return this._startConversation(o)})}startConversation(_,v,b){return c(this,arguments,function*(e,t,i,a=!1,n="",o=!1,p=!1,{onlyAdminCanShareMovie:u}={}){let k=this._preareStartConversationData({conversationId:e,isVideo:a,joiningAllowed:o,payload:n,requireAuthToJoin:p,onlyAdminCanShareMovie:u});if(t&&t.length)switch(i){case We.USER:k.uids=t.join(",");break;case We.GROUP:k.gid=t[0];break;case We.CHAT:k.chatId=t[0];break}return this._startConversation(k)})}_preareStartConversationData({conversationId:e,isVideo:t,payload:i="",joiningAllowed:a=!1,requireAuthToJoin:n=!1,onlyAdminCanShareMovie:o}){let p={conversationId:e,isVideo:t,protocolVersion:l.protocolVersion};return a&&(p.createJoinLink=!0),i&&(p.payload=i),l.domain&&(p.domainId=l.domain),l.externalDomain&&(p.externalDomain=l.externalDomain),n&&(p.requireAuthToJoin=!0),o!==void 0&&(p.onlyAdminCanShareMovie=o),p}_startConversation(e){return c(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return c(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return c(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return c(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let a=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(a.uid),a.token})}joinConversationByLink(e,t=!1,i,a){return c(this,null,function*(){let n={joinLink:e,isVideo:t,protocolVersion:l.protocolVersion};return i!=null&&i.length&&(n.observedIds=i.join(",")),l.anonymToken&&(n.anonymToken=l.anonymToken),a&&(n.payload=a),this._call("vchat.joinConversationByLink",n)})}getOkIdsByExternalIds(e){return c(this,null,function*(){let t=ge.fromIds(e),i=[],a={methods:[]},n=[],o=[...this._externalUidsCache.keys()],p=[...this._externalUidsCache.values()];for(let _ of t){let v=ge.toString(_),b=p.indexOf(v);b>-1?i.push(Number(o[b])):(n.push(v),a.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:_.id,anonym:_.type==="ANONYM"},onError:"SKIP"}}))}return a.methods.length&&(yield this._call("batch.executeV2",a)).forEach((_,v)=>{if(_.ok){let b=Number(_.ok.ok_id);this._externalUidsCache.set(b,n[v]),i.push(b)}}),i})}getExternalIdsByOkIds(e){return c(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.has(n)?t.push(ge.fromString(this._externalUidsCache.get(n))):i.push(n);if(!i.length)return t;let a=yield this._getExternalIdsByOkIds(i);for(let n in a)a.hasOwnProperty(n)&&this._externalUidsCache.set(parseInt(n,10),a[n]);for(let n of i)a.hasOwnProperty(n)&&t.push(ge.fromString(a[n]));return t})}getCachedOkIdByExternalId(e){let t=[...this._externalUidsCache.keys()],i=[...this._externalUidsCache.values()],a=ge.toString(e),n=i.indexOf(a);return n>-1?I.composeUserId(t[n],z.USER):null}cacheExternalId(e,t){let i=I.decomposeId(e).id;this._externalUidsCache.set(i,ge.toString(t))}getConversationParams(e){return c(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:O.HUNGUP};l.anonymToken&&(t.anonymToken=l.anonymToken),gr("vchat.hangupConversation",t)}removeHistoryRecords(e){return c(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return c(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[a,n]of Object.entries(i.external_ids))t[a]=ge.fromIdToString(n,"USER");if(i.anonym_ids)for(let[a,n]of Object.entries(i.anonym_ids))t[a]=ge.fromIdToString(n,"ANONYM");return t}catch(i){return t}})}};var Pi=class{requestAsr(r){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,1),t.setUint8(1,r?0:1),e}};import{Any as Xn,Arr as Da,Int as J,Nil as _t,Str as Zn}from"messagepack";var Aa=(L=>(L.RECOVER="recover",L.ACCEPT_CALL="accept-call",L.ADD_PARTICIPANT="add-participant",L.REMOVE_PARTICIPANT="remove-participant",L.HANGUP="hangup",L.TRANSMIT_DATA="transmit-data",L.ACCEPT_PRODUCER="accept-producer",L.ALLOCATE_CONSUMER="allocate-consumer",L.CHANGE_MEDIA_SETTINGS="change-media-settings",L.CHANGE_PARTICIPANT_STATE="change-participant-state",L.CHANGE_STREAM_PRIORITIES="change-streams-priorities",L.UPDATE_DISPLAY_LAYOUT="update-display-layout",L.REPORT_PERF_STAT="report-perf-stat",L.REPORT_SHARING_STAT="report-sharing-stat",L.RECORD_START="record-start",L.RECORD_STOP="record-stop",L.RECORD_SET_ROLE="record-set-role",L.RECORD_GET_STATUS="record-get-status",L.SWITCH_MICRO="switch-micro",L.SWITCH_TOPOLOGY="switch-topology",L.REQUEST_REALLOC="request-realloc",L.CHAT_MESSAGE="chat-message",L.CHAT_HISTORY="chat-history",L.CUSTOM_DATA="custom-data",L.GRANT_ROLES="grant-roles",L.MUTE_PARTICIPANT="mute-participant",L.ENABLE_FEATURE_FOR_ROLES="enable-feature-for-roles",L.PIN_PARTICIPANT="pin-participant",L.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",L.CHANGE_OPTIONS="change-options",L.GET_WAITING_HALL="get-waiting-hall",L.GET_PARTICIPANT_LIST_CHUNK="get-participant-list-chunk",L.GET_PARTICIPANTS="get-participants",L.PROMOTE_PARTICIPANT="promote-participant",L.REQUEST_TEST_MODE="request-test-mode",L.ADD_MOVIE="add-movie",L.UPDATE_MOVIE="update-movie",L.REMOVE_MOVIE="remove-movie",L.GET_ROOMS="get-rooms",L.UPDATE_ROOMS="update-rooms",L.ACTIVATE_ROOMS="activate-rooms",L.REMOVE_ROOMS="remove-rooms",L.SWITCH_ROOM="switch-room",L.FEEDBACK="feedback",L.ASR_START="asr-start",L.ASR_STOP="asr-stop",L.REQUEST_ASR="request-asr",L))(Aa||{}),x=Aa;function ei(){let s=new DataView(new ArrayBuffer(64)),r=0;function e(t){if(r+t>s.byteLength){let i=new Uint8Array(Math.max(r+t,s.byteLength+64));i.set(new Uint8Array(s.buffer.slice(0,r))),s=new DataView(i.buffer)}}return{put(t){if(e(t.byteLength),Qn(t)){let i=t.buffer;new Uint8Array(s.buffer).set(new Uint8Array(i),r)}else new Uint8Array(s.buffer).set(new Uint8Array(t),r);r+=t.byteLength},putI8(t){e(1),s.setInt8(r,t),++r},putI16(t){e(2),s.setInt16(r,t),r+=2},putI32(t){e(4),s.setInt32(r,t),r+=4},putI64(t){e(8);let i=t<0;i&&(t=-t);let a=t/4294967296|0,n=t%4294967296|0;i&&(n=~n+1|0,a=n===0?~a+1|0:~a),s.setUint32(r,a),s.setUint32(r+4,n),r+=8},putUi8(t){e(1),s.setUint8(r,t),++r},putUi16(t){e(2),s.setUint16(r,t),r+=2},putUi32(t){e(4),s.setUint32(r,t),r+=4},putUi64(t){e(8),s.setUint32(r,t/4294967296|0),s.setUint32(r+4,t%4294967296),r+=8},putF(t){e(8),s.setFloat64(r,t),r+=8},ui8array(){return new Uint8Array(s.buffer.slice(0,r))}}}function Qn(s){return s.buffer!==void 0}function bi(s){let r=ArrayBuffer.isView(s)?new DataView(s.buffer,s.byteOffset,s.byteLength):new DataView(s),e=0;return{peek(){return r.getUint8(e)},get(t){e+=t;let i=r.byteOffset;return r.buffer.slice(i+e-t,i+e)},getI8(){return r.getInt8(e++)},getI16(){return e+=2,r.getInt16(e-2)},getI32(){return e+=4,r.getInt32(e-4)},getI64(){e+=8;let t=r.getInt32(e-8),i=r.getUint32(e-4);return t*4294967296+i},getUi8(){return r.getUint8(e++)},getUi16(){return e+=2,r.getUint16(e-2)},getUi32(){return e+=4,r.getUint32(e-4)},getUi64(){e+=8;let t=r.getUint32(e-8),i=r.getUint32(e-4);return t*4294967296+i},getF32(){return e+=4,r.getFloat32(e-4)},getF64(){return e+=8,r.getFloat64(e-8)}}}var ka=0,Oa=1,es=2,ts=0,is=1,rs=2,Mi=0,as=0,ns=0,ss=1,Ai=class{constructor(){this.participantIdRegistry=null}setParticipantIdRegistry(r){this.participantIdRegistry=r}serializeUpdateDisplayLayout(r,e){let t=ei();J.enc(t,ka),J.enc(t,Mi),J.enc(t,r),_t.enc(t,null);let i=[];for(let a in e)e.hasOwnProperty(a)&&this.writeLayout(e,a,i);return Da.enc(t,i),_t.enc(t,null),t.ui8array()}writeLayout(r,e,t){let i=r[e],a=ei();if(this.writeStreamDesc(e,a),Gt(i))J.enc(a,is);else if(lr(i))J.enc(a,rs);else if(J.enc(a,ts),i.priority!==void 0?J.enc(a,i.priority):_t.enc(a,null),i.width!==void 0&&i.height!==void 0?(J.enc(a,Math.round(i.width)),J.enc(a,Math.round(i.height))):(_t.enc(a,null),_t.enc(a,null)),i.fit!==void 0)switch(i.fit){case"cv":J.enc(a,ns);break;case"cn":J.enc(a,ss);break;default:_t.enc(a,null)}else _t.enc(a,null);t.push(a.ui8array())}writeStreamDesc(r,e){if(this.participantIdRegistry){let t=this.participantIdRegistry.getCompactId(r);if(t!==void 0){J.enc(e,t);return}}Zn.enc(e,r)}serializePerfStatReport(r,e){let t=ei();return J.enc(t,Oa),J.enc(t,Mi),J.enc(t,r),J.enc(t,e.framesDecoded),J.enc(t,e.framesReceived),t.ui8array()}serializeSharingStatReport(r,e){let t=ei();return J.enc(t,es),J.enc(t,Mi),J.enc(t,r),J.enc(t,e.minDelay),J.enc(t,e.maxDelay),J.enc(t,e.avgDelay),J.enc(t,e.largeDelayDuration),t.ui8array()}deserializeCommandResponse(r){return c(this,null,function*(){let e;if(r instanceof Blob){let n=Blob.prototype.arrayBuffer?yield r.arrayBuffer():yield ta(r);e=bi(n)}else e=bi(r);let t=J.dec(e),i=J.dec(e);if(i!==Mi){d.warn("Unsupported version for command type: "+t+", version "+i);return}if(J.dec(e)!==as){d.warn("Error code: "+t+"received for command type: "+t+", version "+i);return}switch(t){case ka:return this.deserializeUpdateDisplayLayoutResponse(e);case Oa:return this.deserializeReportPerfStatResponse(e);default:return d.warn("unsupported command response commandType: "+t),null}})}deserializeUpdateDisplayLayoutResponse(r){let e=J.dec(r),t=Da.dec(r),i={};return t.forEach(a=>{let n=bi(a),o=Xn.dec(n);if(typeof o=="string")i[o]=J.dec(n);else{let p=o,u=Fe(this.participantIdRegistry.getStreamDescription(p));i[u]=J.dec(n)}}),{type:"response",sequence:e,response:x.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:i}}deserializeReportPerfStatResponse(r){let e=J.dec(r),t=J.dec(r);return{type:"response",sequence:e,response:x.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:t}}};var Di="open",wa=[()=>l.producerScreenTrack,()=>l.videoTracksCount>0,()=>!0,()=>l.filteredMessages,()=>l.consumerScreenTrack,()=>!0,()=>l.movieShare,()=>l.useParticipantListChunk,()=>l.useRooms,()=>l.useVmoji],os=10,be=class extends Et{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.asrCommandsQueue=[];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="+be._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null;this.asrDataChannel=null;this.producerCommandDataChannelEnabled=!1;this.producerCommandSerializationService=new Ai;this.asrCommandSerializer=new Pi}static _getCapabilityFlags(){let e=0;for(let t=0;t<wa.length;t++)wa[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 a;let i=(a=this.participantIdRegistry)==null?void 0:a.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=>{d.warn("Cannot parse message at producerCommandDataChannel",i)})},this._handleCommandsQueue(this.datachannelCommandsQueue)}useCommandDataChannel(e){this.producerCommandDataChannelEnabled=e}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return c(this,null,function*(){return this.postfix+=`&clientType=${l.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){S.log(R.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=a=>{t(a),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=a=>{i(a),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(a){return c(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=I.decomposeParticipantId(t.participantId),o=I.decomposeId(n.compositeUserId);t=Object.assign({},t,{participantId:o.id,participantType:o.type}),n.deviceIdx&&(t.deviceIdx=n.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(a){return c(this,arguments,function*(e,t={},i=0){let n=o=>{var p,u;if(e===x.REQUEST_ASR)this.asrCommandsQueue.push(o),((p=this.asrDataChannel)==null?void 0:p.readyState)===Di&&this._handleCommandsQueue(this.asrCommandsQueue);else if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(o),((u=this.producerCommandDataChannel)==null?void 0:u.readyState)===Di&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){S.log(R.SOCKET_ACTION,"not_opened"),d.warn("Socket not opened"),o.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(S.log(R.SOCKET_ACTION,"invalid_state"),d.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(o),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((o,p)=>{let u=(v,b=!1)=>{!i||b?p(v):(d.debug("Resending a signaling message",e,_.sequence),i--,n(_))},_={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:o,reject:u};n(_)})})}_isDataChannelCommand(e){return this.producerCommandDataChannelEnabled?e===x.UPDATE_DISPLAY_LAYOUT||e===x.REPORT_PERF_STAT||e===x.REPORT_SHARING_STAT:!1}static _isDataChannelResponseRequired(e){return e===x.UPDATE_DISPLAY_LAYOUT||e===x.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return c(this,null,function*(){return this._send(x.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return c(this,null,function*(){return this._send(x.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e,t){return c(this,null,function*(){return this._send(x.REQUEST_TEST_MODE,{consumer:e,producer:t})})}sendSdp(e,t){return c(this,null,function*(){return this._send(x.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return c(this,null,function*(){return this._send(x.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return c(this,null,function*(){return this._send(x.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},os)})}changeParticipantState(e){return c(this,null,function*(){return this._send(x.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return c(this,null,function*(){return this._send(x.ADD_PARTICIPANT,Re({participantId:e},t))})}removeParticipant(e,t=!1){return c(this,null,function*(){return this._send(x.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return c(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(x.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return c(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(x.ACCEPT_PRODUCER,i)})}changePriorities(e){return c(this,null,function*(){return this._send(x.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return c(this,null,function*(){return this._send(x.UPDATE_DISPLAY_LAYOUT,e)})}addMovie(e){return c(this,null,function*(){return this._send(x.ADD_MOVIE,e)})}updateMovie(e){return c(this,null,function*(){return this._send(x.UPDATE_MOVIE,e)})}removeMovie(e){return c(this,null,function*(){return this._send(x.REMOVE_MOVIE,e)})}updateRooms(e,t){return c(this,null,function*(){return this._send(x.UPDATE_ROOMS,{rooms:e,assignRandomly:t})})}activateRooms(e,t){return c(this,null,function*(){return this._send(x.ACTIVATE_ROOMS,{roomIds:e,deactivate:t})})}switchRoom(e,t){return c(this,null,function*(){return this._sendRaw(x.SWITCH_ROOM,{toRoomId:e,participantId:t})})}getRooms(e){return c(this,null,function*(){return this._sendRaw(x.GET_ROOMS,{withParticipants:e})})}removeRooms(e){return c(this,null,function*(){return this._send(x.REMOVE_ROOMS,{roomIds:e})})}startStream(e){return c(this,null,function*(){return this._send(x.RECORD_START,e)})}stopStream(){return c(this,arguments,function*(e={roomId:null}){return this._send(x.RECORD_STOP,e)})}recordSetRole(e,t,i=null){return c(this,null,function*(){return this._send(x.RECORD_SET_ROLE,{participantId:e,role:t,roomId:i})})}getRecordStatus(){return c(this,null,function*(){return this._send(x.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return c(this,null,function*(){return this._send(x.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return c(this,null,function*(){return this._send(x.REQUEST_REALLOC)})}reportPerfStat(e){return c(this,null,function*(){return this._send(x.REPORT_PERF_STAT,e)})}reportSharingStat(e){return c(this,null,function*(){return this._send(x.REPORT_SHARING_STAT,e)})}chatMessage(e,t=null){return c(this,null,function*(){return this._send(x.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return c(this,null,function*(){return this._send(x.CHAT_HISTORY,{count:e})})}customData(e,t){return c(this,null,function*(){return this._send(x.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return c(this,null,function*(){let a={participantId:e,roles:t};return i&&(a.revoke=!0),this._sendRaw(x.GRANT_ROLES,a)})}muteParticipant(e,t,i,a=null){return c(this,null,function*(){return this._sendRaw(x.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i,roomId:a})})}enableFeatureForRoles(e,t){return c(this,null,function*(){return this._sendRaw(x.ENABLE_FEATURE_FOR_ROLES,{feature:e,roles:t})})}pinParticipant(e,t){return c(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(x.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return c(this,null,function*(){return this._send(x.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return c(this,null,function*(){return this._send(x.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return c(this,null,function*(){let a={};return e&&(a.fromId=e),t&&(a.count=t),i&&(a.backward=i),this._send(x.GET_WAITING_HALL,a)})}promoteParticipant(e,t=!1){return c(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(x.PROMOTE_PARTICIPANT,i)})}feedback(e){return c(this,null,function*(){return this._sendRaw(x.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 c(this,null,function*(){return this._send(x.GET_PARTICIPANT_LIST_CHUNK,e)})}getParticipants(e){return c(this,null,function*(){return this._send(x.GET_PARTICIPANTS,{externalIds:e})})}startAsr(){return c(this,null,function*(){return this._send(x.ASR_START)})}stopAsr(){return c(this,null,function*(){return this._send(x.ASR_STOP)})}requestAsr(e){return c(this,null,function*(){return this._send(x.REQUEST_ASR,{request:e})})}setAsrDataChannel(e){this.asrDataChannel=e,this._handleCommandsQueue(this.asrCommandsQueue)}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ke.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),t=i(t),d.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(a){if(!l.useParticipantListChunk)return a;let n=l.participantListChunkInitIndex;a+=`&partIdx=${n}`;let o=l.participantListChunkInitCount;return o!==null&&(a+=`&partCount=${o}`),a}}_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(){d.debug("Socket opened"),S.log(R.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){S.log(R.SOCKET_ACTION,"parse_error"),d.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(d.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(Se.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Se.NOTIFICATION,{type:"notification",notification:w.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(Se.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(S.log(R.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(S.log(R.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new V(O.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(Se.NOTIFICATION,{notification:w.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new V(re.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(S.log(R.SOCKET_ACTION,"unknown_message"),d.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(Se.FAILED,e)}_onError(e){S.log(R.SOCKET_ACTION,"error"),d.error("Signaling error",e)}_onClose(e){S.log(R.SOCKET_ACTION,"closed"),d.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<be.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){this.socket&&(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(be.RECONNECT_MAX_DELAY,be.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));d.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),S.log(R.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ke.RETRY),e)}_handleCommandResponse(e,t){var a;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)):((a=this.socket)==null?void 0:a.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],S.log(R.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),be.WAIT_RESPONSE_DELAY)}_serializeAsrCommand(e){let t=e.params;return this.asrCommandSerializer.requestAsr(t.request)}_handleCommandsQueue(e){var t,i,a,n;for(;e.length>0;){let o=e.shift();if(o.name===x.REQUEST_ASR){if(((t=this.asrDataChannel)==null?void 0:t.readyState)!==Di){o.reject(new Error(`Invalid data channel state: ${(i=this.asrDataChannel)==null?void 0:i.readyState}`));return}let p=this._serializeAsrCommand(o);p!==null&&(this.asrDataChannel.send(p),o.resolve({}))}else if(this._isDataChannelCommand(o.name)){if(((a=this.producerCommandDataChannel)==null?void 0:a.readyState)!==Di){o.reject(new Error(`Invalid data channel state: ${(n=this.producerCommandDataChannel)==null?void 0:n.readyState}`));return}be._isDataChannelResponseRequired(o.name)&&(o.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:o.name,sequence:o.sequence}),be.WAIT_RESPONSE_DELAY),this.responseHandlers[o.sequence]=o);let p=this._serializeBinary(o);p!==null&&this.producerCommandDataChannel.send(p)}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){o.reject(new Error("Invalid state or socket already closed"));continue}o.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:o.name,sequence:o.sequence}),be.WAIT_RESPONSE_DELAY),this.responseHandlers[o.sequence]=o,this.socket.send(this._serializeJson(o))}}}_serializeBinary(e){switch(e.name){case x.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case x.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params);case x.REPORT_SHARING_STAT:return this.producerCommandSerializationService.serializeSharingStatReport(e.sequence,e.params)}return d.warn("cannot get binary data for data channel command: "+e.name),null}_serializeJson(e){let t;e.name===x.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 a in t)t.hasOwnProperty(a)&&(i[a]=ga(t[a]));return{layouts:i}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new V(re.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},be.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{d.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Ke.RETRY)},be.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},xe=be;xe.RECONNECT_DELAY=l.signalingReconnectDelay,xe.RECONNECT_MAX_DELAY=l.signalingReconnectMaxDelay,xe.RECONNECT_MAX_COUNT=l.signalingReconnectMaxCount,xe.WAIT_CONNECTION_DELAY=l.waitConnectionDelay,xe.WAIT_RESPONSE_DELAY=l.waitResponseDelay,xe.WAIT_MESSAGE_DELAY=l.waitMessageDelay;var xa=(e=>(e.KING="KING",e.PAWN="PAWN",e))(xa||{}),cs=xa;var fr=class{constructor(r){this._queue=new Array(r).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(r){this._moveReadCursor&&(this._readCursor=this.nextCursor(this._readCursor)),this._queue[this._writeCursor]===null&&(this._left+=1),this._queue[this._writeCursor]=r,this._writeCursor=this.nextCursor(this._writeCursor),this._moveReadCursor=this._writeCursor===this._readCursor}nextCursor(r){return(r+1)%this._queue.length}next(){let r=this._queue[this._readCursor];return r&&(this._moveReadCursor=!1,this._queue[this._readCursor]=null,this._readCursor=this.nextCursor(this._readCursor),this._left-=1),r}};var Lt,ne,ti=null,b_={getCameras:y.getCameras,getMicrophones:y.getMicrophones,getOutput:y.getOutput,getVideoFacingMode:y.getVideoFacingMode,hasCamera:y.hasCamera,hasMicrophone:y.hasMicrophone,getSavedCamera:y.getSavedCamera,getSavedMicrophone:y.getSavedMicrophone,getSavedOutput:y.getSavedOutput,hasCameraPermission:y.hasCameraPermission,hasMicrophonePermission:y.hasMicrophonePermission,hasPermissions:y.hasPermissions,getUserMedia:y.getUserMedia,getUserVideo:y.getUserVideo,getUserAudio:y.getUserAudio,saveDeviceId:y.saveDeviceId,isBrowserSupported:y.isBrowserSupported,isScreenCapturingSupported:y.isScreenCapturingSupported,os:y.os,isMobile:y.isMobile,browserName:y.browserName,browserVersion:y.browserVersion,baseChromeVersion:y.baseChromeVersion,getAudioContext:y.getAudioContext,isAudioShareSupported:y.isAudioShareSupported};function ds(s){ne=s}function ls(s){Lt=s}function M_(s){ti=s}function A_(s){l.videoEffects=s}function D_(s,r=null){l.vmoji=s,r&&s.setSDK(r)}function k_(s){return c(this,null,function*(){if(l.set(s),y.browserName()==="Sferum"&&(l.platform=`SFERUM:${y.browserVersion()}`),ne||ds(new Zt),Lt||ls(()=>new xe),l.debug&&(La.disableLog(!1),d.toggle(!0)),d.log(`Calls SDK ${l.sdkVersion}`,s),yield y.init(),!y.isBrowserSupported())throw new V(re.UNSUPPORTED);d.log("UserAgent:",navigator.userAgent),d.log("Screen resolution:",`${window.screen.width}x${window.screen.height}`),d.log("Permissions:",`Camera: ${y.hasCameraPermission()}, Mic: ${y.hasMicrophonePermission()}`),ne.init()})}function O_(n){return c(this,arguments,function*(s,r=[de.AUDIO],e="",t=!1,i=!1,a){let o=[],p=[];if(Array.isArray(s)?o=s.length?s:[]:s&&(o=[s]),o.length&&(p=yield ne.getOkIdsByExternalIds(o),!p.length))throw new V(O.CALLEE_IS_OFFLINE);return ps(p,We.USER,r,e,t,i,a)})}function ps(o){return c(this,arguments,function*(s,r=We.USER,e,t="",i=!1,a=!1,n){if(N.current())throw d.error("There is already active call"),new V(O.FAILED);return new N(ne,Lt(),ti).onStart(s,r,e,t,i,a,n)})}function w_(s){return c(this,null,function*(){return us(s)})}function us(t){return c(this,arguments,function*(s,r=z.USER,e){if(s===N.id())throw new Error("Push has already been processed");return new N(ne,Lt(),ti).onPush(s,r,e)})}function x_(s){return c(this,null,function*(){return s&&(l.authToken=s),ne.authorize()})}function L_(){return c(this,arguments,function*(s=[de.AUDIO]){return gt().accept(s)})}function N_(){return c(this,null,function*(){let s=N.current();if(s)return s.decline()})}function U_(e){return c(this,arguments,function*(s,r=[de.AUDIO]){return ms(s,r)})}function ms(s,r,e){return c(this,null,function*(){if(N.current())throw d.error("There is already active call"),new V(O.FAILED);return new N(ne,Lt(),ti).onJoin({conversationId:s,mediaOptions:r,chatId:e})})}function B_(a){return c(this,arguments,function*(s,r=[de.AUDIO],e,t,i){if(N.current())throw d.error("There is already active call"),new V(O.FAILED);return e&&(l.anonymToken=e),new N(ne,Lt(),ti).onJoin({joinLink:s,mediaOptions:r,observedIds:t,payload:i})})}function V_(){return c(this,null,function*(){let s=N.current();if(s)return s.hangup();N.hangupAfterInit()})}function F_(s,r){return c(this,null,function*(){let e=yield ne.getOkIdsByExternalIds([s]);if(!e.length)throw new Error("User not found");return hs(e[0],r)})}function hs(s,r){return c(this,null,function*(){let e=N.current();e&&(yield e.addParticipant(I.composeUserId(s,z.USER),r))})}function j_(s,r=!1){return c(this,null,function*(){let e=yield ne.getOkIdsByExternalIds([s]);return _s(e[0],r)})}function _s(s,r=!1){return c(this,null,function*(){let e=N.current();e&&(yield e.removeParticipant(I.composeUserId(s,z.USER),r))})}function H_(s,r){return c(this,null,function*(){let e=N.current();return s==="videoinput"&&Ze.contains(r)?(l.videoFacingMode=r,e?(y.isMobile()&&(yield e.stopVideoTrack()),e.changeDevice(s)):Promise.reject()):(yield y.saveDeviceId(s,r))&&e?e.changeDevice(s):Promise.reject()})}function G_(s){return c(this,null,function*(){let r=typeof s=="object"?qe(Re({},s),{fastScreenSharing:s.captureScreen&&s.fastScreenSharing,captureAudio:s.captureScreen&&s.captureAudio&&l.audioShare}):{captureScreen:s,fastScreenSharing:!1,captureAudio:!1},e=N.current();return e?e.toggleScreenCapturing(r):Promise.reject()})}function W_(s){let r=N.current();r&&r.toggleAnimojiCapturing(s)}function K_(s,r=!1){return c(this,null,function*(){let e=N.current();e&&(yield e.setVideoStream(s,r))})}function $_(s){return c(this,null,function*(){let r=N.current();r&&(yield r.toggleLocalVideo(s))})}function q_(s){return c(this,null,function*(){let r=N.current();r&&(yield r.toggleLocalAudio(s))})}function J_(s,r,e){return c(this,null,function*(){let t=N.current();if(t)return t.setLocalResolution(s,r,e)})}function z_(s){return c(this,null,function*(){let r=N.current();r&&(yield r.changePriorities(s))})}function Y_(s){return c(this,null,function*(){let r=N.current();r&&(yield r.changeParticipantState(s))})}function Q_(s){return c(this,null,function*(){let r=N.current();r&&(yield r.updateDisplayLayout(s))})}function X_(s,r,e=!1){return c(this,null,function*(){let t=yield ne.getOkIdsByExternalIds([s]);return gs(t[0],r,e)})}function gs(s,r,e=!1){return c(this,null,function*(){let t=N.current();t&&(yield t.grantRoles(I.composeUserId(s,z.USER),r,e))})}function Z_(i){return c(this,arguments,function*({externalId:s=null,muteStates:r,requestedMedia:e=[],roomId:t=null}){let a=null;return s&&(a=(yield ne.getOkIdsByExternalIds([s]))[0]),fs({uid:a,muteStates:r,requestedMedia:e,deviceIdx:le.getDeviceIdx(s),roomId:t})})}function fs(a){return c(this,arguments,function*({uid:s=null,muteStates:r,requestedMedia:e=[],deviceIdx:t=0,roomId:i=null}){let n=N.current();if(n){let o=s?I.composeParticipantId(s,z.USER,t):null;yield n.muteParticipant(o,r,e,i)}})}function eg(s,r=!1){return c(this,null,function*(){let e=yield ne.getOkIdsByExternalIds([s]);return Ss(e[0],r,le.getDeviceIdx(s))})}function Ss(s,r=!1,e=0){return c(this,null,function*(){let t=N.current();t&&(yield t.pinParticipant(I.composeParticipantId(s,z.USER,e),r))})}function tg(s){return c(this,null,function*(){let r=N.current();r&&(yield r.updateMediaModifiers(s))})}function ig(s){return c(this,null,function*(){let r=N.current();r&&(yield r.changeOptions(s))})}function rg(s,r=null){return c(this,null,function*(){let e=null;return r&&(e=(yield ne.getOkIdsByExternalIds([r]))[0]),vs(s,e)})}function vs(s,r=null){return c(this,null,function*(){let e=N.current();if(e){let t=r?I.composeUserId(r,z.USER):null;yield e.chatMessage(s,t)}})}function ag(s=10){return c(this,null,function*(){let r=N.current();if(r)return r.chatHistory(s)})}function ng(s,r=null){return c(this,null,function*(){let e=null;return r&&(e=(yield ne.getOkIdsByExternalIds([r]))[0]),Es(s,e,le.getDeviceIdx(r))})}function Es(s,r=null,e=0){return c(this,null,function*(){let t=N.current();if(t){let i=r?I.composeParticipantId(r,z.USER,e):null;yield t.customData(s,i)}})}function sg(){return c(this,arguments,function*(s="",r=!1,{onlyAdminCanShareMovie:e=!1}={}){return(yield ne.createConversation(I.uuid(),s,r,{onlyAdminCanShareMovie:e})).join_link})}function og(){return c(this,null,function*(){let s=N.current();return s?s.createJoinLink():Promise.reject()})}function cg(){return c(this,null,function*(){let s=N.current();return s?s.removeJoinLink():Promise.reject()})}function dg(s,r){return c(this,null,function*(){return ne.getAnonymTokenByLink(s,r)})}function lg(s){let r=N.current();r&&r.setVolume(s)}function pg(s){l.forceRelayPolicy=s}function ug(s=!1,r=null,e=null,t="DIRECT_LINK",i=null,a=null){return c(this,null,function*(){let n=N.current();return n?n.startStream(s,r,e,t,i,a):Promise.reject()})}function mg(s=null){return c(this,null,function*(){let r=N.current();return r?r.stopStream(s):Promise.reject()})}function hg(s,r,e=null){return c(this,null,function*(){let t=N.current();if(t){let i=yield ne.getOkIdsByExternalIds([s]),a=le.getDeviceIdx(s);return t.recordSetRole(I.composeParticipantId(i[0],z.USER,a),r,e)}return Promise.reject()})}function _g(){return c(this,null,function*(){let s=N.current();return s?s.getStreamInfo():Promise.reject()})}function gg(s){return c(this,null,function*(){let r=N.current();return r?r.addMovie(s):Promise.reject()})}function fg(s){return c(this,null,function*(){let r=N.current();return r?r.updateMovie(s):Promise.reject()})}function Sg(s){return c(this,null,function*(){let r=N.current();return r?r.removeMovie(s):Promise.reject()})}function vg(s,r){return c(this,null,function*(){let e=N.current();if(e){let t=[];for(let i of s){let a,n;i.addParticipantIds&&(a=(yield ne.getOkIdsByExternalIds(i.addParticipantIds)).map(o=>I.composeUserId(o,z.USER))),i.removeParticipantIds&&(n=(yield ne.getOkIdsByExternalIds(i.removeParticipantIds)).map(o=>I.composeUserId(o,z.USER))),t.push({id:i.id,name:i.name,participantCount:i.participantCount,addParticipantIds:a,removeParticipantIds:n})}return e.updateRooms(t,r)}return Promise.reject()})}function Eg(s,r){return c(this,null,function*(){let e=N.current();return e?e.activateRooms(s,r):Promise.reject()})}function Ig(s=null,r=null){return c(this,null,function*(){let e=null;if(r){let i=yield ne.getOkIdsByExternalIds([r]);e=I.composeUserId(i[0],z.USER)}let t=N.current();return t?t.switchRoom(s,e):Promise.reject()})}function Tg(s){return c(this,null,function*(){let r=N.current();return r?r.removeRooms(s):Promise.reject()})}function Rg(s){l.statisticsInterval=s;let r=N.current();if(r)return r.updateStatisticsInterval()}function Cg(s){La.disableLog(!s),d.toggle(s)}function yg(s,...r){l.debugLog&&d.send(s,"[external]",...r)}function Pg(s){return c(this,null,function*(){let r=N.current();if(r)return r.videoEffect(s)})}function bg(s){return c(this,null,function*(){let r=N.current();r&&(yield r.setAudioStream(s))})}function Mg(s,r=null,e=null){return c(this,null,function*(){let t=N.current();if(!t)return;let i=e!=null?e:r==null?void 0:r.id,a=null;if(r){let o=(yield ne.getOkIdsByExternalIds([r]))[0];if(!o)throw new Error("Could not get user id to set animoji svg");a=I.composeParticipantId(o,z.USER,le.getDeviceIdx(r))}t.setAnimojiSvg(s,a,i)})}function Ag(s=null,r,e=!1){return c(this,null,function*(){return gt().getWaitingHall(s,r,e)})}function Dg(s,r=!1){return c(this,null,function*(){let e=gt(),t=yield ne.getOkIdsByExternalIds([s]);return e.promoteParticipant(I.composeUserId(t[0],z.USER),r)})}function kg(s){return c(this,null,function*(){return gt().getParticipantListChunk(s)})}function Og(s){return c(this,null,function*(){return gt().getParticipants(s)})}function wg(s){return c(this,null,function*(){return gt().feedback(s)})}function xg(s,r){return c(this,null,function*(){return gt().enableFeatureForRoles(s,r)})}function gt(){let s=N.current();if(!s)throw new Error("Conversation not found");return s}function Lg(s){return c(this,null,function*(){yield ne.removeHistoryRecords(s)})}function Ng(){return c(this,null,function*(){let s=N.current();s&&(yield s.startAsr())})}function Ug(){return c(this,null,function*(){let s=N.current();s&&(yield s.stopAsr())})}function Bg(s){return c(this,null,function*(){let r=N.current();r&&(yield r.requestAsr(s))})}function Vg(){return l.sdkVersion}export{Zt as Api,fr as ArrayDequeue,St as BaseApi,vt as BaseLogger,Et as BaseSignaling,Je as CallDirection,We as CallType,Ni as ChatRoomEventType,Ui as ConversationFeature,Bi as ConversationOption,_a as DebugMessageType,dr as ExternalIdType,Ze as FacingMode,re as FatalError,V as HangupReason,O as HangupType,de as MediaOption,Ue as MediaTrackKind,Wt as MediaType,ke as MuteState,W as ParticipantState,or as ParticipantStatus,cs as RecordRole,Ut as RoomsEventType,xe as Signaling,x as SignalingCommandType,Ke as SignalingConnectionType,w as SignalingNotification,mt as TransportTopology,ze as UserRole,z as UserType,I as Utils,L_ as acceptCall,Eg as activateRooms,gg as addMovie,F_ as addParticipant,hs as addParticipantInternal,x_ as authorize,b_ as browser,ps as callInternal,O_ as callTo,G_ as captureScreen,W_ as captureVmoji,ig as changeConversationOptions,H_ as changeDevice,Y_ as changeParticipantState,z_ as changePriorities,Pg as changeVideoEffect,ag as chatHistory,rg as chatMessage,vs as chatMessageInternal,og as createJoinLink,ng as customData,Es as customDataInternal,Cg as debug,yg as debugMessage,N_ as declineCall,xg as enableFeatureForRoles,wg as feedback,pg as forceRelayPolicy,dg as getAnonymTokenByLink,kg as getParticipantListChunk,Og as getParticipants,_g as getStreamInfo,Ag as getWaitingHall,X_ as grantRoles,gs as grantRolesInternal,V_ as hangup,k_ as init,U_ as joinCall,B_ as joinCallByLink,ms as joinCallInternal,Z_ as muteParticipant,fs as muteParticipantInternal,eg as pinParticipant,Ss as pinParticipantInternal,w_ as processPush,us as processPushInternal,Dg as promoteParticipant,hg as recordSetRole,Lg as removeHistoryRecords,cg as removeJoinLink,Sg as removeMovie,j_ as removeParticipant,_s as removeParticipantInternal,Tg as removeRooms,Bg as requestAsr,ds as setApi,bg as setAudioStream,J_ as setLocalResolution,M_ as setLogger,tg as setMediaModifiers,ls as setSignalingFactory,Rg as setStatisticsInterval,A_ as setVideoEffects,K_ as setVideoStream,D_ as setVmoji,Mg as setVmojiSvg,lg as setVolume,Ng as startAsr,sg as startConversation,ug as startStream,Ug as stopAsr,mg as stopStream,Ig as switchRoom,q_ as toggleLocalAudio,$_ as toggleLocalVideo,Q_ as updateDisplayLayout,fg as updateMovie,vg as updateRooms,Vg as version};
|