@vkontakte/calls-sdk 2.8.13-dev.d26e27ad.0 → 2.8.13-dev.d5fda3ae.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/abstract/BaseApi.d.ts +4 -0
- package/calls-sdk.cjs.js +7 -7
- package/calls-sdk.esm.js +2080 -2055
- package/classes/stat/ApiCallStats.d.ts +12 -0
- package/classes/stat/ConversationStats.d.ts +3 -0
- package/classes/stat/StatAggregator.d.ts +8 -1
- package/classes/transport/DirectTransport.d.ts +4 -0
- package/default/Signaling.d.ts +9 -1
- package/enums/Stat.d.ts +1 -0
- package/package.json +1 -1
- package/static/Params.d.ts +8 -0
- package/static/SimulcastInfo.d.ts +0 -1
- package/types/IEventualStatLog.d.ts +1 -1
package/calls-sdk.cjs.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @vkontakte/calls-sdk v2.8.13-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/calls-sdk v2.8.13-dev.d5fda3ae.0
|
|
3
|
+
* Thu, 24 Sep 2026 15:03:51 GMT
|
|
4
4
|
* https://calls-sdk.cdn-vk.ru/doc/latest/index.html
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("webrtc-adapter");c=s(c);let l=require("messagepack"),u=require("@vkontakte/libvpx");u=s(u);let d=require("bit-buffer"),f=require("simple-ebml-builder");f=s(f);let p=require("fflate");p=s(p);var m=class{log(e,t,n=!1){}destroy(){}};function ee(e){"@babel/helpers - typeof";return ee=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},ee(e)}function te(e,t){if(ee(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(ee(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ne(e){var t=te(e,`string`);return ee(t)==`symbol`?t:t+``}function h(e,t,n){return(t=ne(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var re=25*1024*1024,ie=10,ae=`_okcls_logs_session_`,oe=3e4,se=`ok-calls-sdk-debug-logs`,ce=1,g=`sessions`,_=`chunks`,le=120*1e3,ue=new Set([`WARN`,`ERROR`]);function de(){return`${Date.now()}_${Math.random().toString(36).slice(2)}`}function fe(){let e=de();return pe(e),e}function pe(e){We.has(e)||We.set(e,[]),Ge.has(e)||Ge.set(e,0),Ke.has(e)||Ke.set(e,null)}function me(e){return Ke.get(e)??null}function he(e){let t=Ge.get(e)??0;return Ge.set(e,t+1),t}function ge(e,t){return`${e}:${String(t).padStart(12,`0`)}`}function _e(e){return new Blob([e]).size}function ve(){try{let e=window.localStorage;for(let t of Object.keys(e))t.indexOf(ae)===0&&e.removeItem(t)}catch(e){console.error(`Storage is blocked`,e)}}var v=new class{constructor(){h(this,`_db`,null),h(this,`_dbPromise`,null),h(this,`_dbName`,se),h(this,`_supported`,this.isSupported())}get supported(){return this._supported}open(){return this.isSupported()?(this._dbPromise||(this._dbPromise=new Promise(e=>{let t=window.indexedDB.open(this._dbName,ce);t.onupgradeneeded=()=>{this.createSchema(t.result)},t.onsuccess=()=>{this._db=t.result,this._supported=!0,this._db.onversionchange=()=>{this.close()},e(this._db)},t.onerror=()=>{console.warn(`Failed to open debug log storage`,t.error),this._supported=!1,this._dbPromise=null,e(null)},t.onblocked=()=>{console.warn(`Debug log storage opening is blocked`)}})),this._dbPromise):(this._supported=!1,Promise.resolve(null))}close(){this._db&&(this._db.close(),this._db=null),this._dbPromise=null}async clearForTests(){if(this._supported=this.isSupported(),this._dbName===se&&(this._dbName=`${se}-test-${Math.random().toString(36).slice(2)}`,this.close()),this._supported){let e=await this.open();if(e){let t=e.transaction([g,_],`readwrite`);t.objectStore(g).clear(),t.objectStore(_).clear(),await this.txDone(t).catch(e=>console.warn(`Failed to clear debug log storage`,e))}}this.close()}async getAllSessions(){let e=await this.open();if(!e)return[];let t=e.transaction(g,`readonly`),n=await this.requestToPromise(t.objectStore(g).getAll());return await this.txDone(t),n}async getSessionsByConversationId(e){let t=await this.open();if(!t)return[];let n=t.transaction(g,`readonly`),r=await this.requestToPromise(n.objectStore(g).index(`conversationId`).getAll(e));return await this.txDone(n),r.sort((e,t)=>e.startTime-t.startTime)}async getSessionBySessionId(e){let t=await this.open();if(!t)return[];let n=t.transaction(g,`readonly`),r=await this.requestToPromise(n.objectStore(g).get(e));return await this.txDone(n),r?[r]:[]}async getChunksBySession(e){let t=await this.open();if(!t)return[];let n=t.transaction(_,`readonly`),r=await this.requestToPromise(n.objectStore(_).index(`sessionId`).getAll(e));return await this.txDone(n),r.sort((e,t)=>e.sequence-t.sequence)}async putSession(e){let t=await this.open();if(!t)return!1;let n=t.transaction(g,`readwrite`);return n.objectStore(g).put(e),await this.txDone(n),!0}async putSessionAndChunk(e,t){let n=await this.open();if(!n)return!1;let r=n.transaction([g,_],`readwrite`);return r.objectStore(g).put(e),r.objectStore(_).put(t),await this.txDone(r),!0}async updateSessionConversationId(e,t){let[n]=await this.getSessionBySessionId(e);n&&await this.putSession({...n,conversationId:t,updatedAt:Math.max(n.updatedAt,Date.now())})}async deleteSession(e){let t=await this.open();if(!t)return 0;let n=await this.getChunksBySession(e),r=t.transaction([g,_],`readwrite`),i=r.objectStore(_),a=0;for(let e of n)a+=e.bytes,i.delete(e.id);return r.objectStore(g).delete(e),await this.txDone(r),a}async deleteChunks(e){let t=await this.open();if(!t||!e.length)return;let n=t.transaction(_,`readwrite`),r=n.objectStore(_);for(let t of e)r.delete(t.id);await this.txDone(n)}async estimateStorage(){return navigator.storage?.estimate?navigator.storage.estimate().catch(()=>null):null}async getStorageSummary(){let e=await this.getAllSessions();return{sessions:e,callsCount:this.groupSessions(this.getCallSessions(e)).length,usedBytes:e.reduce((e,t)=>e+t.bytes,0)}}async enforceRetentionPolicy(){let e=await this.getAllSessions(),t=this.groupSessions(this.getCallSessions(e)),n=this.getGlobalSessions(e),r=e.reduce((e,t)=>e+t.bytes,0);for(;r>re&&n.length;){let e=n.shift();if(!e)break;r-=await this.deleteSession(e.sessionId)}for(;t.length>ie||t.length>1&&r>re;){let e=t.shift();if(!e)return;for(let t of e.sessions)r-=await this.deleteSession(t.sessionId)}t.length===1&&r>re&&await this.trimOldestChunks(t[0],r-re),e=await this.getAllSessions(),t=this.groupSessions(this.getCallSessions(e)),n=this.getGlobalSessions(e),(t.length>ie||e.reduce((e,t)=>e+t.bytes,0)>re)&&await this.enforceRetentionPolicy()}createSchema(e){if(!e.objectStoreNames.contains(g)){let t=e.createObjectStore(g,{keyPath:`sessionId`});t.createIndex(`conversationId`,`conversationId`,{unique:!1}),t.createIndex(`updatedAt`,`updatedAt`,{unique:!1})}e.objectStoreNames.contains(_)||e.createObjectStore(_,{keyPath:`id`}).createIndex(`sessionId`,`sessionId`,{unique:!1})}isSupported(){return typeof window<`u`&&!!window.indexedDB}requestToPromise(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}txDone(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}getCallKey(e){return e.conversationId||e.sessionId}getCallSessions(e){return e.filter(e=>e.conversationId!==null)}getGlobalSessions(e){return e.filter(e=>e.conversationId===null).sort((e,t)=>e.updatedAt===t.updatedAt?e.startTime===t.startTime?e.sessionId.localeCompare(t.sessionId):e.startTime-t.startTime:e.updatedAt-t.updatedAt)}groupSessions(e){let t=new Map;for(let n of e){let e=this.getCallKey(n),r=t.get(e);r||(r={key:e,sessions:[],bytes:0,startTime:n.startTime,updatedAt:0},t.set(e,r)),r.sessions.push(n),r.bytes+=n.bytes,r.startTime=Math.min(r.startTime,n.startTime),r.updatedAt=Math.max(r.updatedAt,n.updatedAt)}return Array.from(t.values()).sort((e,t)=>e.updatedAt===t.updatedAt?e.startTime===t.startTime?e.key.localeCompare(t.key):e.startTime-t.startTime:e.updatedAt-t.updatedAt)}async updateSessionFromChunks(e){let t=await this.getChunksBySession(e.sessionId);if(!t.length){await this.deleteSession(e.sessionId);return}let n=t.reduce((e,t)=>e+t.bytes,0),r=t.reduce((e,t)=>e+t.items.length,0),i=t[0].startTime,a=t[t.length-1].endTime;await this.putSession({...e,startTime:i,endTime:a,updatedAt:a,bytes:n,entriesCount:r})}async trimOldestChunks(e,t){let n=[];for(let t of e.sessions){let e=await this.getChunksBySession(t.sessionId);n.push(...e.map(e=>({...e,session:t})))}n.sort((e,t)=>e.startTime===t.startTime?e.sequence-t.sequence:e.startTime-t.startTime);let r=n.slice(0,Math.max(n.length-1,0)),i=0,a=new Map,o=[];for(let e of r)if(o.push(e),i+=e.bytes,a.set(e.sessionId,e.session),i>=t)break;await this.deleteChunks(o);for(let e of a.values())await this.updateSessionFromChunks(e);return i}};async function ye(e){return e.sessionId?v.getSessionBySessionId(e.sessionId):e.conversationId?v.getSessionsByConversationId(e.conversationId):[]}async function be(e,t,n,r){if(!r.length)return;let i=me(e)||t,a=r,o=JSON.stringify(a),s=_e(o);for(;s>re&&a.length>1;)a=a.slice(Math.floor(a.length/2)),o=JSON.stringify(a),s=_e(o);if(s>re)return;let c=a[0].t,l=a[a.length-1].t,[u]=await v.getSessionBySessionId(e),d=u||{sessionId:e,conversationId:i,startTime:c,endTime:l,updatedAt:l,bytes:0,entriesCount:0},f={...d,conversationId:i||d.conversationId,startTime:Math.min(d.startTime,c),endTime:Math.max(d.endTime,l),updatedAt:Math.max(d.updatedAt,l),bytes:d.bytes+s,entriesCount:d.entriesCount+a.length},p={id:ge(e,n),sessionId:e,sequence:n,startTime:c,endTime:l,bytes:s,items:a};await v.putSessionAndChunk(f,p)&&await v.enforceRetentionPolicy()}function xe(e){let t=new WeakSet;try{return JSON.parse(JSON.stringify(e,(e,n)=>{if(n instanceof Error||typeof n==`bigint`||typeof n==`function`||typeof n==`symbol`)return String(n);if(n&&typeof n==`object`){if(t.has(n))return`[Circular]`;t.add(n)}return n}))}catch{return e.map(e=>String(e))}}function Se(e){let t=We.get(e);if(!t?.length)return Ye;let n=t.splice(0),r=me(e),i=he(e);return Ye=Ye.then(()=>be(e,r,i,n)).catch(e=>{console.warn(`Failed to write debug log to storage`,e)}),Ye}function Ce(e){if(e)return Se(e);for(let e of We.keys())Se(e);return Ye}async function we(e){let t=[];for(let n of e.sort((e,t)=>e.startTime-t.startTime)){let e=await v.getChunksBySession(n.sessionId);for(let n of e)t.push(...n.items)}return t}async function Te(e){let t=await we(e);if(!t.length)return t;let n=t.sort(De),r=n[0].t,i=n[n.length-1].t;return[...await Ee(r,i,new Set(e.map(e=>e.sessionId))),...n].sort(De)}async function Ee(e,t,n){let r=(await v.getAllSessions()).filter(r=>!n.has(r.sessionId)&&r.conversationId===null&&r.endTime>=e-le&&r.startTime<=t),i=[];for(let n of r){let r=await v.getChunksBySession(n.sessionId);for(let n of r)n.endTime<e-le||n.startTime>t||i.push(...n.items.filter(n=>n.t>=e-le&&n.t<=e?!0:n.t>=e&&n.t<=t&&ue.has(n.l)))}return i}function De(e,t){return e.t-t.t}function Oe(e,t){let n=document.createElement(`a`),r=new Blob([e],{type:`text/json`}),i=URL.createObjectURL(r);n.href=i,n.download=t,n.click(),URL.revokeObjectURL(i)}function ke(){Ce()}function Ae(){document.visibilityState===`hidden`&&Ce()}function je(e,t,n=qe){Ue||Me(),pe(n);let r=new Date,i={t:r.getTime(),l:e,d:xe(t),h:r.toLocaleString(`ru-RU`,{dateStyle:`short`,timeStyle:`long`})};return We.get(n)?.push(i),Je||(Je=window.setTimeout(()=>{Je=null,Ce()},oe)),i}function Me(){Ue||(Ue=!0,ve(),v.open(),window.addEventListener(`pagehide`,ke),document.addEventListener(`visibilitychange`,Ae))}function Ne(){return Ue||Me(),Ce(),fe()}function Pe(e,t=qe){t&&(pe(t),Ke.set(t,e),e&&v.updateSessionConversationId(t,e))}async function Fe(){return await Ce(),(await v.getAllSessions()).sort((e,t)=>t.updatedAt-e.updatedAt)}async function Ie(e){return await Ce(),Te(await ye(e))}async function Le(e){return JSON.stringify(await Ie(e))}async function Re(e){let t=await Le(e),n=`logs_${e.sessionId||e.conversationId}_${Date.now()}.json`;return Oe(t,n),n}async function ze(e){await Ce();let t=e?await ye(e):await v.getAllSessions();for(let e of t)await v.deleteSession(e.sessionId)}async function Be(){await Ce();let e=await v.getStorageSummary(),t=await v.estimateStorage();return{supported:v.supported,callsCount:e.callsCount,sessionsCount:e.sessions.length,usedBytes:e.usedBytes,maxBytes:re,maxCalls:ie,quotaBytes:t?.quota,usageBytes:t?.usage}}async function Ve(){await Ce();let e=await we(await v.getAllSessions());return JSON.stringify(e.sort(De))}async function He(){let e=await Ve(),t=`logs_${Date.now()}.json`;return Oe(e,t),t}var Ue=!1,We=new Map,Ge=new Map,Ke=new Map,qe=fe(),Je=null,Ye=Promise.resolve();window.__VKCallsSDKLogs__=(e=!1)=>(Ue||Me(),e?Ve():He());var y=class e{static get sessionKey(){return e._sessionKey}static set sessionKey(t){e._sessionKey=t}static get sessionSecretKey(){return e._sessionSecretKey}static set sessionSecretKey(t){e._sessionSecretKey=t}static get accessToken(){return e._accessToken}static set accessToken(t){e._accessToken=t}static get userId(){return e._userId}static set userId(t){e._userId=t}static isEmpty(){return!e._sessionKey}static reauthorize(t){return e._reauthorizePromise||(e._reauthorizePromise=t().finally(()=>{e._reauthorizePromise=null})),e._reauthorizePromise}};h(y,`_sessionKey`,void 0),h(y,`_sessionSecretKey`,void 0),h(y,`_accessToken`,void 0),h(y,`_userId`,null),h(y,`_reauthorizePromise`,null);var b=class{constructor(){h(this,`_handlers`,{}),h(this,`_listeners`,[])}_triggerEvent(e,...t){if(Object.hasOwn(this._handlers,e))for(let n of this._handlers[e])n.apply(this,t)}addEventListener(e,t){if(typeof t!=`function`)throw Error(`Listener should be a function`);return Object.hasOwn(this._handlers,e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!Object.hasOwn(this._handlers,e))return;t||delete this._handlers[e];let n=this._handlers[e].indexOf(t);n>=0&&this._handlers[e].splice(n,1)}subscribe(e,t,n){let r=e.addEventListener(t,n);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}},x=function(e){return e.MIC_CAMERA_PERMISSION=`mic_camera`,e.CAMERA_PERMISSION=`camera`,e.MIC_PERMISSION=`mic`,e.CAMERA_ACCESS=`cameralock`,e.MIC_ACCESS=`miclock`,e.MIC_NOT_FOUND=`nomic`,e.SCREEN_PERMISSION=`screenpermission`,e.SCREEN_ACCESS=`screenlock`,e.CONNECTION=`connection`,e.NETWORK=`network`,e.UNKNOWN=`unknown`,e.UNSUPPORTED=`unsupported`,e.SIGNALING_FAILED=`signalingfailed`,e.API=`api`,e.AUTH=`auth`,e.OVERCONSTRAINED=`overconstrained`,e}(x||{}),S=function(e){return e.AUDIO=`AUDIO`,e.VIDEO=`VIDEO`,e.SCREEN_SHARING=`SCREEN_SHARING`,e.MOVIE_SHARING=`MOVIE_SHARING`,e.AUDIO_SHARING=`AUDIO_SHARING`,e.ANIMOJI=`ANIMOJI`,e}(S||{}),C=function(e){return e.ACCEPT_CONCURRENT=`callAcceptConcurrent`,e.ACCEPT_INCOMING=`callAcceptIncoming`,e.ACCEPTED_OUTGOING=`callAcceptedOutgoing`,e.ADD_PARTICIPANT=`callAddParticipant`,e.CALL_SPEC_ERROR=`callSpecError`,e.DECLINE_INCOMING=`callDeclineIncoming`,e.DEVICE_CHANGED=`callDeviceChanged`,e.DEVICES=`callDevices`,e.ERROR=`callError`,e.HANGUP=`callHangup`,e.ICE_CONNECTION_STATE=`callIceConnectionState`,e.ICE_CONNECTION_TYPE=`callIceConnectionType`,e.ICE_RESTART=`callIceRestart`,e.JOIN_CONVERSATION=`callJoinConversation`,e.MEDIA_STATUS=`callMediaStatus`,e.OUTGOING_CALL=`callStart`,e.OUTGOING_MULTIPARTY_CALL=`callStartMultiparty`,e.PAT_ALLOCATED=`patAllocate`,e.PAT_DEALLOCATED=`patDeallocate`,e.PAT_ERROR=`patError`,e.PAT_OUTDATED_RESPONSE=`patOutdatedResponse`,e.PAT_WAITING_TIME_ERROR=`patWaitingTimeError`,e.POOR_CONNECTION=`callPoorConnection`,e.PUSH=`callPush`,e.RECONNECT=`callReconnect`,e.RELAY_POLICY=`callForceRelay`,e.REMOVE_PARTICIPANT=`callRemoveParticipant`,e.SOCKET_ACTION=`callSocketAction`,e.TOPOLOGY_CHANGE_REQUESTED=`callTopologyChangeRequested`,e}(C||{}),Xe=e=>e.stop(),Ze=e=>e.getTracks().forEach(Xe),Qe=e=>e.getVideoTracks().forEach(Xe);async function $e(e,t){try{let n=typeof t.width==`number`?t.width:void 0,r=typeof t.height==`number`?t.height:void 0;await e.applyConstraints({...t,...n&&{width:{max:n,ideal:n}},...r&&{height:{max:r,ideal:r}}})}catch(e){z.warn(`setVideoConstraints failed`,e)}}var et=class{constructor(){h(this,`_cameraPermissionStatus`,void 0),h(this,`_microphonePermissionStatus`,void 0),h(this,`_listener`,void 0)}static isSupported(){return E.browserName()!==`Firefox`&&`permissions`in navigator&&`PermissionStatus`in window}async init(e){try{let[t,n]=await Promise.all([navigator.permissions.query({name:`camera`}),navigator.permissions.query({name:`microphone`})]);this._cameraPermissionStatus=t,this._microphonePermissionStatus=n,this._listener=e,this._cameraPermissionStatus.onchange=e=>this.handlePermissionChange(e),this._microphonePermissionStatus.onchange=e=>this.handlePermissionChange(e)}catch(e){z.warn(`NavigatorPermissions init error`,e)}}handlePermissionChange(e){let t=e.target;if(t instanceof PermissionStatus){let{name:e,state:n}=t;switch(e){case`audio_capture`:this._listener(`microphone`,n);break;case`video_capture`:this._listener(`camera`,n);break}}}getPermissionState(e){switch(e){case`camera`:return this._cameraPermissionStatus?.state??null;case`microphone`:return this._microphonePermissionStatus?.state??null}return null}},tt=`_okcls_`,nt=(()=>{try{let e=Date.now().toString(),t=window.localStorage,n=!1;return t.setItem(e,e),n=t.getItem(e)===e,t.removeItem(e),n?t:null}catch{return null}})();function rt(e){let t=nt?nt.getItem(tt+e):null;if(t===null)return null;try{return JSON.parse(t)}catch{return null}}function it(e,t){try{nt&&nt.setItem(tt+e,JSON.stringify(t))}catch{}}function at(e){nt&&nt.removeItem(tt+e)}var ot;(function(e){function t(e){return rt(e)||null}e.get=t;function n(e,t){it(e,t)}e.set=n;function r(e){at(e)}e.remove=r})(ot||(ot={}));var w=ot,st=null,ct=null,lt=null,ut=[],dt=[],ft=[],pt=null,mt=null,ht=null,gt=!1,_t=!1,vt,yt,bt,xt=null,St=null,Ct=``,wt=null,Tt=[],Et=null,Dt=navigator.appVersion,Ot=navigator.appName,kt=navigator.userAgent,At={};function jt(e,t){return Number(t.deviceId===`default`)-Number(e.deviceId===`default`)}var Mt=function(e){return e.USER=`user`,e.ENVIRONMENT=`environment`,e}({});(function(e){function t(e){return Object.values(Mt).includes(e)}e.contains=t})(Mt||(Mt={}));var Nt=class{constructor(e,t=!1,n=N.videoMaxWidth,r=N.videoMaxHeight,i=N.videoFrameRate){h(this,`audio`,void 0),h(this,`video`,void 0),h(this,`needVideo`,void 0),h(this,`lastSimplifyWasReached`,void 0),h(this,`supportedConstraints`,void 0),h(this,`isVideoRequested`,()=>this.needVideo),this.supportedConstraints=navigator.mediaDevices.getSupportedConstraints();let a=!1;if(e){a={noiseSuppression:N.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let t=T.getMicrophones(),n,r;if(mt&&(r=mt.groupId,n=mt.deviceId),typeof e==`string`)r=t.find(t=>t.deviceId===e)?.groupId,n=e;else if(!mt&&T.os()===`MacOS`&&t.find(e=>e.label.includes(`iPhone`))){let e=t.find(e=>!e.label.includes(`Virtual`)&&!e.label.includes(`iPhone`));e&&(r=e.groupId,n=e.deviceId)}r&&this.supportedConstraints.groupId?a.groupId={exact:r}:n&&(a.deviceId={exact:n})}let o=!1;if(t){o={width:{min:N.videoMinWidth,max:n,ideal:n},height:{min:N.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:N.videoAspectRatio},frameRate:{ideal:i}};let e=T.getCameras(),a,s;if(pt&&(s=pt.groupId,a=pt.deviceId),typeof t==`string`)s=e.find(e=>e.deviceId===t)?.groupId,a=t;else if(!pt&&T.os()===`MacOS`&&e.find(e=>e.label.includes(`iPhone`))){let t=e.find(e=>!e.label.includes(`Virtual`)&&!e.label.includes(`iPhone`));t&&(s=t.groupId,a=t.deviceId)}s&&this.supportedConstraints.groupId?o.groupId={exact:s}:a&&(o.deviceId={exact:a}),N.videoFacingMode&&(o.facingMode={ideal:N.videoFacingMode},delete o.deviceId,delete o.groupId)}this.audio=a,this.video=o,this.needVideo=!!o,this.lastSimplifyWasReached=!1}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.groupId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.groupId,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||this.audio.groupId)&&(delete this.audio.deviceId,delete this.audio.groupId)),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.audio&&!this.video&&(this.lastSimplifyWasReached=!0,this.audio=!this.isVideoRequested(),this.video=this.isVideoRequested()),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.groupId)||this.video;return!!(typeof this.audio==`object`&&(this.audio.deviceId||this.audio.groupId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)&&!this.lastSimplifyWasReached}isVideo(){return!!this.video}isAudio(){return!!this.audio}},Pt=class extends Nt{constructor(e,t,n,r){if(super(!1,!0),h(this,`captureController`,void 0),this.captureController=`CaptureController`in window?new CaptureController:null,typeof this.video==`object`?(delete this.video.deviceId,delete this.video.groupId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode,delete this.video.width,delete this.video.height):this.video={},this.video.cursor=`motion`,e&&(this.video.width=e),t&&(this.video.height=t),this.video.frameRate=n,this.video.displaySurface=N.displaySurface,T.browserName()===`Safari`){let n=Number(T.browserVersion());n===16?(e&&(this.video.width={max:e}),t&&(this.video.height={max:t})):n===17&&(delete this.video.width,delete this.video.height)}r&&(this.audio={noiseSuppression:!1,echoCancellation:!1,autoGainControl:!1})}getNative(){return Object.assign(super.getNative(),{systemAudio:N.audioShareSystemInclude?`include`:`exclude`,windowAudio:N.audioShareWindowInclude?`include`:`exclude`,controller:this.captureController})}},Ft=class e{constructor(){h(this,`_lockId`,Math.round(Math.random()*99998)+1)}busy(t=null){if(e._lockId)throw t?.log(C.ERROR,`change_device`),z.warn(`Device change failed: MediaSource is busy`),Error(`MediaSource is busy`);e._lockId=this._lockId}free(){e._lockId===this._lockId&&(e._lockId=0)}};h(Ft,`_lockId`,0);async function It(){_t=!1,gt=!1,st=null;let e={camera:T.getSavedCamera(),microphone:T.getSavedMicrophone(),output:T.getSavedOutput()};await Rt(),Lt(`devicechange`,e),R.onDeviceChange()}function Lt(e,...t){if(At[e])for(let n of At[e])n(...t)}async function Rt(){return st||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!ct&&navigator.mediaDevices.addEventListener&&(ct=M.debounce(It,N.enumerateDevicesDelay),navigator.mediaDevices.addEventListener(`devicechange`,ct)),!lt&&et.isSupported()&&(lt=new et,await lt.init((e,t)=>{switch(t){case`denied`:case`prompt`:ct?.();break}})),st=navigator.mediaDevices.enumerateDevices().then(e=>{ut=e.filter(e=>e.kind===`videoinput`?((e.label||lt?.getPermissionState(`camera`)===`granted`)&&(gt=!0),!0):!1),ut.sort(jt),dt=e.filter(e=>e.kind===`audioinput`?((e.label||lt?.getPermissionState(`microphone`)===`granted`)&&(_t=!0),!0):!1),dt.sort(jt),ft=e.filter(e=>e.kind===`audiooutput`),ft.sort(jt);let t=pt?.deviceId??w.get(`videoinput`),n=mt?.deviceId??w.get(`audioinput`),r=ht?.deviceId??w.get(`audiooutput`);return pt=ut.find(e=>e.deviceId===t)||null,mt=dt.find(e=>e.deviceId===n)||null,ht=ft.find(e=>e.deviceId===r)||ft[0]||null,st=Promise.resolve(e),e}).catch(()=>(st=null,[]))))}async function zt(){if(`userAgentData`in navigator)try{let{platformVersion:e}=await navigator.userAgentData.getHighEntropyValues([`platformVersion`]);if(!e){z.warn(`Can't to get OS version`);return}let t=parseInt(e.split(`.`)[0]);wt=isNaN(t)?null:t}catch(e){z.warn(`Failed to get OS version`,e)}}function Bt(e){if(pt&&mt)return;let t=(e,t)=>{let n=t.getSettings()?.deviceId;return e.find(e=>e.deviceId===n||e.label===t.label)||null};e?.getTracks().forEach(e=>{!mt&&e.kind===A.audio?mt=t(T.getMicrophones(),e):!pt&&e.kind===A.video&&(pt=t(T.getCameras(),e))})}async function Vt(e,t,n=z,r=null){n.debug(`Try to get media`,JSON.parse(JSON.stringify(e.getNative())));let i=(!e.isVideo()||T.hasCameraPermission())&&(!e.isAudio()||T.hasMicrophonePermission());!i&&!t&&R.onPermissionsRequested();let a=new Ft;try{a.busy(r);let t=await navigator.mediaDevices.getUserMedia(e.getNative());return T.releaseFirefoxMicrophonePermissionWarmup(),a.free(),i||await It(),Bt(t),t}catch(i){switch(a.free(),n.error(`getUserMedia error`,i),i.name){case`PermissionDeniedError`:case`PermissionDismissedError`:case`NotAllowedError`:case`SecurityError`:case`DOMException`:case`NotFoundError`:t=e.isVideoRequested()?x.CAMERA_PERMISSION:x.MIC_PERMISSION;break;case`OverconstrainedError`:t=x.OVERCONSTRAINED;break;case`TypeError`:t=x.UNKNOWN;break;case`AbortError`:case`NotReadableError`:t=e.isVideoRequested()?x.CAMERA_ACCESS:x.MIC_ACCESS;break;case`Error`:if(i.message===`MediaSource is busy`){t=e.isVideoRequested()?x.CAMERA_ACCESS:x.MIC_ACCESS;break}}if(e.canSimplify())return Vt(e.simplify(),t,n,r);let o=t||x.UNKNOWN;throw R.onPermissionsError(o,i),o}}async function Ht(e=z){if(!(xt||T.browserName()!==`Firefox`||!navigator.mediaDevices?.getUserMedia))try{T.hasMicrophonePermission()||R.onPermissionsRequested(),xt=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(t){e.warn(`Firefox microphone permission warmup failed`,t)}}async function Ut(e,t=z,n=null){t.debug(`Try to get screen`,JSON.parse(JSON.stringify(e.getNative())));let r=new Ft;try{r.busy(n);let i=await navigator.mediaDevices.getDisplayMedia(e.getNative()),a=i?.getVideoTracks()[0];if(a){let n=a.getSettings()?.displaySurface;if(t.debug(`Got display media track: ${a.id} (${n})`),a.contentHint=`text`,e.captureController&&(n===`browser`||n===`window`))try{e.captureController.setFocusBehavior(`no-focus-change`)}catch(e){t.warn(`Failed to set focus behavior`,e)}}return i}catch(e){switch(e.name){case`PermissionDeniedError`:case`NotAllowedError`:case`SecurityError`:throw x.SCREEN_PERMISSION;case`AbortError`:case`NotReadableError`:throw x.SCREEN_ACCESS;default:throw e}}finally{r.free()}}function Wt(){return Tt.length||(Tt=(()=>{let e,t=!1,n=0,r=`0`,i=kt.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(i[1]===`Safari`){if(e=kt.match(/\bCriOS\/(\d+)/),e)return[`Chrome`,e[1],!0,Number(e[1]),r];if(e=kt.match(/\bFxiOS\/(\d+)/),e)return[`Firefox`,e[1],!1,n,r];if(e=kt.match(/\bYaBrowser\/(\d+)/),e)return[`Yandex`,e[1],!1,n,r];if(e=kt.match(/\bOPT\/(\d+)/),e)return[`Opera`,e[1],!1,n,r]}if(i[1]===`Chrome`){if(t=!0,n=Number(i[2]),e=kt.match(/\bOPR\/(\d+)/),e)return[`Opera`,e[1]||`Unknown`,t,n,r];if(e=kt.match(/\bYaBrowser\/(\d+)/),e)return[`Yandex`,e[1]||`Unknown`,t,n,r];if(e=kt.match(/\bSferum\/((\d+)(?:\.\d+)*)/),e)return[`Sferum`,e[1]||`Unknown`,t,n,r];if(e=kt.match(/\bEdge?\/(\d+)/),e)return[`Edge`,e[1]||`Unknown`,t,n,r];if(window.opr!==void 0&&/^(.+\.)?ok.ru$/.test(window.location.host))return[`Opera`,`Hidden`,t,n,r]}return e=kt.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),e&&e[2]!==void 0&&(r=e[2]),[i[2]?i[1]:Ot,e&&e[1]||i[2]||Dt,t,n,r]})()),Tt}var T;(function(e){async function t(){await Rt(),await zt()}e.init=t;function n(){return ut}e.getCameras=n;function r(){return dt}e.getMicrophones=r;function i(){return ft}e.getOutput=i;function a(){return ut.length>0}e.hasCamera=a;function o(){return dt.length>0}e.hasMicrophone=o;function s(){return pt}e.getSavedCamera=s;function c(){return mt}e.getSavedMicrophone=c;function l(){return ht}e.getSavedOutput=l;function u(){return N.videoFacingMode}e.getVideoFacingMode=u;function d(){return gt}e.hasCameraPermission=d;function f(){return _t}e.hasMicrophonePermission=f;function p(){return lt?.getPermissionState(`microphone`)??null}e.getMicrophonePermissionState=p;function m(e=!1){return f()?a()&&e?d():!0:!1}e.hasPermissions=m;function ee(){xt&&(Ze(xt),xt=null)}e.releaseFirefoxMicrophonePermissionWarmup=ee;async function te(e=!1,t=!0,n=!0,r=z,i=null){!e&&!t&&await Ht(r);let s=o()&&t,c=a()&&e,l;if(!s&&!c)l=new MediaStream;else try{l=await Vt(new Nt(s,c),void 0,r,i)}catch{l=new MediaStream}return!l.getVideoTracks().length&&n&&l.addTrack(T.getBlackMediaTrack()),!l.getAudioTracks().length&&n&&l.addTrack(T.getSilentMediaTrack()),l}e.getUserMedia=te;async function ne(e,t,n=z,r=null){return Ut(new Pt(e&&!N.consumerFastScreenShare?N.fastScreenShareWidth:0,e&&!N.consumerFastScreenShare?N.fastScreenShareHeight:0,N.getScreenFrameRate(e),t),n,r)}e.getScreenMedia=ne;async function h(e=!1,t,n=z,r=null){return Vt(new Nt(!1,!0,e?N.videoEffectMaxWidth:N.videoMaxWidth,e?N.videoEffectMaxHeight:N.videoMaxHeight,t),void 0,n,r)}e._getUserVideo=h;async function re(e,t,n=z,r=null){let i=t?.width||N.videoMaxWidth,a=t?.height||N.videoMaxHeight;return Vt(new Nt(!1,e||!0,i,a),void 0,n,r)}e.getUserVideo=re;async function ie(e,t=z,n=null){return Vt(new Nt(e||!0,!1),void 0,t,n)}e.getUserAudio=ie;async function ae(e,t){let[n]=e.getVideoTracks();if(!n)throw Error(`Video track not found in stream`);return $e(n,t)}e.setResolution=ae;async function oe(e,t){let n=(await Rt()).find(n=>n.kind===e&&n.deviceId===t);return n?(e===`videoinput`?pt=n:e===`audioinput`?mt=n:e===`audiooutput`&&(ht=n),w.set(e,t),n):null}e._saveDeviceId=oe;function se(){if(!bt||bt.readyState===`ended`){let e=T.getAudioContext(),t=e.createMediaStreamDestination(),n=e.createGain();n.gain.value=1e-5,n.connect(t),T.browserName()===`Safari`&&n.connect(e.destination);let r=e.createOscillator();r.type=`sine`,r.frequency.value=0,r.connect(n),r.start(),bt=t.stream.getAudioTracks()[0]}return Object.assign(bt.clone(),{enabled:!1})}e.getSilentMediaTrack=se;function ce(e=N.videoMinWidth,t=N.videoMinHeight){yt||(yt=document.createElement(`canvas`)),yt.width=e,yt.height=t;let n=yt.getContext(`2d`);return n.rect(0,0,e,t),n.fillStyle=`black`,n.fill(),(!vt||vt.readyState===`ended`)&&(vt=yt.captureStream(N.videoFrameRate).getVideoTracks()[0]),Object.assign(vt.clone(),{enabled:!1})}e.getBlackMediaTrack=ce;function g(){return _()===null}e.isBrowserSupported=g;function _(){try{let e=window;return e.navigator.mediaDevices?`getUserMedia`in e.navigator.mediaDevices?e.RTCPeerConnection?e.RTCIceCandidate?e.RTCSessionDescription?e.HTMLCanvasElement?e.HTMLCanvasElement.prototype.captureStream?e.RTCRtpSender?e.RTCRtpSender.prototype.replaceTrack?e.RTCRtpSender.prototype.getParameters?`sendBeacon`in e.navigator?null:`send-beacon-unavailable`:`rtp-sender-get-parameters-unavailable`:`rtp-sender-replace-track-unavailable`:`rtp-sender-unavailable`:`canvas-capture-stream-unavailable`:`html-canvas-unavailable`:`rtc-session-description-unavailable`:`rtc-ice-candidate-unavailable`:`rtc-peer-connection-unavailable`:`get-user-media-unavailable`:`media-devices-unavailable`}catch{return`support-check-failed`}}e.getBrowserSupportFailure=_;function le(){return!!navigator.mediaDevices.getDisplayMedia}e.isScreenCapturingSupported=le;function ue(){let e=T.browserName()===`Opera`,t=T.browserName()===`Yandex`;return e||t}e.isBrokenH264Decoder=ue;function de(){return T.browserName()===`Yandex`&&T.os()===`Windows`||N.simulcast}e.isBrokenVP9Encoder=de;function fe(){let e=T.browserName()===`Safari`&&Number(T.browserVersion())===17&&[4,5,6].includes(Number(T.browserSubVersion())),t=T.osVersion(),n=T.os()===`Windows`&&t!=null&&t>0&&t<13;return e||n}e.isBrokenVP9Decoder=fe;function pe(){return!(T.baseChromeVersion()&&T.isMobile())}e.canPreferH264=pe;function me(){let e=T.browserName(),t=Number(T.browserVersion());return e===`Safari`?t>=18:e===`Firefox`?t>=134:!0}e.isSimulcastSupportedByBrowser=me;function he(){return Ct||(Ct=(()=>{let e={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 t in e)if(Object.hasOwn(e,t)&&e[t].test(kt))return t;return`Unknown`})()),Ct}e.os=he;function ge(){return wt}e.osVersion=ge;function _e(){return St===null&&(St=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Dt)),St}e.isMobile=_e;function ve(){return Wt()[0]}e.browserName=ve;function v(){return Wt()[1]}e.browserVersion=v;function ye(){return Wt()[3]}e.baseChromeVersion=ye;function be(){return Et||(Et=new(window.AudioContext||window.webkitAudioContext)),Et.resume().catch(()=>{z.warn(`Failed to resume AudioContext`)}),Et}e.getAudioContext=be;function xe(){return Wt()[4]}e.browserSubVersion=xe;function Se(){return T.baseChromeVersion()>=105&&!T.isMobile()}e.isAudioShareSupported=Se;function Ce(e,t){At[e]||(At[e]=[]),At[e].push(t)}e.addEventListener=Ce;function we(e,t){if(At[e])if(!t)delete At[e];else{let n=At[e].indexOf(t);n>-1&&At[e].splice(n,1)}}e.removeEventListener=we})(T||(T={}));var E=T;function Gt(e,t){return!(e.isAudioEnabled!==t.isAudioEnabled||e.isVideoEnabled!==t.isVideoEnabled||e.isScreenSharingEnabled!==t.isScreenSharingEnabled||e.isFastScreenSharingEnabled!==t.isFastScreenSharingEnabled||e.isAudioSharingEnabled!==t.isAudioSharingEnabled||e.isAnimojiEnabled!==t.isAnimojiEnabled)}function D(e){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,isFastScreenSharingEnabled:!1,isAudioSharingEnabled:!1,isAnimojiEnabled:!1},e||{})}var O=function(e){return e.CANCELED=`CANCELED`,e.REJECTED=`REJECTED`,e.REMOVED=`REMOVED`,e.HUNGUP=`HUNGUP`,e.MISSED=`MISSED`,e.BUSY=`BUSY`,e.FAILED=`FAILED`,e.NETWORK_ERROR=`NETWORK_ERROR`,e.KILLED=`KILLED`,e.BANNED=`BANNED`,e.HAS_ACTIVE_CALL=`HAS_ACTIVE_CALL`,e.CALLER_IS_BLOCKED=`CALLER_IS_BLOCKED`,e.NOT_FRIENDS=`NOT_FRIENDS`,e.CALLEE_IS_OFFLINE=`CALLEE_IS_OFFLINE`,e.CALLEE_UNAVAILABLE=`CALLEE_UNAVAILABLE`,e.CALLER_IS_REJECTED=`CALLER_IS_REJECTED`,e.UNKNOWN_ERROR=`UNKNOWN_ERROR`,e.UNSUPPORTED=`UNSUPPORTED`,e.SERVICE_DISABLED=`SERVICE_DISABLED`,e.SERVICE_UNAVAILABLE=`SERVICE_UNAVAILABLE`,e.EXTERNAL_API_ERROR=`EXTERNAL_API_ERROR`,e.SOCKET_CLOSED=`SOCKET_CLOSED`,e.ENDED=`ENDED`,e.KILLED_WITHOUT_DELETE=`KILLED_WITHOUT_DELETE`,e.ANOTHER_DEVICE=`ANOTHER_DEVICE`,e.NOT_FOUND=`NOT_FOUND`,e.VCHAT_DETAILED_ERROR=`VCHAT_DETAILED_ERROR`,e.TIMEOUT=`TIMEOUT`,e.PARTICIPANT_LIMIT_REACHED=`PARTICIPANT_LIMIT_REACHED`,e.FAST_START_ERROR=`FAST_START_ERROR`,e.FAST_JOIN_ERROR=`FAST_JOIN_ERROR`,e.CALL_TIMEOUT=`CALL_TIMEOUT`,e.OBSOLETE_CLIENT=`OBSOLETE_CLIENT`,e}(O||{}),k=class e extends Error{constructor(t,n){super(),h(this,`message`,void 0),h(this,`hangup`,void 0),h(this,`error`,void 0),h(this,`code`,void 0),h(this,`remote`,void 0),h(this,`custom_error`,void 0),h(this,`callError`,void 0),this.name=`HangupReason`,this.code=n&&n.code||0,this.remote=n&&n.remote||!1,this.custom_error=n?.custom_error??null,this.callError=n?.callError??null,Object.values(O).indexOf(t)>-1?this.hangup=t:this.error=t;let r=[];this.error&&r.push(`error`),this.remote&&r.push(`remote`),this.code&&r.push(`code: ${this.code}`),n&&n.message&&r.push(`message: '${n.message}'`),this.message=t+(r.length?` (${r.join(`, `)})`:``),Error.captureStackTrace&&Error.captureStackTrace(this,e)}},Kt=function(e){return e.FpsLimit=`fps-limit`,e}({}),qt=class extends b{constructor(e=z){super(),h(this,`FPS_LIMITS`,[13,20,Math.max(N.videoFrameRate,25)]),h(this,`THRESHOLD`,.8),h(this,`HISTORY_LENGTH`,10),h(this,`_fpsMeterUnsubscribe`,null),h(this,`_fpsHistory`,{cursor:0,arr:[]}),h(this,`_fpsLimitCursor`,this.FPS_LIMITS.length-1),h(this,`_debug`,void 0),this._debug=e}get fpsLimit(){return this.FPS_LIMITS[this._fpsLimitCursor]}watch(e){this._cleanup();try{e&&(this._assertsVideoEffect(e),this._fpsMeterUnsubscribe=e.addFpsMeterListener(this._handleFpsMeter.bind(this)))}catch(e){this._debug.warn(`VideoEffectsFpsLimiter error`,e)}}_handleFpsMeter(e){if(this._fpsHistory.arr[this._fpsHistory.cursor]=e,this._fpsHistory.cursor=(this._fpsHistory.cursor+1)%this.HISTORY_LENGTH,this._fpsHistory.arr.length===this.HISTORY_LENGTH&&this._fpsLimitCursor){let e=this._fpsHistory.arr.reduce((e,t)=>e+t,0)/this.HISTORY_LENGTH,t=this.FPS_LIMITS[this._fpsLimitCursor];e<t*this.THRESHOLD&&(this._fpsLimitCursor=Math.max(0,this._fpsLimitCursor-1)),t!==this.fpsLimit&&this._triggerEvent(`fps-limit`,this.fpsLimit)}}_assertsVideoEffect(e){if(!(`addFpsMeterListener`in e))throw Error(`Outdated VideoEffect version`)}addEventListener(e,t){return super.addEventListener(e,t)}_cleanup(){this._fpsMeterUnsubscribe?.(),this._fpsMeterUnsubscribe=null}destroy(){this._cleanup(),super.unsubscribe()}},Jt=function(e){return e.SOURCE_CHANGED=`SOURCE_CHANGED`,e.SOURCE_READY=`SOURCE_READY`,e.TRACK_REPLACED=`TRACK_REPLACED`,e.SCREEN_STATUS=`SCREEN_STATUS`,e.ANIMOJI_STATUS=`ANIMOJI_STATUS`,e}({}),A=function(e){return e.audio=`audio`,e.video=`video`,e.screen=`screen`,e.audioshare=`audioshare`,e}({}),Yt=function(e){return e[e.CAMERA=1]=`CAMERA`,e[e.SCREEN=2]=`SCREEN`,e}({}),Xt=class extends b{constructor(e=z,t=null){super(),h(this,`_stream`,null),h(this,`_screenTrack`,null),h(this,`_audioShareTrack`,null),h(this,`_screenShareTrack`,null),h(this,`_sendVideoTrack`,null),h(this,`_cameraVideoTrack`,null),h(this,`_micAudioTrack`,null),h(this,`_audioEffectsTrack`,null),h(this,`_mediaSettings`,D()),h(this,`_lastMediaSettings`,null),h(this,`_videoStatusOnScreenCapturingEnabled`,!1),h(this,`_effect`,null),h(this,`_audioEffectParams`,null),h(this,`_onDeviceChange`,void 0),h(this,`_animojiEnabled`,!1),h(this,`_videoEffectsFpsLimiter`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_cameraTrackSetAt`,0),h(this,`_cameraMuteRecoveredAt`,0),h(this,`videoTrackMuteHandler`,()=>{!this._mediaSettings.isVideoEnabled||this._cameraMuteRecoveredAt>=this._cameraTrackSetAt||E.browserName()!==`Safari`||(this._cameraMuteRecoveredAt=Date.now(),this._logger?.log(C.ERROR,`camera_mute_recover`),this._debug.log(`[MediaSource] Safari camera mute recovery`),this.toggleVideo(!0).then(()=>this._logger?.log(C.ERROR,`camera_mute_recover_success`)).catch(e=>{this._logger?.log(C.ERROR,`camera_mute_recover_fail`),this._debug.warn(`[MediaSource] Camera mute recovery failed`,e)}))}),this._debug=e,this._logger=t,this._initDeviceChangeListener(),N.audioShare&&(this._audioShareTrack=this.getSilentAudioShareTrack()),N.enableVideoEffectsFpsDegradation&&(this._videoEffectsFpsLimiter=new qt(this._debug),this._videoEffectsFpsLimiter.addEventListener(Kt.FpsLimit,this.handleVideoEffectsLowFps.bind(this)))}get cameraVideoTrack(){return this._cameraVideoTrack}set cameraVideoTrack(e){this._cameraVideoTrack&&this._cameraVideoTrack.removeEventListener(`mute`,this.videoTrackMuteHandler),this._cameraVideoTrack=e,this._cameraVideoTrack&&(this._cameraTrackSetAt=Date.now(),this._cameraVideoTrack.addEventListener(`mute`,this.videoTrackMuteHandler)),N.consumerFastScreenShare&&(this._screenShareTrack=this.getBlackScreenShareTrack())}async request(e=[S.AUDIO],t=!0){if(this._stream)return;let n=e.includes(S.VIDEO),r=e.includes(S.AUDIO),i=e.includes(S.ANIMOJI),a=E.getBrowserSupportFailure();if(a)throw new k(x.UNSUPPORTED,{callError:{scope:`internal`,code:`environment`,description:a}});try{this._stream=await E.getUserMedia(n,r,t,this._debug,this._logger),this.cameraVideoTrack?.stop(),this.cameraVideoTrack=this._stream.getVideoTracks()[0],this._micAudioTrack?.stop(),this._micAudioTrack=this._stream.getAudioTracks()[0],this._audioEffectsTrack?.stop(),this._mediaSettings.isVideoEnabled=n&&this._stream.getVideoTracks().filter(e=>e.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=r&&this._stream.getAudioTracks().filter(e=>e.enabled).length>0||!1,this._mediaSettings.isAnimojiEnabled=i&&!this._mediaSettings.isVideoEnabled||!1,this._animojiEnabled=i,this._triggerEvent(`SOURCE_READY`)}catch(e){throw new k(e)}}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(){let e=this._stream?.getAudioTracks().filter(e=>!e.contentHint)??[];return e.find(e=>e.enabled)??e[0]??null}get isAnimojiRequested(){return this._animojiEnabled&&!this._mediaSettings.isVideoEnabled}addTrackToPeerConnection(e,t,n){let r=this.getStream(),i=this.getSendAudioTrack(),a=this.getSendVideoTrack(n);if(!r||!i&&!a&&!t)throw Error(`No local stream found`);i&&!t&&e.addTrack(i,r),a&&!t&&e.addTrack(a,r)}getMediaSettings(){return this._mediaSettings}get mediaSettings(){return this._mediaSettings}async changeDevice(e){switch(e){case`videoinput`:if(this._mediaSettings.isVideoEnabled)return this._changeVideoInput();break;case`audioinput`:if(this._mediaSettings.isAudioEnabled)return this._changeAudioInput();break;default:return Promise.reject(x.UNKNOWN)}}stopVideoTrack(){this._mediaSettings.isVideoEnabled&&(this._stopEffect(),this._stream&&Qe(this._stream),this.cameraVideoTrack?.stop())}async setVideoStream(e,t){return t?this._changeScreen(!1,!1,e):this._changeVideoInput(e)}_initDeviceChangeListener(){!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener||(this._onDeviceChange=async e=>{if(!this._stream)return;let t=E.getSavedMicrophone(),n=E.getSavedCamera(),r=this._mediaSettings.isAudioEnabled&&t?.groupId!==e.microphone?.groupId,i=this._mediaSettings.isVideoEnabled&&n?.groupId!==e.camera?.groupId;try{r&&await this._changeAudioInput(),i&&await this._changeVideoInput()}catch{}},E.addEventListener(`devicechange`,this._onDeviceChange))}_destroyDeviceChangeListener(){this._onDeviceChange&&E.removeEventListener(`devicechange`,this._onDeviceChange)}async _changeVideoInput(e){try{let t=e?`stream`:`video`,n=e||await E._getUserVideo(!!this._effect,this._frameRate,this._debug,this._logger);if(this.cameraVideoTrack?.stop(),this.cameraVideoTrack=n.getVideoTracks()[0],!this._stream)Ze(n);else{let e=await this._setEffect(this._effect,this.cameraVideoTrack);this._logger?.log(C.DEVICE_CHANGED,t),this._debug.log(`Video stream changed`),await this._replaceLocalTrack(e),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent(`SOURCE_CHANGED`,{kind:`video`})}}catch(e){throw this._logger?.log(C.ERROR,`change_video`),this._debug.warn(`Camera change failed`,e),e}}async setAudioStream(e){return this._changeAudioInput(e)}async _changeAudioInput(e=null){try{let t=e||await E.getUserAudio(void 0,this._debug,this._logger);if(this._micAudioTrack?.stop(),this._micAudioTrack=t.getAudioTracks()[0],!this._stream)Ze(t);else{let e=await this._applyAudioEffect();this._logger?.log(C.DEVICE_CHANGED,`audio`),this._debug.log(`Audio stream changed`,e),await this._replaceLocalTrack(e),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent(`SOURCE_CHANGED`,{kind:`audio`})}}catch(e){throw this._logger?.log(C.ERROR,`change_audio`),this._debug.error(`Microphone change failed`,e),e}}async _changeScreen(e,t,n){try{if(n=n||await E.getScreenMedia(e,t,this._debug,this._logger),!this._stream)Ze(n);else{let r=n.getVideoTracks()[0];if(r.addEventListener(`ended`,()=>{this._mediaSettings.isScreenSharingEnabled&&this.disableScreenCapturing()},!1),this._logger?.log(C.DEVICE_CHANGED,`screen`),this._debug.log(`Screen capturing started`),this._screenTrack=r,this._mediaSettings.isScreenSharingEnabled=!0,this._mediaSettings.isFastScreenSharingEnabled=e,N.consumerFastScreenShare&&this._mediaSettings.isFastScreenSharingEnabled&&(r.contentHint=`motion`,this._screenShareTrack=r),n.getAudioTracks().length>0){let e=n.getAudioTracks()[0];e.contentHint=`music`,this._audioShareTrack=e,await this._addLocalTrack(e),this._mediaSettings.isAudioSharingEnabled=!0}t&&!this._mediaSettings.isAudioSharingEnabled&&this._debug.debug(`Audio share requested but not captured`),this._triggerEvent(`SCREEN_STATUS`,{track:r}),this._triggerEvent(`SOURCE_CHANGED`,{kind:`screen`})}}catch(e){throw this._logger?.log(C.ERROR,`screen`),this._debug.warn(`Screen capturing failed`,e),e}}async _disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._screenShareTrack&&(this._screenShareTrack.stop(),this._screenShareTrack=this.getBlackScreenShareTrack()),await this.stopAudioShareTrack(),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._mediaSettings.isFastScreenSharingEnabled=!1,this._triggerEvent(`SCREEN_STATUS`,{track:null}),this._triggerEvent(`SOURCE_CHANGED`,{kind:`screen`}))}async stopAudioShareTrack(){if(this._audioShareTrack){let e=this.getSilentAudioShareTrack();await this._replaceTrack(this._audioShareTrack,e),this._mediaSettings.isAudioSharingEnabled=!1}}async _applyAudioEffect(){if(!N.audioEffects||!this._audioEffectParams)return N.audioEffects?.pause(),this._micAudioTrack;N.audioEffects.isInitialized||await N.audioEffects.init(),N.audioEffects.resume(),N.audioEffects.setEffects(this._audioEffectParams.effects,this._audioEffectParams.isPreset),N.audioEffects.setSource(this._micAudioTrack);let e=N.audioEffects.outputStream.getAudioTracks()[0];return(!this._audioEffectsTrack||this._audioEffectsTrack.id!==e.id)&&(this._audioEffectsTrack=e),this._audioEffectsTrack}getSilentAudioShareTrack(){let e=E.getSilentMediaTrack();return e.contentHint=`music`,e.stop(),e}getBlackScreenShareTrack(){let e=E.getBlackMediaTrack();return e.contentHint=`motion`,e.stop(),e}async _replaceLocalTrack(e,t){if(!this._stream)return;let n=this._stream.getTracks().filter(t=>t.kind===e.kind),r=n.find(t=>t.contentHint===e.contentHint)??n.find(e=>e!==this._audioEffectsTrack);r?.id!==e.id&&(r?await this._replaceTrack(r,e,t):await this._addLocalTrack(e,t))}async _replaceTrack(e,t,n){this._stream&&(e!==this._audioEffectsTrack&&e.stop(),this._stream.removeTrack(e),this._stream.addTrack(t),this._triggerEvent(`TRACK_REPLACED`,t,n))}async _addLocalTrack(e,t){this._stream&&(this._stream.addTrack(e),this._triggerEvent(`TRACK_REPLACED`,e,t))}async _setEffect(e,t){if(this._videoEffectsFpsLimiter?.watch(N.videoEffects),!N.videoEffects)return t;try{return N.videoEffects.setEffect(e,t)}catch(e){return this._debug.warn(`Video effect failed`,e),t}}_stopEffect(){if(N.videoEffects)try{N.videoEffects.stopEffect()}catch(e){this._debug.warn(`Video effect failed`,e)}}destroy(){this._destroyDeviceChangeListener(),E.releaseFirefoxMicrophonePermissionWarmup(),N.videoEffects&&(this._effect=null,N.videoEffects.destroy()),N.audioEffects&&N.audioEffects.destroy(),this._stream&&(Ze(this._stream),this._stream=null),this.cameraVideoTrack?.stop(),this._micAudioTrack?.stop(),this._audioEffectsTrack?.stop(),this._disableScreenCapture(),E.getAudioContext()?.suspend().catch(e=>this._debug.error(e)),this._videoEffectsFpsLimiter?.destroy()}async stopLocalMedia(){this._mediaSettings.isScreenSharingEnabled&&await this.disableScreenCapturing(),this._stream&&(this._lastMediaSettings={...this._mediaSettings},this._stream.getAudioTracks().length>0&&await this.toggleAudio(!1),this._stream.getVideoTracks().length>0&&await this.toggleVideo(!1),this.cameraVideoTrack=null,this._micAudioTrack=null)}async resumeLocalMedia(e){if(!this._lastMediaSettings)return;let t=[];if((e?e.isAudioEnabled:this._lastMediaSettings.isAudioEnabled)&&(t.push(S.AUDIO),await this.toggleAudio(!0)),await this.request(t),this._lastMediaSettings=null,this._stream)for(let e of this._stream.getTracks())this._triggerEvent(`TRACK_REPLACED`,e)}async toggleScreenCapturing(e){if(e.captureScreen){await this._changeScreen(e.fastScreenSharing,e.captureAudio);return}return this._disableScreenCapture()}async disableScreenCapturing(){return this.toggleScreenCapturing({captureScreen:!1,fastScreenSharing:!1,captureAudio:!1})}async toggleVideo(e){if(!this._stream)return;this.cameraVideoTrack?.stop();let t;if(e){let e=await E._getUserVideo(!!this._effect,this._frameRate,this._debug,this._logger);this.cameraVideoTrack=e.getVideoTracks()[0],t=await this._setEffect(this._effect,this.cameraVideoTrack)}else t=E.getBlackMediaTrack(N.videoMinWidth,N.videoMinHeight),this._stopEffect();if(this._mediaSettings.isVideoEnabled=e,await this._replaceLocalTrack(t),this._animojiEnabled){this._triggerEvent(`ANIMOJI_STATUS`,!e);return}this._triggerEvent(`SOURCE_CHANGED`,{kind:`video`})}async toggleAudio(e){if(!this._stream)return;this._micAudioTrack?.stop();let t=async(e,t)=>{await this._replaceLocalTrack(e),this._mediaSettings.isAudioEnabled=t,this._triggerEvent(`SOURCE_CHANGED`,{kind:`audio`})};if(e)try{let e=await E.getUserAudio(void 0,this._debug,this._logger);this._micAudioTrack=e.getAudioTracks()[0],await t(await this._applyAudioEffect(),!0)}catch(e){throw N.audioEffects?.pause(),await t(E.getSilentMediaTrack(),!1),typeof e==`string`?Error(e):e}else N.audioEffects?.pause(),await t(E.getSilentMediaTrack(),!1)}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`})}async setResolution({video:e,effect:t}){if(!this._mediaSettings.isVideoEnabled)return;if(!this._stream)throw Error(`Local stream not found`);if(!this.cameraVideoTrack)throw Error(`Local video track not found`);let n=this._effect&&t||e;await this._applyVideoConstraints(this.cameraVideoTrack,n)}getCameraVideoTrack(){return this.cameraVideoTrack}async updateNoiseSuppression(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks().find(e=>!e.contentHint);if(!e)throw Error(`Local audio track not found`);if(e.enabled)return e.applyConstraints({noiseSuppression:N.noiseSuppression})}async videoEffect(e){if(!N.videoEffects)throw Error(`Video Effects library is not set`);if(this._logger?.log(C.DEVICE_CHANGED,`effect_${e?.effect||`none`}`),!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect&&this.cameraVideoTrack){let t=this._effect;this._effect=e;try{let e=this.cameraVideoTrack.clone(),t=new MediaStream([e]);await this._applyVideoConstraints(e),await this._changeVideoInput(t)}catch(e){this._effect=t;let n=this.cameraVideoTrack.clone(),r=new MediaStream([n]);throw await this._changeVideoInput(r),e}}}async audioEffect(e){if(!N.audioEffects)throw Error(`Audio Effects library is not set`);if(!this._mediaSettings.isAudioEnabled){this._audioEffectParams=e;return}if(this._stream&&(!e&&this._audioEffectParams||e&&!this._audioEffectParams||!M.isArraysEquals(e?.effects||[],this._audioEffectParams?.effects||[]))&&this._micAudioTrack){let t=this._audioEffectParams;this._audioEffectParams=e;try{let e=this._micAudioTrack.clone(),t=new MediaStream([e]);await this._changeAudioInput(t)}catch(e){this._audioEffectParams=t;let n=this._micAudioTrack.clone(),r=new MediaStream([n]);throw await this._changeAudioInput(r),e}}}getAudioShareTrack(){return this._audioShareTrack}handleVideoEffectsLowFps(e){this._mediaSettings.isVideoEnabled&&this.cameraVideoTrack&&e<N.videoFrameRate&&this._applyVideoConstraints(this.cameraVideoTrack).catch(e=>{this._debug.warn(`MediaSource handleVideoEffectsLowFps error`,e)})}get _frameRate(){let e=this._videoEffectsFpsLimiter?.fpsLimit??N.videoFrameRate;return this._effect?Math.min(e,N.videoFrameRate):void 0}async _applyVideoConstraints(e,t){await $e(e,{width:this._effect?N.videoEffectMaxWidth:N.videoMaxWidth,height:this._effect?N.videoEffectMaxHeight:N.videoMaxHeight,...this._frameRate&&{frameRate:{ideal:this._frameRate}},...t})}getScreenShareTrack(){return this._screenShareTrack}},j=function(e){return e.USER=`USER`,e.GROUP=`GROUP`,e}(j||{}),Zt={HEIGHT:720,WIDTH:1280,BITRATE:1e6,FPS:30},Qt=60,$t=`L1T2`,en=1.35,tn=[{dimension:320,bitrate:18e4},{dimension:520,bitrate:4e5},{dimension:640,bitrate:5e5},{dimension:960,bitrate:9e5},{dimension:1280,bitrate:12e5},{dimension:1920,bitrate:25e5},{dimension:2560,bitrate:35e5},{dimension:3840,bitrate:5e6}];function nn(e,t){return!e||!t?e===t:e.streams.length===t.streams.length?e.streams.every((e,n)=>{let r=t.streams[n];return e.rid===r.rid&&e.width===r.width&&e.height===r.height&&e.fps===r.fps&&e.bitrate===r.bitrate}):!1}function rn(e,t){for(let n of t)if(e<=n.dimension)return n.bitrate;return t.length>0?t[t.length-1].bitrate:tn[0].bitrate}function an(e){return!Number.isFinite(e)||e<=0?Zt.FPS:Math.min(Math.round(e),Qt)}function on(e=Zt.WIDTH,t=Zt.HEIGHT,n=tn,r=Zt.FPS){let i=Math.max(e,t),a=an(r),o=1;i>=960?o=3:i>=480&&(o=2);let s=[`h`,`m`,`l`].slice(3-o),c=[],l=rn(i,n);for(let r=0;r<o;r++){let i=s[r];c.push({rid:i,width:e,height:t,fps:a,bitrate:l}),e=Math.round(e/2),t=Math.round(t/2),l=rn(Math.max(e,t),n)}return{streams:c.reverse()}}function sn(e,t){let n=t.streams.findIndex(t=>t.rid===e);return n>=0?2**(t.streams.length-n-1):1}function cn(e,t,n,r){let i=n?Math.round(n*en):1/0;if(e.forEach(e=>{let n=t.streams.find(t=>t.rid===e.rid);e.scaleResolutionDownBy=sn(e.rid,t),e.scalabilityMode=$t,n?(e.active=n.rid===`l`||Math.max(n.width,n.height)<i,e.maxBitrate=n.bitrate,e.maxFramerate=n.fps):(e.active=!1,e.maxBitrate=0,delete e.maxFramerate)}),r)for(let n=t.streams.length-1;n>=0;n--){let{rid:i}=t.streams[n],a=e.find(e=>e.rid===i);if(a?.active){a.maxBitrate=r;break}}}var ln=typeof Object.fromEntries==`function`?Object.fromEntries:function(e){if(!e||!e[Symbol.iterator])throw Error(`Object.fromEntries() requires a single iterable argument`);let t={};for(let[n,r]of e)t[n]=r;return t};async function un(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>{t(e.target?.result)},r.onerror=n,r.readAsArrayBuffer(e)})}var dn=/\r?\n/;function fn(e){return e.split(dn)}function pn(e){return e.join(`\r
|
|
8
|
-
`)}var
|
|
9
|
-
`+pn(t)),e}function p(e){let n=t(e,`red`);n.length>0&&r(e,`audio`,[],n)}return i?c(s,`H264`,`local`,`decoder`):l(s,n),a&&u(s),p(s),o&&f(s),pn(s)}e.patchLocalSDP=f;function p(e,t,n,r,i,o){let s=fn(e);return n?a(s,`H264`):t&&l(s,t),i&&o?a(s,`VP9`):i?c(s,`VP9`,`remote`,`encoder`):o?c(s,`VP9`,`remote`,`decoder`):r&&u(s),d(s),pn(s)}e.patchRemoteSDP=p;function m(e){return e?`${e.type||`WEB_SOCKET`}_${e.id}`:`_`}e.getPeerIdString=m;function ee(e,t){return e&&e.id===t.id&&(e.type||`WEB_SOCKET`)===(t.type||`WEB_SOCKET`)}e.comparePeerId=ee;async function te(e){let t={local:null,remote:null};if(!e||!e.getStats)return t;try{let n=await e.getStats(null),r=null;if(n.forEach(e=>{e.type===`transport`&&e.selectedCandidatePairId?r=n.get(e.selectedCandidatePairId):e.type===`candidate-pair`&&e.state===`succeeded`&&!r&&(!Object.hasOwn(e,`selected`)||e.selected)&&(r=e)}),r?.localCandidateId){let e=n.get(r.localCandidateId);e&&(t.local={type:e.candidateType,ip:e.ip||e.ipAddress,port:e.port||e.portNumber})}if(r?.remoteCandidateId){let e=n.get(r.remoteCandidateId);e&&(t.remote={type:e.candidateType,ip:e.ip||e.ipAddress,port:e.port||e.portNumber})}return t}catch{return t}}e.getPeerConnectionHostInfo=te;let ne=/^-?[0-9]+$/,h=/^([gu])(-?[0-9]+)$/;function re(e,t=j.USER){let n=String(e);return h.test(n)?(z.warn(`Already composite id [${e}] type supplied [${t}]`),n):t===j.GROUP?`g`+n:t===j.USER?`u`+n:(z.warn(`Unknown type [${t}] for id [${e}]`),n.match(ne)?`u`+n:n)}e.composeUserId=re;function ie(e,t,n=0){return ae(re(e,t),n)}e.composeParticipantId=ie;function ae(e,t){return t?e+`:d`+t:e}e.compose=ae;function oe(e){return ie(e.id,e.idType||j.USER,e.deviceIdx)}e.composeId=oe;function se(e){if(e.decorativeUserId)return ie(e.decorativeUserId,e.idType||j.USER,e.deviceIdx)}e.composeDecorativeId=se;function ce(e){return e.participant?oe(e.participant):ie(e.participantId,e.participantType||j.USER,e.deviceIdx)}e.composeMessageId=ce;function g(e){return typeof e==`string`?_(le(e).compositeUserId).id:e}e.extractOkId=g;function _(e){let t=String(e),n=t.match(h);return n?{id:Number(n[2]),type:n[1]===`g`?j.GROUP:j.USER}:(z.warn(`Unsupported compositeId [${e}]`),{id:Number(t),type:j.USER})}e.decomposeId=_;function le(e){let t=e.split(`:d`);return{compositeUserId:t[0],deviceIdx:t.length>1?parseInt(t[1],10):0}}e.decomposeParticipantId=le;function ue(){let e=window.crypto?.randomUUID?.();if(e)return e;let t=`0123456789abcdefghijklmnopqrstuvwxyz`.split(``),n=Array(36),r=0,i,a;for(a=0;a<36;a++)a===8||a===13||a===18||a===23?n[a]=`-`:a===14?n[a]=`4`:(r<=2&&(r=33554432+Math.random()*16777216|0),i=r&15,r>>=4,n[a]=t[a===19?i&3|8:i]);return n.join(``)}e.uuid=ue;function de(e,t){let n;function r(...r){let i=this;n&&window.clearTimeout(n),n=window.setTimeout(()=>{e.apply(i,r)},t)}return r}e.debounce=de;function fe(e){if(!window.BigInt)return null;let t=``,n=fn(e);for(let e of n)if(e.startsWith(`a=fingerprint`)){let n=e.split(` `);if(n.length===2){t=n[1];break}}if(!t)return BigInt(-1);let r=t.split(`:`),i=BigInt(0);for(let e=Math.min(7,r.length-1);e>=0;e--){let t=BigInt(parseInt(r[e],16));i<<=BigInt(8),i|=t}return BigInt.asIntN(64,i)}e.sdpFingerprint=fe;async function pe(e,{signal:t}={}){return new Promise((n,r)=>{if(t?.aborted)return r(t.reason);let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(t?.reason)};t?.addEventListener(`abort`,a,{once:!0})})}e.delay=pe;function me(e,t,n,r=z){let i=[];return e.getSenders().forEach(e=>he(t,e,e.track,n,i,r)),i}e.applySettings=me;function he(e,t,n,r,i,a=z){if(!RTCRtpSender.prototype.getParameters||!RTCRtpSender.prototype.setParameters||!e||!n||n.kind!==A.video)return;let o=n.getSettings();if(!o)return;let s=e.maxBitrateK?e.maxBitrateK*1024:null,c=o.width,l=o.height,u=c&&l&&e.maxDimension?Math.max(1,Math.max(c,l)/e.maxDimension):null,d=e.maxFramerate||null;if(c&&l&&e.maxDimension&&e.maxDimension>Math.max(c,l)){let e=Math.round(c*l/256),t=(Math.round(e*mn/1e4)+1)*1e4;s=s===null?t:Math.min(t,s)}let f=e.degradationPreference||`balanced`,p=r[n.id];if(p&&p.bitrate===s&&p.scaleResolutionDownBy===u&&p.maxFramerate===d&&p.degradationPreference===f){i[n.id]=p;return}i[n.id]={bitrate:s,scaleResolutionDownBy:u,maxFramerate:d,degradationPreference:f};let m=t.getParameters();if(m.encodings||(m.encodings=[{}]),m.encodings.length>1&&c&&l&&e.maxDimension){let t=Math.round(e.maxDimension*1.35),n=e.bitrates?.generic?.length?e.bitrates.generic:void 0,r=o.frameRate||30,i=on(c,l,n,d?Math.min(r,d):r);a.log(`applyVideoTrackSettings: maxDim=${e.maxDimension} targetDim=${t} track=${c}x${l} sim=${JSON.stringify(i)}`),cn(m.encodings,i,e.maxDimension,n?void 0:s??void 0)}else m.encodings.forEach(t=>{e?.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),s?t.maxBitrate=s:delete t.maxBitrate,u?t.scaleResolutionDownBy=u:delete t.scaleResolutionDownBy,d?t.maxFramerate=d:delete t.maxFramerate});m.degradationPreference=f,m.encodings.length>0&&t.setParameters?.(m).then(()=>{let e=t.getParameters();a.log(`applyVideoTrackSettings: actual encodings= ${JSON.stringify(e.encodings)}`)},e=>{a.error(`Failed to set sender parameters`,m,e)})}e.applyVideoTrackSettings=he;function ge(e,t){Array.isArray(t)||(t=[t]);for(let n of t)if(e.includes(n))return!0;return!1}e.includesOneOf=ge;function _e(e){return Object.entries(e.participantState?.state||{}).reduce((t,[n,r])=>(e.participantState&&(t[n]={ts:e.participantState.stateUpdateTs[n],state:r}),t),{})}e.mapParticipantState=_e;function ve(e){let t=e.map(e=>({uid:e.externalId,mediaSettings:e.mediaSettings,status:e.connectionStatus.lastEffective,muteStates:e.muteStates,unmuteOptions:e.unmuteOptions,participantState:e.participantState,markers:e.markers,movieShareInfos:e.movieShareInfos,roles:e.roles}));return N.filterObservers?t.filter(e=>!e.uid.observer):t}e.mapSharedParticipants=ve;function v(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let i of n)if(!Object.hasOwn(r,i)||e[i].state!==t[i].state||e[i].ts!==t[i].ts)return!1;return!0}e.isEqualParticipantState=v;function ye(e,t,n=!1){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let i of r){if(!Object.hasOwn(t,i))return!1;let r=e[i],a=t[i];if(n&&Te(r)&&Te(a))return ye(r,a,n);if(r!==a)return!1}return!0}e.isObjectsEquals=ye;function be(e,t){if(e.length!==t.length)return!1;for(let n of e)if(t.indexOf(n)<0)return!1;return!0}e.isArraysEquals=be;function xe(e){return!Object.keys(e).length}e.isEmptyObject=xe;function Se(e,t){if(!e&&!t)return 0;if(!e||!t)return e?-1:1;return r(t.rank,e.rank)||r(e.ts,t.ts)||n(e,t);function n(e,t){let n={[j.USER]:0,[j.GROUP]:1},{compositeUserId:i,deviceIdx:a}=le(e.id),{compositeUserId:o,deviceIdx:s}=le(t.id),{id:c,type:l}=_(i),{id:u,type:d}=_(o);return r(n[l],n[d])||r(c,u)||r(a,s)}function r(e,t){return e<t?-1:e===t?0:1}}e.participantMarkerCompare=Se;function Ce(e,t){return ln(Object.entries(e).filter(([,e])=>Array.isArray(t)?!t.includes(e):e!==t))}e.objectFilterOutValues=Ce;function we(e,t,n){let r=n;for(let n in e)Object.hasOwn(e,n)&&(r=t(r,e[n],n));return r}e.objectReduce=we,e.setImmediate=(()=>{let e=1,t={},n=null;return typeof MessageChannel<`u`&&(n=new MessageChannel,n.port1.onmessage=e=>{let n=e.data;t[n]&&(t[n](),delete t[n])}),function(r){if(n&&document.visibilityState===`hidden`){let i=e;return e=e>=2**53-1?1:e+1,t[i]=r,n.port2.postMessage(i),()=>{t[i]&&delete t[i]}}let i=setTimeout(r,0);return()=>clearTimeout(i)}})();function Te(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}e.isObject=Te})(_n||(_n={}));var M=_n,vn=`__CALLS_SDK_DEVTOOLS_`,yn=class{set(e,t){try{this.getStorage().setItem(vn+e,JSON.stringify(t))}catch(t){z.warn(`DevTools: Failed to save option`,e,t)}}get(e){try{let t=this.getStorage().getItem(vn+e);return t===null?null:JSON.parse(t)}catch(t){return z.warn(`DevTools: Failed to read option`,e,t),null}}remove(e){try{this.getStorage().removeItem(vn+e)}catch(t){z.warn(`DevTools: Failed to remove option`,e,t)}}clear(){try{let e=this.getStorage(),t=Object.keys(e);for(let n of t)n.startsWith(vn)&&e.removeItem(n)}catch(e){z.warn(`DevTools: Failed to clear options`,e)}}getAll(){try{let e=this.getStorage(),t=Object.keys(e),n={};for(let r of t)if(r.startsWith(vn)){let t=r.substring(21),i=e.getItem(r);if(i!==null)try{n[t]=JSON.parse(i)}catch{}}return n}catch(e){return z.warn(`DevTools: Failed to get all options`,e),{}}}getStorage(){return window.localStorage}},bn=class{constructor(e){h(this,`storage`,void 0),this.storage=e}set(e,t){this.storage.set(e,t),console.debug(`DevTools: ${String(e)} override set to ${t}`)}get(e){return this.storage.get(e)}clear(e){this.storage.remove(e),console.debug(`DevTools: ${String(e)} override cleared`)}clearAll(){this.storage.clear(),console.debug(`DevTools: All overrides cleared`)}getAll(){return this.storage.getAll()}applyOverrides(e){let t=this.getAll(),n={...e},r=Object.keys(t);if(r.length>0){console.debug(`DevTools: Current overrides:`,t);for(let e of r)t[e]!==void 0&&(n[e]=t[e]);console.debug(`DevTools: Overrides applied`)}return n}},xn=class e{static getInstance(){return e.instance||(e.instance=new e),e.instance}constructor(){h(this,`params`,void 0),h(this,`storage`,void 0),this.storage=new yn,this.params=new bn(this.storage)}};h(xn,`instance`,null);var Sn=xn.getInstance(),N=class e{static set(t){Object.hasOwn(t,`voiceParams`)&&(Object.assign(e._params.voiceParams,t.voiceParams),delete t.voiceParams),Object.hasOwn(t,`specListenerParams`)&&(Object.assign(e._params.specListenerParams,t.specListenerParams),delete t.specListenerParams),Object.hasOwn(t,`apiAuth`)&&(y.accessToken=t.apiAuth.accessToken,y.sessionKey=t.apiAuth.sessionKey,y.sessionSecretKey=t.apiAuth.sessionSecretKey);let n=Sn.params.applyOverrides(t);Object.assign(e._params,M.objectFilterOutValues(n,void 0))}static getScreenFrameRate(t){return t?e._params.fastScreenShareFrameRate:e._params.screenFrameRate}static get(t){return e._params[t]}static get appName(){return`ok.calls.sdk.js`}static get appVersion(){return e._params.appVersion}static get apiClientVersion(){return 1.1}static get sdkVersion(){return`2.8.13-dev.d26e27ad.0`}static get debug(){return e._params.debug}static get protocolVersion(){return e._params.joinFromMultipleDevices?6:5}static get platform(){return e._params.platform}static set platform(t){e._params.platform=t}static get clientStatsPlatform(){return e._params.clientStatsPlatform}static set clientStatsPlatform(t){e._params.clientStatsPlatform=t}static get autoStartStats(){return e._params.autoStartStats}static get statQueueEnabled(){return e._params.statQueueEnabled}static get clientType(){return e._params.clientType}static set clientType(t){e._params.clientType=t}static get externalUserType(){return e._params.externalUserType}static set externalUserType(t){e._params.externalUserType=t}static get device(){return e._params.device}static get apiKey(){return e._params.apiKey}static get apiEnv(){return e._params.apiEnv}static get apiBaseUrl(){return e._params.apiBaseUrl}static set apiBaseUrl(t){e._params.apiBaseUrl=t}static apiEndpoint(t){switch(t??e.apiEnv){case`AUTO`:case`PROD`:return`https://api.mycdn.me`;case`CALLS`:return`https://calls.okcdn.ru`;case`PROD_OK`:return`https://api.ok.ru`;case`TEST`:return`https://apitest.ok.ru/api`;case`VIDEOTEST`:return`https://videotestapi.ok.ru/api`;case`CALLSTEST`:return`https://calls-test.okcdn.ru/api`;case`CALLS_BETA`:return`https://api-beta.calls-test.oneme.ru/api`;case`CALLS_BENDER`:return`https://api-bender.calls-test.oneme.ru/api`;case`CALLS_MAMES`:return`https://calls-mames.okcdn.ru/api`;case`CALLS_MARS`:return`https://api-mars.calls-test.oneme.ru/api`;default:return e._params.apiEnv}}static get apiTimeout(){return e._params.apiTimeout}static get apiMaxAttempt(){return e._params.apiMaxAttempt}static get authToken(){return e._params.authToken}static set authToken(t){e._params.authToken=t}static get anonymToken(){return e._params.anonymToken}static set anonymToken(t){e._params.anonymToken=t}static get domain(){return e._params.domain}static get externalDomain(){return e._params.externalDomain}static get iceServers(){return e._params.iceServers}static set iceServers(t){e._params.iceServers=t}static get wssBase(){return e._params.wssBase}static set wssBase(t){e._params.wssBase=t}static get wtsBase(){return e._params.wtsBase}static set wtsBase(t){e._params.wtsBase=t}static get wssToken(){return e._params.wssToken}static set wssToken(t){e._params.wssToken=t}static get signalingReconnectDelay(){return e._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return e._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return e._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return e._params.waitConnectionDelay}static get waitResponseDelay(){return e._params.waitResponseDelay}static get waitMessageDelay(){return e._params.waitMessageDelay}static get waitAnotherTabDelay(){return e._params.waitAnotherTabDelay}static get calleeUnavailableWaitingTime(){return e._params.calleeUnavailableWaitingTime}static get debugLog(){return e._params.debugLog}static get forceRelayPolicy(){return e._params.forceRelayPolicy}static set forceRelayPolicy(t){e._params.forceRelayPolicy=t}static get videoMinWidth(){return e._params.videoMinWidth}static get videoMaxWidth(){return e._params.videoMaxWidth}static set videoMaxWidth(t){e._params.videoMaxWidth=t}static get videoMinHeight(){return e._params.videoMinHeight}static get videoMaxHeight(){return e._params.videoMaxHeight}static set videoMaxHeight(t){e._params.videoMaxHeight=t}static get videoAspectRatio(){return e._params.videoAspectRatio}static get videoFrameRate(){return e._params.videoFrameRate}static get videoFacingMode(){return e._params.videoFacingMode||(E.isMobile()?Mt.USER:null)}static set videoFacingMode(t){e._params.videoFacingMode=t}static get displaySurface(){return e._params.displaySurface}static get audioEffects(){return e._params.audioEffects}static set audioEffects(t){e._params.audioEffects=t,e._params.audioEffects?.setLogger((e,...t)=>z.send(e,...t))}static get vad(){return e._params.vad}static set vad(t){e._params.vad=t}static get vadOptions(){return e._params.vadOptions}static set vadOptions(t){e._params.vadOptions=t}static get videoEffects(){return e._params.videoEffects}static set videoEffects(t){e._params.videoEffects=t,e._params.videoEffects?.setLogger((e,...t)=>z.send(e,...t))}static get videoEffectMaxWidth(){return e._params.videoEffectMaxWidth}static set videoEffectMaxWidth(t){e._params.videoEffectMaxWidth=t}static get videoEffectMaxHeight(){return e._params.videoEffectMaxHeight}static set videoEffectMaxHeight(t){e._params.videoEffectMaxHeight=t}static get vmoji(){return e._params.vmoji?.isBrowserSupported()?e._params.vmoji:null}static set vmoji(t){e._params.vmoji=t}static get vmojiOptions(){return e._params.vmojiOptions||{protocolVersion:1,renderingOptions:{}}}static set vmojiOptions(t){e._params.vmojiOptions=t}static get voiceParams(){return e._params.voiceParams}static get specListenerParams(){return e._params.specListenerParams}static get iceRestartWaitTime(){return e._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return e._params.transportConnectionWaitTime}static get statisticsInterval(){return e._params.statisticsInterval}static set statisticsInterval(t){e._params.statisticsInterval=t}static get networkStatisticsInterval(){return e._params.networkStatisticsInterval}static get perfStatReportEnabled(){return e._params.perfStatReportEnabled}static get callStatReportEnabled(){return e._params.callStatReportEnabled}static get enableLogPerfStatReport(){return e._params.enableLogPerfStatReport}static get asrDataChannel(){return e._params.asrDataChannel}static get consumerScreenDataChannelPacketSize(){return e._params.consumerScreenDataChannelPacketSize}static get screenShareWebmBuilder(){return e._params.screenShareWebmBuilder}static get noiseSuppression(){return e._params.noiseSuppression}static get preferH264(){return e._params.preferH264}static get preferVP9(){return e._params.preferVP9}static get audioNack(){return e._params.audioNack}static get movieShare(){return e._params.movieShare&&e.videoTracksCount>0}static get videoTracksCount(){return Number(e._params.videoTracksCount)}static get requestDisplayLayoutThrottleMs(){return Number(e._params.requestDisplayLayoutThrottleMs)}static get breakVideoPayloadTypes(){return e._params.breakVideoPayloadTypes}static get useCallsToContacts(){return e._params.useCallsToContacts}static get useParticipantListChunk(){return e._params.useParticipantListChunk&&e.videoTracksCount>0}static get useRooms(){return e._params.useRooms}static get useChatRooms(){return e._params.useChatRooms}static get addParticipant(){return e._params.addParticipant}static get waitForAdminInGroupCalls(){return e._params.waitForAdminInGroupCalls}static get hold(){return e._params.hold}static get maxParallelCalls(){return e._params.maxParallelCalls}static get participantListChunkInitIndex(){return e._params.participantListChunkInitIndex??0}static get participantListChunkInitCount(){return e._params.participantListChunkInitCount??null}static get filterObservers(){return e._params.filterObservers}static get muteMode(){return e._params.muteMode}static get preserveAudioTracks(){return e._params.preserveAudioTracks}static get audioShare(){return E.isAudioShareSupported()&&e._params.audioShare}static get audioShareWindowInclude(){return e._params.audioShareWindowInclude}static get audioShareSystemInclude(){return e._params.audioShareSystemInclude}static get fastScreenShare(){return e._params.fastScreenShare}static get screenShareCongestionControl(){return e._params.screenShareCongestionControl}static get screenShareCongestionControlThreshold(){return e._params.screenShareCongestionControlThreshold}static get fastScreenShareWidth(){return e._params.fastScreenShareWidth}static get fastScreenShareHeight(){return e._params.fastScreenShareHeight}static get consumerFastScreenShare(){return e._params.consumerFastScreenShare}static get consumerFastScreenShareQualityOnDemand(){return e._params.consumerFastScreenShareQualityOnDemand}static get videoSuspend(){return e._params.videoSuspend}static get enumerateDevicesDelay(){return e._params.enumerateDevicesDelay}static get switchVideoAtBadNetwork(){return e._params.switchVideoAtBadNetwork}static get enableVideoEffectsFpsDegradation(){return e._params.enableVideoEffectsFpsDegradation}static get simulcast(){return E.isSimulcastSupportedByBrowser()&&e._params.simulcast}static get webtransport(){return e._params.webtransport}static get waitForRecordResponse(){return e._params.waitForRecordResponse}static get transparentAudio(){return e._params.transparentAudio}static get enableSessionStateUpdates(){return e._params.enableSessionStateUpdates}static get safariAudioElement(){return e._params.safariAudioElement}static get forwardEmptyIceCandidate(){return e._params.forwardEmptyIceCandidate}static toJSON(){return{apiKey:e._params.apiKey,apiEnv:e._params.apiEnv,audioShare:e._params.audioShare,audioShareWindowInclude:e._params.audioShareWindowInclude,audioShareSystemInclude:e._params.audioShareSystemInclude,useCallsToContacts:e._params.useCallsToContacts,useParticipantListChunk:e._params.useParticipantListChunk,useRooms:e._params.useRooms,useChatRooms:e._params.useChatRooms,addParticipant:e._params.addParticipant,fastScreenShare:e._params.fastScreenShare,participantListChunkInitCount:e._params.participantListChunkInitCount,screenShareCongestionControl:e._params.screenShareCongestionControl,screenShareCongestionControlThreshold:e._params.screenShareCongestionControlThreshold,videoTracksCount:e._params.videoTracksCount,requestDisplayLayoutThrottleMs:e._params.requestDisplayLayoutThrottleMs,asrDataChannel:e._params.asrDataChannel,videoMaxHeight:e._params.videoMaxHeight,videoMaxWidth:e._params.videoMaxWidth,videoEffectMaxHeight:e._params.videoEffectMaxHeight,videoEffectMaxWidth:e._params.videoEffectMaxWidth,videoSuspend:e._params.videoSuspend,debugLog:e._params.debugLog,callStatReportEnabled:e._params.callStatReportEnabled,joinFromMultipleDevices:e._params.joinFromMultipleDevices,movieShare:e._params.movieShare,clientType:e._params.clientType,clientStatsPlatform:e._params.clientStatsPlatform,appVersion:e._params.appVersion,autoStartStats:e._params.autoStartStats,statQueueEnabled:e._params.statQueueEnabled,consumerScreenDataChannelPacketSize:e._params.consumerScreenDataChannelPacketSize,switchVideoAtBadNetwork:e._params.switchVideoAtBadNetwork,simulcast:e._params.simulcast,webtransport:e._params.webtransport,waitForRecordResponse:e._params.waitForRecordResponse,transparentAudio:e._params.transparentAudio,enableSessionStateUpdates:e._params.enableSessionStateUpdates,safariAudioElement:e._params.safariAudioElement,forwardEmptyIceCandidate:e._params.forwardEmptyIceCandidate}}};h(N,`_params`,{platform:`WEB`,clientStatsPlatform:``,appVersion:`0.0.0`,autoStartStats:!0,statQueueEnabled:!1,clientType:`PORTAL`,externalUserType:``,device:`browser`,apiKey:``,authToken:``,anonymToken:``,apiEnv:`AUTO`,apiBaseUrl:null,domain:``,externalDomain:``,iceServers:[],wssBase:``,wtsBase:``,wssToken:``,signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:10,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,debug:!1,apiTimeout:5e3,apiMaxAttempt:10,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoFacingMode:null,displaySurface:`monitor`,audioEffects:null,vad:null,vadOptions:{},videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,vmoji:null,vmojiOptions:null,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,enableLogPerfStatReport:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},asrDataChannel:!1,consumerScreenDataChannelPacketSize:64*1024,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!1,audioNack:!0,videoTracksCount:30,requestDisplayLayoutThrottleMs:750,movieShare:!1,useCallsToContacts:!1,useParticipantListChunk:!1,useRooms:!1,useChatRooms:!1,addParticipant:!1,waitForAdminInGroupCalls:!1,hold:!1,maxParallelCalls:2,participantListChunkInitIndex:0,participantListChunkInitCount:null,breakVideoPayloadTypes:!1,joinFromMultipleDevices:!1,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1,audioShare:!1,audioShareWindowInclude:!1,audioShareSystemInclude:!1,fastScreenShare:!1,screenShareCongestionControl:!1,screenShareCongestionControlThreshold:2100,consumerFastScreenShare:!1,consumerFastScreenShareQualityOnDemand:!1,fastScreenShareFrameRate:24,fastScreenShareWidth:1280,fastScreenShareHeight:720,videoSuspend:!1,enumerateDevicesDelay:2e3,switchVideoAtBadNetwork:!1,enableVideoEffectsFpsDegradation:!1,simulcast:!1,webtransport:!1,waitForRecordResponse:!1,transparentAudio:!1,enableSessionStateUpdates:!1,safariAudioElement:!0,forwardEmptyIceCandidate:!1});var P=function(e){return e.WAITING_HALL=`WAITING_HALL`,e.WAIT_FOR_ADMIN=`WAIT_FOR_ADMIN`,e.WAITING=`WAITING`,e.CONNECTING=`CONNECTING`,e.CONNECTED=`CONNECTED`,e.RECONNECT=`RECONNECT`,e.ERROR=`ERROR`,e.HANGUP=`HANGUP`,e.PERMISSIONS=`PERMISSIONS`,e.ONHOLD=`ONHOLD`,e}({});function F(e,...t){let n=N.get(e);typeof n==`function`&&setTimeout(n,0,...t)}function I(e,t,...n){if(N.filterObservers){if(Array.isArray(t)){if(t=t.filter(e=>!e.observer),!t.length)return}else if(t.observer)return}F(e,t,...n)}function L(e){return Object.assign({},e)}function Cn(e){return e.slice()}var wn;(function(e){function t(e,t,n){F(`onLocalStream`,e,L(t),n)}e.onLocalStream=t;function n(e,t,n){F(`onScreenStream`,e,L(t),n)}e.onScreenStream=n;function r(e,t,n){F(`onVmojiStream`,e,L(t),n)}e.onVmojiStream=r;function i(e,t){F(`onVmojiError`,e,t)}e.onVmojiError=i;function a(e,t,n){F(`onLocalStreamUpdate`,L(e),t,n)}e.onLocalStreamUpdate=a;function o(e,t){z.debug(`Local status:`,e),F(`onLocalStatus`,e,t)}e.onLocalStatus=o;function s(e,t,n){I(`onRemoteStream`,e,t,n)}e.onRemoteStream=s;function c(e,t,n){I(`onRemoteLive`,e,t,n)}e.onRemoteLive=c;function l(e,t,n){I(`onLocalLive`,e,t,n)}e.onLocalLive=l;function u(e,t,n){I(`onRemoteLiveUpdate`,e,t,n)}e.onRemoteLiveUpdate=u;function d(e,t,n){I(`onLocalLiveUpdate`,e,t,n)}e.onLocalLiveUpdate=d;function f(e,t,n){I(`onRemoteScreenStream`,e,t,n)}e.onRemoteScreenStream=f;function p(e,t,n){I(`onRemoteVmojiStream`,e,t,n)}e.onRemoteVmojiStream=p;function m(e,t,n,r){I(`onRemoteStreamSuspended`,e,t,n,r)}e.onRemoteStreamSuspended=m;function ee(e,t,n,r,i,a){I(`onConversation`,e,L(t),L(n),r,i,a)}e.onConversation=ee;function te(e,t){e&&F(`onConversationParticipantListChunk`,e,t)}e.onConversationParticipantListChunk=te;function ne(e,t,n,r){I(`onRemoteMediaSettings`,e,L(t),n,r)}e.onRemoteMediaSettings=ne;function h(e,t,n){I(`onLocalMediaSettings`,e,L(t),n)}e.onLocalMediaSettings=h;function re(e,t,n,r){I(`onRemoteSharedMovieInfo`,e,L(t),n,r)}e.onRemoteSharedMovieInfo=re;function ie(e,t,n,r){I(`onRemoteSharedMovieStoppedInfo`,e,L(t),n,r)}e.onRemoteSharedMovieStoppedInfo=ie;function ae(e,t,n,r){I(`onLocalSharedMovieInfo`,e,L(t),n,r)}e.onLocalSharedMovieInfo=ae;function oe(e,t,n,r){I(`onLocalSharedMovieStoppedInfo`,e,L(t),n,r)}e.onLocalSharedMovieStoppedInfo=oe;function se(e,t,n,r){I(`onRemoteSharedUrl`,e,t,n,r)}e.onRemoteSharedUrl=se;function ce(e,t,n){I(`onParticipantAdded`,e,t,n)}e.onParticipantAdded=ce;function g(e,t,n){I(`onParticipantJoined`,e,t,n)}e.onParticipantJoined=g;function _(e,t=!1,n){F(`onLocalParticipantState`,L(e),t,n)}e.onLocalParticipantState=_;function le(e,t,n,r){I(`onRemoteParticipantState`,e,L(t),n,r)}e.onRemoteParticipantState=le;function ue(e,t,n){F(`onRemoteParticipantsState`,e,t,n)}e.onRemoteParticipantsState=ue;function de(e,t,n=null,r){z.debug(`Remote status:`,t,e),I(`onRemoteStatus`,e,t,n,r)}e.onRemoteStatus=de;function fe(){F(`onPermissionsRequested`)}e.onPermissionsRequested=fe;function pe(e,t){F(`onPermissionsError`,e,t)}e.onPermissionsError=pe;function me(e,t,n){I(`onRemoteRemoved`,e,t,n)}e.onRemoteRemoved=me;function he(e,t,n,r){F(`onCallState`,e,t,L(n),r)}e.onCallState=he;function ge(e,t,n){F(`onDeviceSwitched`,e,t,n)}e.onDeviceSwitched=ge;function _e(e,t,n,r=!1,i=!1,a=null,o=null,s,c,l=null,u){let d=c?Cn(c):void 0;F(`onMuteStates`,L(e),Cn(t),Cn(n),r,i,a,o,s,d,l,u)}e.onMuteStates=_e;function ve(e,t,n=!1,r){I(`onRolesChanged`,e,Cn(t),n,r)}e.onRolesChanged=ve;function v(e,t=!1,n){F(`onLocalRolesChanged`,Cn(e),t,n)}e.onLocalRolesChanged=v;function ye(e,t,n,r,i){I(`onPinnedParticipant`,e,t,n,r,i)}e.onPinnedParticipant=ye;function be(e,t,n){F(`onLocalPin`,e,t,n)}e.onLocalPin=be;function xe(e,t){F(`onOptionsChanged`,Cn(e),t)}e.onOptionsChanged=xe;function Se(e){F(`onCallAccepted`,e)}e.onCallAccepted=Se;function Ce(e){F(`onCallActive`,e)}e.onCallActive=Ce;function we(e,t,n){I(`onAcceptedCall`,e,t,n)}e.onAcceptedCall=we;function Te(e){F(`onRateNeeded`,e)}e.onRateNeeded=Te;function Ee(e,t){I(`onSpeakerChanged`,e,t)}e.onSpeakerChanged=Ee;function De(e,t){F(`onVolumesDetected`,Cn(e),t)}e.onVolumesDetected=De;function Oe(e,t){F(`onLocalVolume`,e,t)}e.onLocalVolume=Oe;function ke(e,t,n){F(`onJoinStatus`,e,t,n)}e.onJoinStatus=ke;function Ae(e,t){F(`onHangup`,e,t)}e.onHangup=Ae;function je(e){F(`onMultipartyChatCreated`,L(e))}e.onMultipartyChatCreated=je;function Me(){F(`onDeviceChange`)}e.onDeviceChange=Me;function Ne(e){F(`onFingerprintChange`,e)}e.onFingerprintChange=Ne;function Pe(){F(`onTokenExpired`)}e.onTokenExpired=Pe;function Fe(e,t,n=!1,r){F(`onChatMessage`,e,t,n,r)}e.onChatMessage=Fe;function Ie(e,t,n=!1,r){F(`onCustomData`,e,t,n,r)}e.onCustomData=Ie;function Le(e,t,n,r,i,a,o=null,s){F(`onRecordStarted`,e,t,n,r,i,a,o,s)}e.onRecordStarted=Le;function Re(e=null,t,n){F(`onRecordStopped`,e,t,n)}e.onRecordStopped=Re;function ze(e,t){F(`onLocalNetworkStatusChanged`,e,t)}e.onLocalNetworkStatusChanged=ze;function Be(e,t){F(`onNetworkStatusChanged`,e,t)}e.onNetworkStatusChanged=Be;function Ve(e,...t){F(`onDebugMessage`,e,...t)}e.onDebugMessage=Ve;function He(e,t,...n){F(`onDebugMessageWithContext`,e,t,...n)}e.onDebugMessageWithContext=He;function Ue(e,t){F(`onStatistics`,Object.assign({},e,{memory:t}))}e.onStatistics=Ue;function We(){F(`onAutoplayError`)}e.onAutoplayError=We;function Ge(e,t,n,r,i,a){F(`onChatRoomUpdated`,e,t,n,r,i,a)}e.onChatRoomUpdated=Ge;function Ke(e,t){F(`onPromoted`,e,t)}e.onPromoted=Ke;function qe(e,t){F(`onRemoteMixedAudioStream`,e,t)}e.onRemoteMixedAudioStream=qe;function Je(e,t){F(`onJoinLinkChanged`,e,t)}e.onJoinLinkChanged=Je;function Ye(e,t){F(`onRoomsUpdated`,e,t)}e.onRoomsUpdated=Ye;function y(e,t,n,r,i){F(`onRoomUpdated`,e,t,n,r,i)}e.onRoomUpdated=y;function b(e,t){F(`onRoomParticipantsUpdated`,e,t)}e.onRoomParticipantsUpdated=b;function x(e,t){F(`onRoomSwitched`,e,t)}e.onRoomSwitched=x;function S(e,t){F(`onRoomStart`,e,t)}e.onRoomStart=S;function C(e,t=null,n){F(`onFeedback`,e,t,n)}e.onFeedback=C;function Xe(e,t){F(`onFeaturesPerRoleChanged`,e,t)}e.onFeaturesPerRoleChanged=Xe;function Ze(e,t){F(`onParticipantVmojiUpdate`,e,t)}e.onParticipantVmojiUpdate=Ze;function Qe(e,t,n){F(`onAsrSet`,e,t,n)}e.onAsrSet=Qe;function $e(e,t,n,r){F(`onAsrStarted`,e,t,n,r)}e.onAsrStarted=$e;function et(e,t){F(`onAsrStopped`,e,t)}e.onAsrStopped=et;function tt(e,t,n,r,i){F(`onAsrTranscription`,e,t,n,r,i)}e.onAsrTranscription=tt;function nt(e,t,n){F(`onParticipantIdChanged`,e,t,n)}e.onParticipantIdChanged=nt;function rt(e,t){F(`onVideoSuspendSuggest`,e,t)}e.onVideoSuspendSuggest=rt;function it(e){F(`onSignalingMessage`,typeof e==`string`?e:L(e))}e.onSignalingMessage=it;function at(e,t){F(`onPromotionApproved`,e,t)}e.onPromotionApproved=at;function ot(e,t){F(`onPeerRegistered`,e,t)}e.onPeerRegistered=ot;function w(e,t){F(`onNonFatalError`,e,t)}e.onNonFatalError=w})(wn||(wn={}));var R=wn,Tn=function(e){return e.DEBUG=`DEBUG`,e.LOG=`LOG`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),En;(function(e){let t=`📞`,n=()=>({sessionId:null,conversationId:null}),r=(e,t,...n)=>{R.onDebugMessage(t,...n),R.onDebugMessageWithContext(t,{conversationId:e.conversationId},...n)},i=console.debug.bind(console,t),a=console.log.bind(console,t),o=console.warn.bind(console,t),s=console.error.bind(console,t),c=!1;function l(e){if(!e)return n();try{return e()}catch{return n()}}function u(e,t,n){let u=l(n);if(N.debugLog&&je(e,t,u.sessionId||void 0),c)switch(e){case`DEBUG`:i(...t);break;case`LOG`:a(...t);break;case`WARN`:o(...t);break;case`ERROR`:s(...t);break}else r(u,e,...t)}function d(...e){u(`DEBUG`,e)}e.debug=d;function f(...e){u(`LOG`,e)}e.log=f;function p(...e){u(`WARN`,e)}e.warn=p;function m(...e){u(`ERROR`,e)}e.error=m;function ee(){return c}e.enabled=ee;function te(e){c=e,N.debugLog&&Me()}e.toggle=te;function ne(e,...t){switch(e){case`DEBUG`:d(...t);break;case`LOG`:f(...t);break;case`WARN`:p(...t);break;case`ERROR`:m(...t);break}}e.send=ne;function h(e){return{debug:(...t)=>u(`DEBUG`,t,e),log:(...t)=>u(`LOG`,t,e),warn:(...t)=>u(`WARN`,t,e),error:(...t)=>u(`ERROR`,t,e)}}e.createLogger=h;function re(e=null){let t=null,n=e;function r(){!N.debugLog||t||(t=Ne(),n&&Pe(n,t))}let i=()=>(r(),{sessionId:t,conversationId:n});return{get sessionId(){return t},get conversationId(){return n},setConversationId(e){n=e,t&&Pe(n,t)},send:(e,...t)=>u(e,t,i),debug:(...e)=>u(`DEBUG`,e,i),log:(...e)=>u(`LOG`,e,i),warn:(...e)=>u(`WARN`,e,i),error:(...e)=>u(`ERROR`,e,i)}}e.createSessionLogger=re;function ie(e,...t){}e.test=ie})(En||(En={}));var z=En,B=new class{constructor(){h(this,`_conversations`,new Map),h(this,`_reserved`,new Set),h(this,`_activeId`,null),h(this,`_mutex`,!1),h(this,`_pendingRemovals`,new Set)}reserve(e){if(this._conversations.has(e)||this._reserved.has(e))throw Error(`CallRegistry: conversation ${e} already exists`);this._reserved.add(e)}add(e){let t=e.id;if(this._conversations.has(t)){z.warn(`CallRegistry: conversation ${t} already exists, skip duplicate add`),this._reserved.delete(t);return}this._conversations.set(t,e),this._reserved.delete(t)}remove(e){if(e){if(this._reserved.delete(e),this._mutex){this._pendingRemovals.add(e);return}this._conversations.delete(e),this._activeId===e&&(this._activeId=null)}}get(e){return this._conversations.get(e)}getActive(){return this._activeId?this._conversations.get(this._activeId)??null:null}getFirst(){return this._conversations.values().next().value??null}getActiveId(){return this._activeId}has(e){return this._conversations.has(e)||this._reserved.has(e)}getAll(){return Array.from(this._conversations.values())}get callsLength(){return this._conversations.size}async setActive(e){if(!(this._activeId===e||!this._conversations.has(e)||this._mutex)){this._mutex=!0;try{let t=this.getActive(),n;if(t){n=t.mediaSettings;try{await t.hold(!0)}catch(e){throw z.error(`Can't hold previous active, error: ${e}`),Error(`Cannot switch call: hold failed`)}}this._conversations.has(e)&&(this._activeId=e,R.onCallActive(e));let r=this._conversations.get(e);if(r&&r?.isCallHeld)try{await r.hold(!1,n)}catch(e){throw z.error(`Can't hold next active, error: ${e}`),Error(`Cannot switch call: hold failed`)}}finally{this._mutex=!1,this._flushPendingRemovals()}}}async setHold(e){if(!(this._activeId!==e||!this._conversations.has(e)||this._mutex)){this._mutex=!0;try{let e=this.getActive();if(e)try{await e.hold(!0)}catch(e){throw z.error(`Can't hold previous active, error: ${e}`),Error(`Cannot switch call: hold failed`)}this._activeId=null}finally{this._mutex=!1,this._flushPendingRemovals()}}}async switchCall(e){this._activeId===e?await this.setHold(e):await this.setActive(e)}clear(){this._conversations.clear(),this._reserved.clear(),this._pendingRemovals.clear(),this._activeId=null}_flushPendingRemovals(){if(this._pendingRemovals.size!==0){for(let e of this._pendingRemovals)this._conversations.delete(e),this._activeId===e&&(this._activeId=null);this._pendingRemovals.clear()}}},Dn=class extends Error{constructor(e){super(e?`Signaling disposed. Command ${e}`:`Signaling disposed`),this.name=`SignalingDisposedError`}},On=class extends Error{constructor(e){super(e?`Producer connection closed. Command ${e}`:`Producer connection closed`),this.name=`ProducerConnectionClosedError`}},kn=class extends b{constructor(...e){super(...e),h(this,`_abortSignal`,void 0)}setAbortSignal(e){this._abortSignal=e}get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setWebTransportEndpoint(e){}readyToSend(e=!0){}async requestTestMode(e,t){}getNextCommandSequenceNumber(){return 0}},V=function(e){return e.RECOVER=`recover`,e.ACCEPT_CALL=`accept-call`,e.ADD_PARTICIPANT=`add-participant`,e.REMOVE_PARTICIPANT=`remove-participant`,e.HANGUP=`hangup`,e.TRANSMIT_DATA=`transmit-data`,e.ACCEPT_PRODUCER=`accept-producer`,e.ALLOCATE_CONSUMER=`allocate-consumer`,e.CHANGE_MEDIA_SETTINGS=`change-media-settings`,e.CHANGE_PARTICIPANT_STATE=`change-participant-state`,e.CHANGE_STREAM_PRIORITIES=`change-streams-priorities`,e.UPDATE_DISPLAY_LAYOUT=`update-display-layout`,e.REPORT_PERF_STAT=`report-perf-stat`,e.REPORT_SHARING_STAT=`report-sharing-stat`,e.REPORT_NETWORK_STAT=`report-network-stat`,e.RECORD_START=`record-start`,e.RECORD_STOP=`record-stop`,e.RECORD_PUBLISH=`record-publish`,e.RECORD_SET_CONF=`record-set-conf`,e.RECORD_GET_STATUS=`record-get-status`,e.SWITCH_MICRO=`switch-micro`,e.SWITCH_TOPOLOGY=`switch-topology`,e.REQUEST_REALLOC=`request-realloc`,e.CHAT_MESSAGE=`chat-message`,e.CHAT_HISTORY=`chat-history`,e.CUSTOM_DATA=`custom-data`,e.GRANT_ROLES=`grant-roles`,e.MUTE_PARTICIPANT=`mute-participant`,e.ENABLE_FEATURE_FOR_ROLES=`enable-feature-for-roles`,e.PIN_PARTICIPANT=`pin-participant`,e.UPDATE_MEDIA_MODIFIERS=`update-media-modifiers`,e.CHANGE_OPTIONS=`change-options`,e.GET_WAITING_HALL=`get-waiting-hall`,e.GET_PARTICIPANT_LIST_CHUNK=`get-participant-list-chunk`,e.GET_PARTICIPANTS=`get-participants`,e.PROMOTE_PARTICIPANT=`promote-participant`,e.REQUEST_TEST_MODE=`request-test-mode`,e.ADD_MOVIE=`add-movie`,e.UPDATE_MOVIE=`update-movie`,e.REMOVE_MOVIE=`remove-movie`,e.START_URL_SHARING=`start-url-sharing`,e.STOP_URL_SHARING=`stop-url-sharing`,e.GET_ROOMS=`get-rooms`,e.UPDATE_ROOMS=`update-rooms`,e.ACTIVATE_ROOMS=`activate-rooms`,e.REMOVE_ROOMS=`remove-rooms`,e.SWITCH_ROOM=`switch-room`,e.FEEDBACK=`feedback`,e.ASR_START=`asr-start`,e.ASR_STOP=`asr-stop`,e.REQUEST_ASR=`request-asr`,e.REQUEST_PROMOTION=`request-promotion`,e.ACCEPT_PROMOTION=`accept-promotion`,e.GET_HAND_QUEUE=`get-hand-queue`,e.ENABLE_VIDEO_SUSPEND=`enable-video-suspend`,e.ENABLE_VIDEO_SUSPEND_SUGGEST=`enable-video-suspend-suggest`,e.HOLD=`hold`,e.PUT_HANDS_DOWN=`put-hands-down`,e.CHANGE_SIMULCAST=`change-simulcast`,e}(V||{});function An(e){return e.stopStream}function jn(e){return e.keyFrameRequested}function Mn(e){if(An(e))return`ss`;if(jn(e))return`kf`;let t=``;return e.priority!==void 0&&(t+=`p=`+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==``&&(t+=`:`),t+=`sz=`+Math.round(e.width)+`x`+Math.round(e.height)),e.fit!==void 0&&(t!==``&&(t+=`:`),t+=`fit=`+e.fit),t}var H=function(e){return e.CAMERA=`CAMERA`,e.SCREEN=`SCREEN`,e.STREAM=`STREAM`,e.MOVIE=`MOVIE`,e.ANIMOJI=`ANIMOJI`,e.SHARED_URL=`SHARED_URL`,e}({}),Nn=`s`,Pn=`m`;function Fn(e){return e.participantId+(e.mediaType?`:`+Nn+e.mediaType:``)+(e.streamName?`:`+Pn+e.streamName:``)}function In(e){let t=e.split(`:`),n=t.shift();if(!n)throw Error(`Illegal stream description: `+e);let r=null,i,a=0;for(let n of t)switch(n.charAt(0)){case Nn:r=Ln(n.slice(1));break;case Pn:i=n.slice(1);break;case`d`:a=Number.parseInt(n.slice(1),10);break;default:throw Error(`Unexpected parameter type `+n.charAt(0)+` in stream description `+e)}return{participantId:M.compose(n,a),mediaType:r,streamName:i}}function Ln(e){for(let t of Object.keys(H))if(t===e)return H[t];return null}function Rn(){let e=new DataView(new ArrayBuffer(64)),t=0;function n(n){if(t+n>e.byteLength){let r=new Uint8Array(Math.max(t+n,e.byteLength+64));r.set(new Uint8Array(e.buffer.slice(0,t))),e=new DataView(r.buffer)}}return{put(r){if(n(r.byteLength),zn(r)){let n=r.buffer;new Uint8Array(e.buffer).set(new Uint8Array(n),t)}else new Uint8Array(e.buffer).set(new Uint8Array(r),t);t+=r.byteLength},putI8(r){n(1),e.setInt8(t,r),++t},putI16(r){n(2),e.setInt16(t,r),t+=2},putI32(r){n(4),e.setInt32(t,r),t+=4},putI64(r){n(8);let i=r<0;i&&(r=-r);let a=r/4294967296|0,o=r%4294967296|0;i&&(o=~o+1|0,a=o===0?~a+1|0:~a),e.setUint32(t,a),e.setUint32(t+4,o),t+=8},putUi8(r){n(1),e.setUint8(t,r),++t},putUi16(r){n(2),e.setUint16(t,r),t+=2},putUi32(r){n(4),e.setUint32(t,r),t+=4},putUi64(r){n(8),e.setUint32(t,r/4294967296|0),e.setUint32(t+4,r%4294967296),t+=8},putF(r){n(8),e.setFloat64(t,r),t+=8},ui8array(){return new Uint8Array(e.buffer.slice(0,t))}}}function zn(e){return e.buffer!==void 0}function Bn(e){let t=ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),n=0;return{peek(){return t.getUint8(n)},get(e){n+=e;let r=t.byteOffset;return t.buffer.slice(r+n-e,r+n)},getI8(){return t.getInt8(n++)},getI16(){return n+=2,t.getInt16(n-2)},getI32(){return n+=4,t.getInt32(n-4)},getI64(){n+=8;let e=t.getInt32(n-8),r=t.getUint32(n-4);return e*4294967296+r},getUi8(){return t.getUint8(n++)},getUi16(){return n+=2,t.getUint16(n-2)},getUi32(){return n+=4,t.getUint32(n-4)},getUi64(){n+=8;let e=t.getUint32(n-8),r=t.getUint32(n-4);return e*4294967296+r},getF32(){return n+=4,t.getFloat32(n-4)},getF64(){return n+=8,t.getFloat64(n-8)}}}var Vn=0,Hn=1,Un=2,Wn=3,Gn=4,Kn=5,qn=6,Jn=7,Yn=0,Xn=1,Zn=2,Qn=0,$n=0,er=0,tr=1,nr=class{constructor(e=z){h(this,`participantIdRegistry`,null),h(this,`_debug`,void 0),this._debug=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}serializeUpdateDisplayLayout(e,t){let n=Rn();l.Int.enc(n,Vn),l.Int.enc(n,Qn),l.Int.enc(n,e),l.Nil.enc(n,null);let r=[];for(let e in t)Object.hasOwn(t,e)&&this.writeLayout(t,e,r);return l.Arr.enc(n,r),l.Nil.enc(n,null),n.ui8array().buffer}writeLayout(e,t,n){let r=e[t],i=Rn();if(this.writeStreamDesc(t,i),An(r))l.Int.enc(i,Xn);else if(jn(r))l.Int.enc(i,Zn);else if(l.Int.enc(i,Yn),r.priority===void 0?l.Nil.enc(i,null):l.Int.enc(i,r.priority),r.width!==void 0&&r.height!==void 0?(l.Int.enc(i,Math.round(r.width)),l.Int.enc(i,Math.round(r.height))):(l.Nil.enc(i,null),l.Nil.enc(i,null)),r.fit!==void 0)switch(r.fit){case`cv`:l.Int.enc(i,er);break;case`cn`:l.Int.enc(i,tr);break;default:l.Nil.enc(i,null)}else l.Nil.enc(i,null);n.push(i.ui8array().buffer)}writeStreamDesc(e,t){if(this.participantIdRegistry){let n=this.participantIdRegistry.getCompactId(e);if(n!==void 0){l.Int.enc(t,n);return}}l.Str.enc(t,e)}serializePerfStatReport(e,t){let n=Rn();return l.Int.enc(n,Hn),l.Int.enc(n,Qn),l.Int.enc(n,e),l.Int.enc(n,t.framesDecoded),l.Int.enc(n,t.framesReceived),n.ui8array().buffer}serializeSharingStatReport(e,t){let n=Rn();return l.Int.enc(n,Un),l.Int.enc(n,Qn),l.Int.enc(n,e),l.Int.enc(n,t.minDelay),l.Int.enc(n,t.maxDelay),l.Int.enc(n,t.avgDelay),l.Int.enc(n,t.largeDelayDuration),n.ui8array().buffer}serializeRequestAsr(e,t){let n=Rn();return l.Int.enc(n,Wn),l.Int.enc(n,Qn),l.Int.enc(n,e),l.Bool.enc(n,t.request),n.ui8array().buffer}serializeNetworkStatReport(e,t){let n=Rn();return l.Int.enc(n,Gn),l.Int.enc(n,Qn),l.Int.enc(n,e),l.Int.enc(n,t.timestamp),l.Int.enc(n,t.sendBitrate),n.ui8array().buffer}serializeEnableVideoSuspend(e,t){let n=Rn();return l.Int.enc(n,Kn),l.Int.enc(n,Qn),l.Int.enc(n,e),l.Bool.enc(n,t.enabled),n.ui8array().buffer}serializeEnableVideoSuspendSuggest(e,t){let n=Rn();return l.Int.enc(n,qn),l.Int.enc(n,Qn),l.Int.enc(n,e),l.Bool.enc(n,t.enabled),n.ui8array().buffer}serializeChangeSimulcast(e,t){let n=Rn();l.Int.enc(n,Jn),l.Int.enc(n,Qn),l.Int.enc(n,e);let r=t.simulcastInfo.streams.length;l.Int.enc(n,t.mediaSource),l.Int.enc(n,r);for(let e of t.simulcastInfo.streams)l.Str.enc(n,e.rid),l.Int.enc(n,e.width),l.Int.enc(n,e.height),l.Int.enc(n,e.fps),l.Int.enc(n,e.bitrate/1e3);return n.ui8array().buffer}async deserializeCommandResponse(e){let t;t=e instanceof Blob?Bn(`arrayBuffer`in Blob.prototype?await e.arrayBuffer():await un(e)):Bn(e);let n=l.Int.dec(t),r=l.Int.dec(t);if(r!==Qn){this._debug.warn(`Unsupported version for command type: `+n+`, version `+r);return}if(l.Int.dec(t)!==$n){this._debug.warn(`Error code: `+n+`received for command type: `+n+`, version `+r);return}switch(n){case Vn:return this.deserializeUpdateDisplayLayoutResponse(t);case Hn:return this.deserializeReportPerfStatResponse(t);default:this._debug.warn(`unsupported command response commandType: `+n);return}}deserializeUpdateDisplayLayoutResponse(e){let t=l.Int.dec(e),n=l.Arr.dec(e),r={};return n.forEach(e=>{let t=Bn(e),n=l.Any.dec(t);if(typeof n==`string`)r[n]=l.Int.dec(t);else{let e=n,i=Fn(this.participantIdRegistry?.getStreamDescription(e));r[i]=l.Int.dec(t)}}),{type:`response`,sequence:t,response:V.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:r}}deserializeReportPerfStatResponse(e){let t=l.Int.dec(e),n=l.Int.dec(e);return{type:`response`,sequence:t,response:V.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:n}}},U=function(e){return e.CALL_INIT=`call_init`,e.CALL_START=`call_start`,e.CALL_ACCEPTED_OUTGOING=`call_accepted_outgoing`,e.CALL_ACCEPTED_INCOMING=`call_accepted_incoming`,e.FIRST_MEDIA_SENT=`first_media_sent`,e.CALL_FINISH=`call_finish`,e.CODEC_USAGE=`codec_usage`,e.SIGNALING_CONNECTED=`signaling_connected`,e.SCREENSHARE_FIRST_FRAME=`screen_share_first_frame`,e.FIRST_MEDIA_RECEIVED=`first_media_received`,e.CALL_DECLINED_OR_HANGED_LOCALLY=`CallDeclinedOrHangedLocally`,e.USER_FEEDBACK_RECEIVED=`UserFeedbackReceived`,e.SIGNALING_PING_SUMMARY=`signaling_ping_summary`,e.SIGNALING_COMMAND_SUMMARY=`signaling_command_summary`,e.WEBSOCKET_CONNECTED=`websocket_connected`,e.WEBSOCKET_RECONNECTED=`websocket_reconnected`,e.WEBSOCKET_FAILED_PINGS=`websocket_failed_pings`,e.WEBSOCKET_FAILED_EXCEPTION=`websocket_failed_exception`,e.WEBSOCKET_TIMEOUT=`websocket_timeout`,e.WEBSOCKET_RESTART=`websocket_restart`,e.WEBTRANSPORT_CONNECTED=`webtransport_connected`,e.WEBTRANSPORT_RECONNECTED=`webtransport_reconnected`,e.WEBTRANSPORT_FAILED_PINGS=`webtransport_failed_pings`,e.WEBTRANSPORT_FAILED_EXCEPTION=`webtransport_failed_exception`,e.WEBTRANSPORT_TIMEOUT=`webtransport_timeout`,e.WEBTRANSPORT_RESTART=`webtransport_restart`,e}(U||{}),rr=1e3;function W(e,t,n=0){return t in e&&e[t]?e[t]:n}function ir(...e){return t=>{for(let n of e)if(n(t))return!0;return!1}}function ar(e,t){return n=>n[e]===t}function or(e){return(t,n)=>n[e]-t[e]}function sr(e,t){return t.reduce((t,n)=>(t[n[e]]=n,t),{})}function cr(e){let t={},n=[];for(let r of e)t[r.id]||(t[r.id]=!0,n.push(r));return n}function lr(e){return Object.keys(e).filter(t=>e[t]!==void 0).map(t=>[t,e[t]]).reduce((e,t)=>(e[t[0]]=M.isObject(t[1])?lr(t[1]):t[1],e),{})}function ur(e){let t=[];for(let n of e)n.forEach(e=>t.push(e));return t}async function dr(e){let t=[];return RTCRtpReceiver.prototype.getStats?(t.push(...e.getReceivers().map(e=>e.getStats())),t.push(...e.getSenders().map(e=>e.getStats()))):t.push(e.getStats()),Promise.all(t).then(ur).then(cr)}function fr(e){let t=e.filter(ar(`type`,`candidate-pair`)).sort(or(`priority`)).find(ir(ar(`nominated`,!0),ar(`selected`,!0)));if(!t)return{timestamp:0,availableOutgoingBitrate:0,totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let n={timestamp:t.timestamp,availableOutgoingBitrate:t.availableOutgoingBitrate||0,totalRoundTripTime:t.totalRoundTripTime||0,currentRoundTripTime:t.currentRoundTripTime||0,bytesSent:t.bytesSent||0,bytesReceived:t.bytesReceived||0},r=e.find(ar(`id`,t.remoteCandidateId));r&&Object.assign(n,{remote:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol}});let i=e.find(ar(`id`,t.localCandidateId));return i&&Object.assign(n,{local:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol,relayProtocol:i.relayProtocol,networkType:i.networkType}}),lr(n)}function pr(e,t,n=!1){let r=sr(`id`,e);return(n?e.filter(ir(ar(`type`,`remote-inbound-rtp`))):e.filter(ir(ar(`type`,`inbound-rtp`),ar(`type`,`outbound-rtp`)))).map(e=>{let n=Number(e.ssrc),i=e.mediaType||e.kind,a=e.remoteId||e.trackId,o=e.type,s=e.codecId;if(!o||!n||!i)return null;let c={ssrc:n,type:o,kind:i,bytesReceived:W(e,`bytesReceived`),bytesSent:W(e,`bytesSent`),headerBytesReceived:W(e,`headerBytesReceived`),headerBytesSent:W(e,`headerBytesSent`),jitter:W(e,`jitter`),packetsLost:W(e,`packetsLost`),packetsReceived:W(e,`packetsReceived`),packetsSent:W(e,`packetsSent`),fractionLost:W(e,`fractionLost`),pliCount:W(e,`pliCount`),firCount:W(e,`firCount`),nackCount:W(e,`nackCount`),userId:t[n],freezeCount:W(e,`freezeCount`,0),totalFreezesDuration:W(e,`totalFreezesDuration`,0)},l=`mid`in e&&typeof e.mid==`string`?e.mid:void 0,u=`rid`in e&&typeof e.rid==`string`?e.rid:void 0;if(l&&(c.mid=l),u&&(c.rid=u),i===`video`){let t=W(e,`framesDecoded`),n=W(e,`totalInterFrameDelay`),r=W(e,`totalSquaredInterFrameDelay`),i=W(e,`encoderImplementation`),a=W(e,`decoderImplementation`);i&&(c.encoderImplementation=i),a&&(c.decoderImplementation=a),c.interframeDelayVariance=(r-n*n/t)/t}if(i===`video`&&c.type===`outbound-rtp`&&(c.totalEncodeTime=W(e,`totalEncodeTime`)??0),i===`audio`&&(c.totalSamplesReceived=W(e,`totalSamplesReceived`),c.concealedSamples=W(e,`concealedSamples`),c.insertedSamplesForDeceleration=W(e,`insertedSamplesForDeceleration`),c.removedSamplesForAcceleration=W(e,`removedSamplesForAcceleration`),c.silentConcealedSamples=W(e,`silentConcealedSamples`),c.concealmentEvents=W(e,`concealmentEvents`),c.totalAudioEnergy=W(e,`totalAudioEnergy`)),s&&r[s]){let e=r[s];c.clockRate=e.clockRate,c.mimeType=e.mimeType,i===`audio`&&e.sdpFmtpLine&&(c.sdpFmtpLine=e.sdpFmtpLine)}if(a&&r[a]){let e=r[a];c.frameHeight=e.frameHeight,c.frameWidth=e.frameWidth,c.framesDecoded=e.framesDecoded,c.framesReceived=e.framesReceived,c.framesDropped=e.framesDropped}return lr(c)}).filter(e=>!!e)}function mr(e,t,n=!1){if(!t||!t.rtps.length||!e.rtps.length)return e;let r,i;n&&(r=sr(`ssrc`,e?.remoteRtps||[]),i=sr(`ssrc`,t?.remoteRtps||[]));let a=sr(`ssrc`,e.rtps),o=sr(`ssrc`,t.rtps),s=(e.timestamp-t.timestamp)/1e3;return!a||!o||Object.keys(a).forEach(c=>{let l=a[c],u=o[c];if(!(!l||!u)){if(l.bytesReceived&&l.bytesReceived>u.bytesReceived&&(l.bandwidth=Math.round((l.bytesReceived-u.bytesReceived)/s),l.bandwidth+=Math.round((l.headerBytesReceived-u.headerBytesReceived)/s)),l.bytesSent&&l.bytesSent>u.bytesSent&&(l.bandwidth=Math.round((l.bytesSent-u.bytesSent)/s),l.bandwidth+=Math.round((l.headerBytesSent-u.headerBytesSent)/s)),l.packetsReceived)if(l.packetsReceived>u.packetsReceived||l.packetsLost>u.packetsLost){let e=l.packetsLost-u.packetsLost,t=l.packetsReceived-u.packetsReceived;l.packetLoss=parseFloat((100*e/(e+t)).toFixed(2))}else l.packetLoss=0;if(l.freezeCount>u.freezeCount&&(l.freezeCountDelta=l.freezeCount-u.freezeCount),l.totalFreezesDuration>u.totalFreezesDuration&&(l.totalFreezesDurationDelta=l.totalFreezesDuration-u.totalFreezesDuration),l.framesDropped&&u.framesDropped&&l.framesDropped>u.framesDropped&&(l.framesDroppedDelta=parseFloat(((l.framesDropped-u.framesDropped)/s).toFixed(0))),n&&l.type===`outbound-rtp`&&l.kind===A.video){let n=r?.[c],a=i?.[c],o=e=>e??0,s=Math.max(0,o(n?.packetsLost)-o(a?.packetsLost)),d=Math.max(1,l.packetsSent-u.packetsSent);e.transport.averageNetStat={currentRoundTripTime:(e.transport.currentRoundTripTime+t.transport.currentRoundTripTime)/2*1e3,lostPercent:Math.round(s/d*100)}}}}),e}async function hr(e,t,n={},r=!1){let i=await dr(e),a={timestamp:Date.now(),transport:fr(i),rtps:pr(i,n)};return r&&(a.remoteRtps=pr(i,n,!0)),t?mr(a,t,r):(await M.delay(rr),hr(e,a,n,r))}function gr(e){performance.clearMarks(e),performance.mark(e)}function _r(e){performance.clearMarks(e)}function vr(e){let t=performance.getEntriesByName(e)[0];if(t===void 0)return null;let n=Math.round(performance.now()-t.startTime);return performance.clearMarks(e),n}function yr(e){return`${U.SCREENSHARE_FIRST_FRAME}_${br(e)}`}function br(e){return typeof e==`string`?e:JSON.stringify(e)}var G={distinctById:cr,rtcStatsToArray:ur,extractTransport:fr,extractRtps:pr,delta:mr,collectStats:hr,setMark:gr,clearMark:_r,measureMark:vr,getMarkNameScreenshareFirstFrame:yr},xr=function(e){return e.START=`start`,e.ACCEPT=`accept`,e.JOIN=`join`,e.RETRY=`retry`,e}(xr||{}),Sr=function(e){return e.NOTIFICATION=`NOTIFICATION`,e.FAILED=`FAILED`,e.RECONNECT=`RECONNECT`,e}(Sr||{}),K=function(e){return e.TRANSMITTED_DATA=`transmitted-data`,e.ACCEPTED_CALL=`accepted-call`,e.HUNGUP=`hungup`,e.PARTICIPANT_ADDED=`participant-added`,e.PARTICIPANT_JOINED=`participant-joined`,e.CLOSED_CONVERSATION=`closed-conversation`,e.MEDIA_SETTINGS_CHANGED=`media-settings-changed`,e.PARTICIPANT_STATE_CHANGED=`participant-state-changed`,e.PARTICIPANTS_STATE_CHANGED=`participants-state-changed`,e.RATE_CALL_DATA=`rate-call-data`,e.FEATURE_SET_CHANGED=`feature-set-changed`,e.TOPOLOGY_CHANGED=`topology-changed`,e.PRODUCER_UPDATED=`producer-updated`,e.CONSUMER_ANSWERED=`consumer-answered`,e.MULTIPARTY_CHAT_CREATED=`multiparty-chat-created`,e.FORCE_MEDIA_SETTINGS_CHANGE=`force-media-settings-change`,e.SETTINGS_UPDATE=`settings-update`,e.VIDEO_QUALITY_UPDATE=`video-quality-update`,e.REGISTERED_PEER=`registered-peer`,e.SWITCH_MICRO=`switch-micro`,e.RECORD_STARTED=`record-started`,e.RECORD_STOPPED=`record-stopped`,e.REALLOC_CON=`realloc-con`,e.AUDIO_ACTIVITY=`audio-activity`,e.SPEAKER_CHANGED=`speaker-changed`,e.SESSION_STATE=`session-state`,e.STALLED_ACTIVITY=`stalled-activity`,e.CHAT_MESSAGE=`chat-message`,e.CUSTOM_DATA=`custom-data`,e.ROLES_CHANGED=`roles-changed`,e.MUTE_PARTICIPANT=`mute-participant`,e.PIN_PARTICIPANT=`pin-participant`,e.OPTIONS_CHANGED=`options-changed`,e.NETWORK_STATUS=`network-status`,e.PARTICIPANT_SOURCES_UPDATE=`participant-sources-update`,e.PROMOTE_PARTICIPANT=`promote-participant`,e.CHAT_ROOM_UPDATED=`chat-room-updated`,e.PROMOTION_APPROVED=`promotion-approved`,e.JOIN_LINK_CHANGED=`join-link-changed`,e.FEEDBACK=`feedback`,e.MOVIE_UPDATE_NOTIFICATION=`movie-update-notification`,e.MOVIE_SHARE_STARTED=`movie-share-started`,e.MOVIE_SHARE_STOPPED=`movie-share-stopped`,e.URL_SHARING_INFO_UPDATED=`url-sharing-info-updated`,e.ROOM_UPDATED=`room-updated`,e.ROOMS_UPDATED=`rooms-updated`,e.ROOM_PARTICIPANTS_UPDATED=`room-participants-updated`,e.FEATURES_PER_ROLE_CHANGED=`features-per-role-changed`,e.PARTICIPANT_ANIMOJI_CHANGED=`participant-animoji-changed`,e.ASR_STARTED=`asr-started`,e.ASR_STOPPED=`asr-stopped`,e.DECORATIVE_PARTICIPANT_ID_CHANGED=`decorative-participant-id-changed`,e.VIDEO_SUSPEND_SUGGEST=`video-suspend-suggest`,e.HOLD=`hold`,e}(K||{}),Cr=function(e){return e.WEBSOCKET=`ws`,e.WEBTRANSPORT=`wt`,e}({}),wr=function(e){return e.CONNECTED=`connected`,e.RECONNECTED=`reconnected`,e.FAILED_PINGS=`failed_pings`,e.FAILED_EXCEPTIONS=`failed_exception`,e.TIMEOUT=`timeout`,e.RESTART=`restart`,e}({}),Tr={connected:{wt:U.WEBTRANSPORT_CONNECTED,ws:U.WEBSOCKET_CONNECTED},reconnected:{wt:U.WEBTRANSPORT_RECONNECTED,ws:U.WEBSOCKET_RECONNECTED},failed_pings:{wt:U.WEBTRANSPORT_FAILED_PINGS,ws:U.WEBSOCKET_FAILED_PINGS},failed_exception:{wt:U.WEBTRANSPORT_FAILED_EXCEPTION,ws:U.WEBSOCKET_FAILED_EXCEPTION},timeout:{wt:U.WEBTRANSPORT_TIMEOUT,ws:U.WEBSOCKET_TIMEOUT},restart:{wt:U.WEBTRANSPORT_RESTART,ws:U.WEBSOCKET_RESTART}},q=function(e){return e.IDLE=`IDLE`,e.OPENED=`OPENED`,e.CONNECTING=`CONNECTING`,e.RECONNECTING=`RECONNECTING`,e.CONNECTED=`CONNECTED`,e.CLOSED=`CLOSED`,e.FAILED=`FAILED`,e}(q||{}),J=function(e){return e.DIRECT=`DIRECT`,e.SERVER=`SERVER`,e}(J||{}),Er=function(e){return e.producerNotification=`producerNotification`,e.producerCommand=`producerCommand`,e.consumerScreenShare=`consumerScreenShare`,e.producerScreenShare=`producerScreenShare`,e.asr=`asr`,e.animoji=`animoji`,e}(Er||{}),{isObject:Dr,isObjectsEquals:Or}=M;function kr(e,t){return e===null||t===null?e===null&&t===null:e.maxDimension!==t.maxDimension||e.maxBitrateK!==t.maxBitrateK||e.maxFramerate!==t.maxFramerate||e.degradationPreference!==t.degradationPreference||e.scalabilityMode!==t.scalabilityMode||Dr(e.bitrates)&&Dr(t.bitrates)&&!Or(e.bitrates,t.bitrates,!0)?!1:e.bitrates===t.bitrates}var Ar=function(e){return e.L1T1=`L1T1`,e.L1T2=`L1T2`,e.L1T3=`L1T3`,e}({});function jr(e,t){return!(!kr(e.camera,t.camera)||!kr(e.screenSharing,t.screenSharing)||!kr(e.fastScreenSharing,t.fastScreenSharing))}function Mr(e,t){return{camera:Object.assign({},e.camera,t.camera),screenSharing:Object.assign({},e.screenSharing,t.screenSharing),fastScreenSharing:Object.assign({},e.fastScreenSharing,t.fastScreenSharing)}}function Nr(){return{camera:null,screenSharing:null,fastScreenSharing:null}}var Pr=200;function Fr(e){for(let t of e.values())if(t.type===`outbound-rtp`&&(t.packetsSent??0)>0)return!0;return!1}var Ir=class{constructor(e,t,n=Pr){h(this,`_peerConnection`,void 0),h(this,`_onFirstMediaSent`,void 0),h(this,`_pollIntervalMs`,void 0),h(this,`_timer`,null),h(this,`_state`,`idle`),this._peerConnection=e,this._onFirstMediaSent=t,this._pollIntervalMs=n}start(){this._state===`idle`&&(this._state=`polling`,this._poll())}destroy(){this._state!==`stopped`&&(this._state=`stopped`,this._timer!==null&&(clearTimeout(this._timer),this._timer=null))}async _getStatsReports(){return(await Promise.all(this._peerConnection.getSenders().map(async e=>{try{return await e.getStats()}catch{return null}}))).filter(e=>e!==null)}async _poll(){if(this._state===`polling`){try{let e=await this._getStatsReports();if(this._state!==`polling`)return;if(e.some(Fr)){this._state=`stopped`,this._onFirstMediaSent();return}}catch{}this._scheduleNextPoll()}}_scheduleNextPoll(){this._state===`polling`&&(this._timer=setTimeout(()=>{this._timer=null,this._poll()},this._pollIntervalMs))}},Lr=class extends b{constructor(e,t,n=null){super(),h(this,`_signaling`,void 0),h(this,`_mediaSource`,void 0),h(this,`_state`,q.IDLE),h(this,`_pc`,null),h(this,`_onFirstMediaSent`,void 0),h(this,`_firstMediaSentProbe`,null),h(this,`_firstMediaSentProbeStopped`,!1),this._signaling=e,this._mediaSource=t,this._onFirstMediaSent=n}getState(){return this._state||q.IDLE}stopFirstMediaSentProbe(){this._firstMediaSentProbeStopped=!0,this._disposeFirstMediaSentProbe()}_startFirstMediaSentProbe(){this._disposeFirstMediaSentProbe(),!(!this._pc||!this._onFirstMediaSent||this._firstMediaSentProbeStopped)&&(this._firstMediaSentProbe=new Ir(this._pc,this._onFirstMediaSent),this._firstMediaSentProbe.start())}_disposeFirstMediaSentProbe(){this._firstMediaSentProbe?.destroy(),this._firstMediaSentProbe=null}},Rr=class{constructor(e,t=null){h(this,`weightUp`,void 0),h(this,`weightDown`,void 0),h(this,`value`,NaN),this.weightUp=e,this.weightDown=t??e}set(e){this.value=e}update(e){return this.value=Number.parseFloat(this.getNext(e).toFixed(3)),this.value}getNext(e){if(isNaN(this.value))return e;let t=e<this.value?this.weightDown:this.weightUp;return this.value*(1-t)+e*t}getValue(){return this.value}},zr=.25,Br=.35,Vr=85,Hr=.1,Ur=1.5,Wr=.1,Gr=1,Kr=.6,qr=.3,Jr=class extends b{constructor(e,t=z){super(),h(this,`_signaling`,void 0),h(this,`_localNetworkStat`,void 0),h(this,`_remoteNetworkStat`,void 0),h(this,`_lastNetworkStat`,void 0),h(this,`_networkLimits`,{badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}}),h(this,`_lastStatSentTimestamp`,0),h(this,`_currentState`,`good`),h(this,`_debug`,void 0),this._debug=t,this._signaling=e,this._localNetworkStat={rtt:new Rr(zr,zr),loss:new Rr(Br,Br),bitrate:0},this._remoteNetworkStat={rtt:0,loss:0,bitrate:0},this._lastNetworkStat={rtt:0,loss:0,date:0}}_calcRttRating(e){let t=typeof e==`number`?e:e.getValue(),n=1;if(isNaN(t))return n;let r=Math.round((t-this._networkLimits.goodNet.rtt)/Vr);for(let e=0;e<r;e++)n*=1-Hr;return n}_calcLossRating(e){let t=typeof e==`number`?e:e.getValue(),n=1;if(isNaN(t))return n;let r=Math.round((t-this._networkLimits.goodNet.loss)/Ur);for(let e=0;e<r;e++)n*=1-Wr;return n}_calcBitrateRating(e,t){if(!e||!t)return 1;let n=1-(1-Math.min(e,t)/Math.max(e,t))*Gr;return Math.min(n,1)}_calcUDPRating({rtt:e,loss:t}){return this._calcRttRating(e)*this._calcLossRating(t)}_calcRating(e,t,n){return n?this._calcBitrateRating(e.bitrate,t.bitrate):this._calcUDPRating(e)*this._calcUDPRating(t)}_getNetworkState(e){return isNaN(e)||e>=Kr?`good`:e>=qr?`medium`:`bad`}updateSettings(e){Object.assign(this._networkLimits.badNet,e?.badNet||{}),Object.assign(this._networkLimits.goodNet,e?.goodNet||{})}reportLocal(e){if(!this._signaling.ready)return;let t=e.outbound.transport.local?.protocol===`tcp`,n=Math.max(0,Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0),r=e.inbound.rtps.reduce((e,t)=>Math.max(e,t.packetLoss||0),0),i={rtt:this._localNetworkStat.rtt.update(n),loss:this._localNetworkStat.loss.update(r)};if(t){let t=e.outbound.rtps.reduce((e,t)=>e+(t.bandwidth??0)*8,0);i.bitrate=t,this._localNetworkStat.bitrate=t}let a=Date.now(),o=this._calcRating(this._localNetworkStat,this._remoteNetworkStat,t),s=Math.max(Math.round(o*10)/10,.1),c=this._getNetworkState(s);(t||c!==this._currentState||a-this._lastStatSentTimestamp>N.networkStatisticsInterval)&&(this._lastStatSentTimestamp=a,this._signaling.customData({sdk:Object.assign({type:`bad-net`},i)},null).catch(e=>{this._debug.warn(`Unable to send [bad-net]`,e)})),this._currentState=c,this._triggerEvent(Y.NETWORK_STATUS,s)}reportRemote(e){let{rtt:t,loss:n,bitrate:r}=e||{};this._remoteNetworkStat.rtt=t||0,this._remoteNetworkStat.loss=n||0,this._remoteNetworkStat.bitrate=r||0}},Yr=30*1e3,Xr=class e extends Lr{constructor(e,t,n,r,i,a=z,o=null,s=null,c=null,l=null){super(n,r,l),h(this,`_participantId`,void 0),h(this,`_isMaster`,void 0),h(this,`_remoteSDP`,{}),h(this,`_remoteCandidates`,{}),h(this,`_lastRemoteSDP`,null),h(this,`_animojiDataChannel`,null),h(this,`_animojiReceiver`,null),h(this,`_animojiSender`,null),h(this,`_remoteAnimojiVersion`,1),h(this,`_isOpen`,!1),h(this,`_remotePeerId`,null),h(this,`_statInterval`,null),h(this,`_settingsInterval`,null),h(this,`_failedOnCreate`,null),h(this,`_remoteStream`,null),h(this,`_iceRestartTimeout`,null),h(this,`_reconnectionTimeout`,null),h(this,`_reconnectionPrevented`,!1),h(this,`_remoteHold`,!1),h(this,`_lastStat`,null),h(this,`_fingerprint`,null),h(this,`_neverConnected`,!0),h(this,`_serverSettings`,void 0),h(this,`_prevConsumerSettings`,{}),h(this,`_networkLimitsForVideo`,{bad:{loss:4,rtt:1e3},good:{loss:2,rtt:700}}),h(this,`_videoMaxDimensionsForNet`,{worst:320,bad:640,good:1280}),h(this,`_lastVideoMaxDimension`,this._videoMaxDimensionsForNet.good),h(this,`_lastBadConnection`,0),h(this,`_perfStatReporter`,void 0),h(this,`_directStatReporter`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_statAggregator`,void 0),h(this,`_codecStatsAggregator`,void 0),this._participantId=e,this._isMaster=t,this._serverSettings=i,this._debug=a,this._logger=o,this._statAggregator=s,this._codecStatsAggregator=c,this._perfStatReporter=new va(this,n,this._statAggregator,!0,this._debug),this._directStatReporter=new Jr(n,this._debug),this.subscribe(this._signaling,Sr.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Jt.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Jt.SOURCE_CHANGED,this._applySettings.bind(this)),this.subscribe(this._directStatReporter,Y.NETWORK_STATUS,this._onNetworkStatus.bind(this));try{this._pc=this._createPeerConnection()}catch(e){this._debug.error(`Failed to create RTCPeerConnection:`,e),this._failedOnCreate=e;return}if(this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(e){this._logger?.log(C.ERROR,`addTrack-direct`),this._debug.error(`Unable to add media source tracks`,e,{participantId:this._participantId}),this._failedOnCreate=e;return}this._createOffer(!1).catch(e=>{this._state===q.IDLE?this._failedOnCreate=e:this.close(e)})}this._startSettingsInterval()}get participantId(){return this._participantId}updateStatisticsInterval(){this._stopStatInterval(),this._isDeadConnection()||this._startStatInterval()}_isDeadConnection(){return!this._pc||[q.IDLE,q.CLOSED,q.FAILED].includes(this.getState())}async open(e=null){if(this._isOpen){this._debug.warn(`DirectTransport: Already opened`,{participantId:this._participantId});return}if(this._failedOnCreate){this._finishClose(this._failedOnCreate);return}if(this._debug.debug(`DirectTransport: Open transport`,{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(e){this._logger?.log(C.ERROR,`addTrack-direct`),this._debug.error(`DirectTransport: Unable to add media source tracks`,e,{participantId:this._participantId}),this.close(e);return}this._startFirstMediaSentProbe(),this._setState(q.OPENED);let t=e;if(!e){let e=Object.keys(this._remoteSDP);t=e[e.length-1]}if(t&&this._remoteSDP[t])try{await this._setRemoteDescription(t,this._remoteSDP[t])}catch{this.close();return}this._remoteSDP={},this._remoteCandidates={}}updateSettings(e){jr(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}setRemoteHold(e){if(this._remoteHold!==e){if(this._remoteHold=e,e){this._stopReconnection(),this._stopStatInterval(),this._stopSettingsInterval(),this._isOpen&&(this._disposePeerConnection(),this._remoteSDP={},this._remoteCandidates={},this._lastRemoteSDP=null);return}this._isOpen&&this._recreatePeerConnection()}}_recreatePeerConnection(){this._debug.log(`Recreating peer connection after remote unhold`,{participantId:this._participantId});try{this._pc=this._createPeerConnection()}catch(e){this._debug.error(`Failed to recreate RTCPeerConnection:`,e),this.close(e);return}this._neverConnected=!0;try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(e){this._debug.error(`Unable to add media source tracks after unhold`,e,{participantId:this._participantId});return}this._startFirstMediaSentProbe(),this._startSettingsInterval(),this._isMaster&&this._createOffer(!1).catch(e=>{this._debug.error(`Unable to create offer after unhold`,e,{participantId:this._participantId})}),this._setState(q.CONNECTING)}_createPeerConnection(){let e=new RTCPeerConnection({iceServers:N.iceServers,iceTransportPolicy:N.forceRelayPolicy?`relay`:`all`});return e.onicecandidate=this._handleIceCandidate.bind(this),e.ontrack=this._onAddTrack.bind(this),e.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),e.onconnectionstatechange=this._onConnectionStateChange.bind(this),e.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},N.vmoji&&this._createDataChannel(e,Er.animoji,e=>{this._animojiDataChannel=e,this._animojiDataChannel.binaryType=`arraybuffer`,this._animojiReceiver?.setDataChannel(this._animojiDataChannel),this._animojiSender?.setDataChannel(this._animojiDataChannel)}),e}_disposePeerConnection(){if(this._disposeFirstMediaSentProbe(),this._lastStat=null,this._remoteStream){let e=this._remoteStream;e.getTracks().forEach(t=>{t.stop(),this._triggerEvent(Y.REMOTE_TRACK_REMOVED,e,t)}),this._remoteStream=null}this._animojiDataChannel&&(this._animojiDataChannel.onopen=null,this._animojiDataChannel.onmessage=null,this._animojiDataChannel.onerror=null,this._animojiDataChannel.close(),this._animojiDataChannel=null),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._pc=null)}setAnimojiTransport(e,t){if(N.vmoji&&(this._animojiReceiver=e,this._animojiSender=t,e.setParticipantId(this._participantId),this._animojiDataChannel)){e.setDataChannel(this._animojiDataChannel),t.setDataChannel(this._animojiDataChannel);return}}close(e){this._isOpen&&this._finishClose(e)}_finishClose(e){this._isOpen=!1,this._stopReconnection(),this._stopStatInterval(),this._stopSettingsInterval(),this._disposePeerConnection(),this._onNetworkStatus(1),this.unsubscribe(),e?(this._debug.error(`DirectTransport: Closed`,e,{participantId:this._participantId}),this._setState(q.FAILED)):(this._debug.debug(`DirectTransport: Closed`,{participantId:this._participantId}),this._setState(q.CLOSED)),this._triggerEvent(Y.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(this._debug.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(Y.STATE_CHANGED,e))}_onSignalingNotification(e){switch(e.notification){case K.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case K.SETTINGS_UPDATE:this._directStatReporter.updateSettings(e.settings);break;case K.CUSTOM_DATA:Object.hasOwn(e.data,`sdk`)&&this._directStatReporter.reportRemote(e.data?.sdk);break}}_handleTransmittedData(e){let t=e.data,n=M.getPeerIdString(e.peerId);M.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(n,t.candidate).catch(this.close.bind(this)):t.sdp&&(this._remoteAnimojiVersion=t.animojiVersion||1,this._setRemoteDescription(n,t.sdp).catch(this.close.bind(this))))}async _addIceCandidate(e,t){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){this._debug.debug(`Add remote ice candidate`,{participantId:this._participantId,candidate:t});try{await this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(e){throw this._logger?.log(C.ERROR,`addIceCandidate-direct`),this._debug.error(`Unable to add remote ice candidate`,e,{participantId:this._participantId,candidate:t}),e}}else this._debug.debug(`Cache remote ice candidate`,{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)}async _setRemoteCandidates(e){if(!this._remoteCandidates[e]){this._debug.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let n of t)try{await this._addIceCandidate(e,n)}catch{}}async _setRemoteDescription(t,n){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===t)&&this._pc){if(this._lastRemoteSDP?.sdp===n.sdp)return;this._lastRemoteSDP=n,n=e._patchRemoteDescription(n),this._debug.debug(`Add remote description`,{participantId:this._participantId,sdp:n}),this._calcFingerprint(n.sdp);try{await this._pc.setRemoteDescription(n),await this._setRemoteCandidates(t),this._processAnimojiProtocolVersion(this._remoteAnimojiVersion)}catch(e){throw this._logger?.log(C.ERROR,`setRemoteDescription-direct`),this._debug.error(`Unable to set remote description`,e,{participantId:this._participantId,sdp:n}),e}}else this._remoteSDP[t]=n}_processAnimojiProtocolVersion(e){let t=Math.min(e,N.vmojiOptions?.protocolVersion||1);this._animojiSender?.setProtocolVersion(t)}_onAddTrack(e){this._debug.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=e=>{this._triggerEvent(Y.REMOTE_TRACK_REMOVED,this._remoteStream,e.track)}),this._triggerEvent(Y.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}async _handleIceCandidate(e){this._signaling.ready&&(e.candidate?(this._debug.debug(`Local ice candidate`,{participantId:this._participantId,candidate:e.candidate}),await this._signaling.sendCandidate(this._participantId,e.candidate)):N.forwardEmptyIceCandidate&&(this._debug.debug(`ICE gathering complete, forwarding empty candidate`,{participantId:this._participantId}),await this._signaling.sendCandidate(this._participantId,{candidate:``})))}_onSignalingStateChange(){this._debug.debug(`DirectTransport: Signaling state changed to ${this._pc?.signalingState}`,{participantId:this._participantId});let e={animojiVersion:N.vmojiOptions.protocolVersion||1};switch(this._pc?.signalingState){case`have-local-offer`:let t=this._pc.localDescription;t?this._signaling.sendSdp(this._participantId,t,e).catch(this.close.bind(this)):this.close(Error());break;case`have-remote-offer`:this._createAnswer().then(t=>this._signaling.sendSdp(this._participantId,t,e)).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(this._debug.debug(`DirectTransport: Ice Connection state changed to ${this._pc?.iceConnectionState}`,{participantId:this._participantId}),this._pc?.iceConnectionState){case`checking`:{let e=this.getState();e===q.IDLE||e===q.OPENED?this._setState(q.CONNECTING):this._setState(q.RECONNECTING);break}case`connected`:case`completed`:this._pc?.connectionState!==`connected`&&(this._debug.warn(`DirectTransport: marking connected via iceConnectionState fallback`,{participantId:this._participantId,connectionState:this._pc?.connectionState,iceConnectionState:this._pc?.iceConnectionState}),this._logger?.log(C.ERROR,`iceConnectionState-fallback`),this._markConnected());break}}_markConnected(){this._neverConnected=!1,this._setState(q.CONNECTED),this._stopReconnection(),this._pc&&M.getPeerConnectionHostInfo(this._pc).then(e=>{e?.local&&(this._logger?.log(C.ICE_CONNECTION_TYPE,e.local.type),this._debug.debug(`Selected ICE candidates`,e))}),this._startStatInterval()}_onConnectionStateChange(){switch(this._debug.debug(`DirectTransport: Connection state changed to ${this._pc?.connectionState}`,{participantId:this._participantId}),this._logger?.log(C.ICE_CONNECTION_STATE,this._pc?.connectionState),this._pc?.connectionState){case`connected`:this._markConnected();break;case`failed`:case`disconnected`:this._remoteHold?this._debug.log(`Remote participant on hold, skipping reconnection`,{participantId:this._participantId}):this._reconnectionPrevented?this.close(Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(q.RECONNECTING),this._startReconnection());break;case`closed`:this._remoteHold||this.close(Error(`Ice connection closed`));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(this._debug.log(`Waiting for reconnection...`,{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},N.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(this._debug.log(`Switch topology DIRECT to SERVER`,{participantId:this._participantId}),this._signaling.switchTopology(J.SERVER).catch(e=>{e instanceof Dn||this._debug.warn(`Unable to switch topology DIRECT to SERVER`,e)}))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(this._logger?.log(C.ICE_RESTART),this._debug.log(`Ice restart`,{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):this._debug.debug(`Waiting for ice restart...`,{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,this._debug.error(`Ice restart failed`,{participantId:this._participantId}),this._logger?.log(C.ERROR,`iceRestart-direct`),this._requestTopologySwitch()},N.iceRestartWaitTime)}async _createOffer(t){let n={iceRestart:t,offerToReceiveAudio:!0,offerToReceiveVideo:!0};this._debug.debug(`Create offer`,{participantId:this._participantId,options:n});let r;try{r=await this._pc?.createOffer(n),this._debug.debug(`Created offer`,{participantId:this._participantId,offer:r}),r=e._patchLocalDescription(r)}catch(e){throw this._debug.error(`Unable to create offer`,e,{participantId:this._participantId}),this._logger?.log(C.ERROR,`createOffer-direct`),e}try{return this._debug.debug(`Set local description`,{participantId:this._participantId,offer:r}),this._calcFingerprint(r.sdp),await this._pc?.setLocalDescription(r),r}catch(e){throw this._debug.error(`Unable to set local description`,e,{participantId:this._participantId}),this._logger?.log(C.ERROR,`setLocalDescription-direct`),e}}async _createAnswer(){this._debug.debug(`Create answer`,{participantId:this._participantId});let t;try{t=await this._pc?.createAnswer(),this._debug.debug(`Created answer`,{participantId:this._participantId,answer:t}),t=e._patchLocalDescription(t)}catch(e){throw this._debug.error(`Unable to create answer`,e,{participantId:this._participantId}),this._logger?.log(C.ERROR,`createAnswer-direct`),e}try{return this._debug.debug(`Set local description`,{participantId:this._participantId,answer:t}),this._calcFingerprint(t.sdp),await this._pc?.setLocalDescription(t),t}catch(e){throw this._debug.error(`Unable to set local description`,e,{participantId:this._participantId}),this._logger?.log(C.ERROR,`setLocalDescription-direct`),e}}static _patchLocalDescription(e){let t=!!E.baseChromeVersion();return e.sdp=M.patchLocalSDP(e.sdp,N.preferH264&&E.canPreferH264(),E.isBrokenH264Decoder(),N.preferVP9,t&&N.audioNack),e}static _patchRemoteDescription(e){return e.sdp=M.patchRemoteSDP(e.sdp,!1,!1,N.preferVP9,E.isBrokenVP9Encoder(),E.isBrokenVP9Decoder()),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&t.track.contentHint===e.contentHint&&t.replaceTrack(e).catch(e=>{this._debug.error(`DirectTransport: Unable to replace track`,e,{participantId:this._participantId}),this._logger?.log(C.ERROR,`replaceTrack-direct`)})}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(this._isDeadConnection()){this._stopStatInterval();return}G.collectStats(this._pc,this._lastStat,void 0,!0).then(t=>{this._lastStat=t,this._codecStatsAggregator?.reportUsage(t);let n={inbound:{topology:J.DIRECT,transport:t.transport,rtps:t.rtps.filter(e=>e.type===`inbound-rtp`?(e.userId=this._participantId,!0):!1)},outbound:{topology:J.DIRECT,transport:t.transport,rtps:t.rtps.filter(e=>e.type===`outbound-rtp`)},remoteInbound:{topology:J.DIRECT,transport:t.transport,rtps:t.remoteRtps??[]}};this._checkPPTNetwork(n),this._directStatReporter.reportLocal(n),this._triggerEvent(Y.REMOTE_DATA_STATS,n),this._statInterval=window.setTimeout(e,N.statisticsInterval)})};this._statInterval=window.setTimeout(e,N.statisticsInterval)}async _isSVCSupported(e,t){let n=this._mediaSource.getSendVideoTrack(),r=e.outbound.rtps.find(e=>e.kind===`video`);if(!r?.mimeType||!r?.bandwidth||!n)return!1;let i=n.getSettings();if(!i.width||!i.height||!i.frameRate)return!1;let a={type:`webrtc`,video:{contentType:r.mimeType,width:i.width,height:i.height,bitrate:r.bandwidth,framerate:i.frameRate,scalabilityMode:t}};try{return(await navigator.mediaCapabilities.encodingInfo(a)).supported||!1}catch(e){return this._debug.warn(`Failed to get encodingInfo`,a,e),!1}}async _checkPPTNetwork(e){if(!N.switchVideoAtBadNetwork||!e.inbound.transport.averageNetStat)return;let{averageNetStat:t}=e.inbound.transport,n=t.currentRoundTripTime<=this._networkLimitsForVideo.good.rtt&&t.lostPercent<=this._networkLimitsForVideo.good.loss,r=t.currentRoundTripTime>=this._networkLimitsForVideo.bad.rtt||t.lostPercent>=this._networkLimitsForVideo.bad.loss,i=t.currentRoundTripTime<this._networkLimitsForVideo.bad.rtt,a=this._videoMaxDimensionsForNet.good,o=Ar.L1T1;if(r?(this._lastBadConnection=Date.now(),i?(a=this._videoMaxDimensionsForNet.bad,o=Ar.L1T2):(a=this._videoMaxDimensionsForNet.worst,o=Ar.L1T3)):n&&(a=this._videoMaxDimensionsForNet.good,o=Ar.L1T1),!(a<this._lastVideoMaxDimension||Date.now()-this._lastBadConnection>Yr)||this._lastVideoMaxDimension===a)return;let s=this._serverSettings.camera;if(!s||!await this._isSVCSupported(e,o))return;this._debug.debug(`Switch outbound video frame size and scalabilityMode`,{scalabilityMode:o,averageNetStat:t,nextVideoMaxDimension:a}),this._lastVideoMaxDimension=a;let c={...this._serverSettings,camera:{...s,scalabilityMode:o,maxDimension:this._lastVideoMaxDimension}};this.updateSettings(c)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_onNetworkStatus(e){let t={};t[this._participantId]=t[``]=e,this._triggerEvent(Y.NETWORK_STATUS,t)}_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=M.sdpFingerprint(e);if(t===null){this._debug.warn(`Fingerprint calculation is unsupported`);return}this._fingerprint===null?this._fingerprint=t:(R.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){let e=this._mediaSource.mediaSettings.isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&this._pc?.connectionState===`connected`&&(this._prevConsumerSettings=M.applySettings(this._pc,e,this._prevConsumerSettings,this._debug))}_createDataChannel(e,t,n){this._debug.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{negotiated:!0,id:1});r.onopen=()=>{let e=r.readyState;e===`open`?(this._debug.debug(`[${t}] data channel opened`),r.onerror=e=>{this._debug.error(`[${t}] data channel error`,e)},n(r)):this._debug.error(`[${t}] data channel open failed, state [${e}]`)}}},Zr=function(e){return e.AUDIO_MIX=`audio-mix`,e.PARTICIPANT_AGNOSTIC_TRACK_PREFIX=`pat`,e.TRANSPARENT_AUDIO_TRACK_PREFIX=`ta`,e}({}),Qr=16,$r=class e{constructor(e,t,n,r=z){h(this,`_datachannel`,void 0),h(this,`_participantIdRegistry`,void 0),h(this,`_asrCallback`,void 0),h(this,`_textDecoder`,void 0),h(this,`_debug`,void 0),this._debug=r,this._debug.debug(`AsrReceiver started`),this._datachannel=e,this._participantIdRegistry=t,this._asrCallback=n,this._textDecoder=new TextDecoder,this._datachannel.onmessage=e=>this._onDataChannelMessage(e.data)}static parse(e){let t=new DataView(e),n=t.getUint8(0),r=t.getUint8(1);if(r!==0)throw Error(`Unsupported message type. Message type: ${r}`);let i=t.getUint16(2),a=t.getUint32(4),o=t.getUint32(8),s=t.getUint32(12);if(n!==1)throw Error(`Unexpected protocol version. Got ${n}, expected 1`);return{sequence:i,ssrc:a,timestamp:o,duration:s,data:e.slice(Qr)}}_onDataChannelMessage(t){let n=e.parse(t),r=this._participantIdRegistry?.getStreamDescription(n.ssrc)?.participantId;if(!r){this._debug.warn(`Participant id for ssrc ${n.ssrc} not found in registry`);return}let i={participantId:r,text:this._textDecoder.decode(n.data),timestamp:n.timestamp,duration:n.duration};this._asrCallback(i)}destroy(){this._datachannel.onmessage=null}},ei,ti=class{constructor(){h(this,`_value`,1)}get value(){return this._value}set value(e){this._value=e}};ei=ti,h(ti,`_instance`,null),h(ti,`getInstance`,()=>(ei._instance||(ei._instance=new ei),ei._instance));var ni=class{constructor(e=z){h(this,`streamDescriptionByCompactId`,new Map),h(this,`compactIdByStreamDescription`,new Map),h(this,`_debug`,void 0),this._debug=e}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}getCompactId(e){return this.compactIdByStreamDescription.get(e)}handleMessage(e){let t=new Uint8Array(e),n=t[0],r=t.subarray(1);switch(n){case 1:let e=(0,l.decode)(r);return Object.entries(e).forEach(([e,t])=>{let n=In(e);this.streamDescriptionByCompactId.set(t,n),this.compactIdByStreamDescription.set(e,t)}),null;case 2:case 4:let t=(0,l.decode)(r),i=[];for(let e of t){let t=this.getStreamDescription(e);t&&i.push(t.participantId)}return n===2?{type:`notification`,notification:K.AUDIO_ACTIVITY,activeParticipants:i}:{type:`notification`,notification:K.STALLED_ACTIVITY,stalledParticipants:i};case 3:let a=(0,l.decode)(r);return{type:`notification`,notification:K.SPEAKER_CHANGED,speaker:this.getStreamDescription(a)?.participantId};case 5:let o=(0,l.decode)(r);return{type:`notification`,notification:K.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:o[0],maxDimension:o[1]},mediaType:this._decodeMediaType(o[2])};case 6:let s=(0,l.decode)(r),c={};for(let[e,t]of Object.entries(s)){let n=this.getStreamDescription(Number(e))?.participantId;n&&(c[n]=t/100)}return{type:`notification`,notification:K.NETWORK_STATUS,statuses:c};case 7:return this._createParticipantSourcesUpdateNotification(r);case 8:{let e=(0,l.decode)(r).map(e=>{let[t,n,r,i,a,o,s]=e;return{participantId:this.getStreamDescription(t)?.participantId,gain:n,pause:r,offset:i,mute:a,liveStatus:o,startTimeMs:s}});return{type:`notification`,notification:K.MOVIE_UPDATE_NOTIFICATION,data:e}}case 9:let u=(0,l.decode)(r);return{type:`notification`,notification:K.VIDEO_SUSPEND_SUGGEST,bandwidth:u};default:return this._debug.debug(`unsupported message type: `+n),null}}_decodeMediaType(e){if(e===null)return null;switch(e){case 0:return H.CAMERA;case 1:return H.SCREEN;default:throw Error(`Unsupported media type: ${e}`)}}_createParticipantSourcesUpdateNotification(e){let t=(0,l.decode)(e),n=[];for(let[e,r]of Object.entries(t)){let t=r[0],i=r[1],a=r[2],o=!!r[3],s=r[4]===null?void 0:!!r[4],c;if(t!==null){if(c=this.getStreamDescription(t),!c){this._debug.error(`could not uncompress participant ID ${t}`);continue}}else c=null;if(a===null){this._debug.error(`unexpected null sequenceNumber`,e,r);continue}let l=Zr.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+`-`+e,u=i?i>>>0:null;n.push({participantStreamDescription:c,streamId:l,rtpTimestamp:u,sequenceNumber:a,fastScreenShare:o,suspend:s})}return{type:`notification`,notification:K.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:n}}},ri=function(e){return 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}({}),ii=class{constructor(e=z,t=null){h(this,`_worker`,null),h(this,`_debug`,void 0),h(this,`_logger`,void 0),this._debug=e,this._logger=t}async _createWorker(e,t,n=[],r={},i=[]){return new Promise((a,o)=>{let s=!1,c=!1,l=n.join(`,`),u=new Blob([e,`exports.default(${l});`],{type:`application/javascript; charset=utf-8`}),d=window.URL.createObjectURL(u),f=new Worker(d);window.URL.revokeObjectURL(d),this._worker=f;let p=e=>{c||(c=!0,o(e))},m=e=>{if(this._debug.warn(e),!s){p(e);return}t({type:ri.FRAME,error:e})};f.onerror=e=>{e.preventDefault?.(),m(this._formatWorkerError(e))},f.onmessageerror=e=>{e.preventDefault?.(),m(this._formatWorkerMessageError(e))},f.onmessage=e=>{switch(e.data.type){case ri.READY:s=!0,c||(c=!0,a());break;case ri.ERROR:s?m(e.data.error):p(e.data.error);break;case ri.FRAME:t(e.data);break;case ri.DEBUG:this._debug.debug(e.data.message);break;case ri.LOG_ERROR:this._logger?.log(C.ERROR,e.data.message);break}},this._sendToWorker(ri.INIT,r,i)})}_removeWorker(){this._worker?.terminate(),this._worker=null}_sendToWorker(e,t={},n=[]){this._worker?.postMessage(Object.assign({type:e},t),n)}_formatWorkerError(e){let t=e.message||e.error?.message||`Unknown worker error`,n=[[e.filename,e.lineno,e.colno].filter(Boolean).join(`:`),[e.error?.name,e.error?.stack].filter(Boolean).join(`: `)].filter(Boolean).join(` `);return`${this.constructor.name} Worker crashed: ${t}${n?` (${n})`:``}`}_formatWorkerMessageError(e){return`${this.constructor.name} Worker message error${e.origin?` from ${e.origin}`:``}`}static isBrowserSupported(){throw Error(`Not implemented`)}},ai=class extends ii{constructor(e=z,t=null){super(e,t)}async init(e,t,n){this._debug.debug(`LibVPxDecoder started`),await this._createWorker("var workerExports=(function(){var e=function(e){return 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}({});return(t,n)=>{let r=null,i=null,a=!0,o=!1;function s(){return t({locateFile:n}).then(e=>i=e)}function c(t,n,s,c){if(!i){self.postMessage({type:e.LOG_ERROR,message:`decoder-init-fail-libvpx`}),self.postMessage({type:e.FRAME,error:`Fatal initialization error`});return}if(a!==s&&(a=s,r&&(r=null,self.postMessage({type:e.DEBUG,message:`LibVPxDecoder codec changed to ${s?`VP9`:`VP8`} - reinitialize`}))),!r&&(self.postMessage({type:e.DEBUG,message:`LibVPxDecoder codec ${s?`VP9`:`VP8`}`}),r=new i.VpxDecoder,r.debug(c),!r.init(s?i.VpxType.VP9:i.VpxType.VP8))){r=null,self.postMessage({type:e.FRAME,error:`Decoder failed to create`});return}try{r.allocateBuffer(n.byteLength).set(new Uint8Array(n))}catch(t){self.postMessage({type:e.DEBUG,message:t}),r=null,self.postMessage({type:e.FRAME,error:String(t)});return}if(r.decode()&&r.nextImage())o=!1;else{self.postMessage({type:e.FRAME,error:`Decode failed`}),l();return}let u=r.getImageBuffer();if(!u){self.postMessage({type:e.FRAME,error:`No decoded data`});return}let d=r.getImageWidth(),f=r.getImageHeight();r.nextImage()&&(self.postMessage({type:e.DEBUG,message:`LibVPxDecoder dropped frame`}),self.postMessage({type:e.LOG_ERROR,message:`LibVPxDecoder-drop`}));let p=new Uint8ClampedArray(u.byteLength);p.set(u),self.postMessage({type:e.FRAME,data:p.buffer,width:d,height:f},[p.buffer])}function l(){o||(self.postMessage({type:e.FRAME,requestKeyFrame:!0}),o=!0)}s().then(()=>{self.onmessage=t=>{switch(t.data.type){case e.FRAME:c(t.data.timestamp,t.data.data,t.data.isVP9,t.data.debug);break}},self.postMessage({type:e.READY})}).catch(t=>{self.postMessage({type:e.ERROR,error:String(t)})})}})(),exports={default:workerExports};",r=>{r.error?(this._debug.warn(`LibVPxDecoder`,r.error),t(r.error)):r.requestKeyFrame?(this._debug.debug(`LibVPxDecoder requests key frame`),n()):e(new ImageData(new Uint8ClampedArray(r.data),r.width,r.height))},[u.default,u.default.getUrl])}decodeFrame(e,t,n,r){this._sendToWorker(ri.FRAME,{timestamp:e,data:t.buffer,isVP9:n,keyFrame:r,debug:z.enabled()},[t.buffer])}destroy(){this._removeWorker(),this._debug.debug(`LibVPxDecoder destroyed`)}static isBrowserSupported(){return`WebAssembly`in window&&`Worker`in window}},oi=class extends ii{constructor(e=z,t=null){super(e,t)}async init(e,t,n){this._debug.debug(`WebCodecsDecoder started`),await this._createWorker("var workerExports=(function(){var e=function(e){return e.VP9=`vp09.00.50.08`,e.VP8=`vp8`,e}({}),t=function(e){return 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}({});return n=>{let r=null,i=`no-preference`,a=!0,o=!1,s=!1,c=null,l=null;function u(e){return e instanceof Error?[e.name,e.message,e.stack].filter(Boolean).join(`: `):String(e)}function d(e,n){try{self.postMessage({type:t.FRAME,error:`WebCodecsDecoder ${e} failed: ${u(n)}`})}catch{}}function f(){self.postMessage({type:t.READY})}function p(e,n,r,i=!1){try{c={timestamp:e,data:n,isVP9:r,keyFrame:i};let a=h(r);if(o&&!i){self.postMessage({type:t.FRAME,error:`WebCodecsDecoder waiting for keyframe`}),m();return}else o&&i&&(o=!1,s=!1,self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder got keyframe. Start decoding`}));let l=new EncodedVideoChunk({type:i?`key`:`delta`,timestamp:e,data:n});a.decode(l)}catch(e){_(`because failed call decode: ${u(e)}`),d(`decode`,e);return}v(i)}self.onmessage=e=>{try{switch(e.data.type){case t.INIT:f();break;case t.FRAME:p(e.data.timestamp,e.data.data,e.data.isVP9,e.data.keyFrame);break}}catch(e){d(`message`,e)}};function m(){s||(self.postMessage({type:t.FRAME,requestKeyFrame:!0}),s=!0)}function h(e){if(a!==e&&(a=e,_(`because codec is changed to ${a?`VP9`:`VP8`}`)),!r){o=!0,self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec ${a?`VP9`:`VP8`}`}),r=new VideoDecoder({output:e=>{y(),g(e)},error:e=>{y(),_(`because error during decoding: ${u(e)}`),i===`prefer-software`?self.postMessage({type:t.FRAME,error:`WebCodecsDecoder failed, reinitialize: `+u(e)}):(i=`prefer-software`,c&&c.keyFrame&&p(c.timestamp,c.data,c.isVP9,c.keyFrame),self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec switch to prefer-software because decoding issue: ${u(e)}`}))}});try{r.configure(b(a,i))}catch(e){throw _(`because failed configure: ${u(e)}`),d(`configure`,e),e}}return r}function g(e){try{let r=n?[e]:[];self.postMessage({type:t.FRAME,data:e},r)}catch(n){try{self.postMessage({type:t.FRAME,data:e})}catch(e){d(`postMessage`,e),d(`postMessage transfer`,n)}}finally{try{e.close()}catch{}}}function _(e){if(r){try{r&&r.state!==`closed`&&r.close()}catch{}r=null,self.postMessage({type:t.FRAME,error:`WebCodecsDecoder reset ${e}`})}}function v(e=!1){l=setTimeout(()=>{_(`because of decode timeout`)},3e3)}function y(){l&&clearTimeout(l),l=null}function b(t,n){return{codec:t?e.VP9:e.VP8,hardwareAcceleration:n}}}})(),exports={default:workerExports};",r=>{r.error?(this._debug.warn(`WebCodecsDecoder`,r.error),t(r.error)):r.requestKeyFrame?(this._debug.debug(`WebCodecsDecoder requests key frame`),n()):(e(r.data),r.data.close())},[!0])}decodeFrame(e,t,n,r=!1){this._sendToWorker(ri.FRAME,{timestamp:e,data:t.buffer,isVP9:n,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),this._debug.debug(`WebCodecsDecoder destroyed`)}static isBrowserSupported(){return`VideoDecoder`in window&&`Worker`in window&&`VideoFrame`in window&&!E.isBrokenVP9Decoder()&&E.browserName()!==`Firefox`}},si=class{constructor(e=null,t=0){h(this,`_counter`,0),h(this,`_interval`,0),h(this,`_lastCalculationTime`,Date.now()),h(this,`_onCalculated`,null),this._onCalculated=e,t&&(this._interval=window.setInterval(()=>this.calculate(),t))}increment(e=1){this._counter+=e}calculate(){let e=Date.now(),t=e-this._lastCalculationTime,n=Math.round(this._counter*1e3/t);return this._counter=0,this._lastCalculationTime=e,this._onCalculated?.(n),n}destroy(){window.clearInterval(this._interval),this._interval=0}},ci=class{constructor(e,t){h(this,`_participantId`,void 0),h(this,`_statAggregator`,void 0),h(this,`_firstFrameReceived`,!1),this._participantId=e,this._statAggregator=t}measure(e,t){if(this._firstFrameReceived)return;this._firstFrameReceived=!0;let n=G.getMarkNameScreenshareFirstFrame(this._participantId),r=G.measureMark(n);r!==null&&this._statAggregator?.logEventualStat({name:U.SCREENSHARE_FIRST_FRAME,value:r,width:e,height:t})}},li=65536,ui=`MARK_SCREENSHARE_FREEZE_DURATION`,di=class e{constructor(e,t,n,r,i,a=z){h(this,`_participantId`,void 0),h(this,`_onStream`,void 0),h(this,`_onStat`,void 0),h(this,`_onKeyFrameRequested`,void 0),h(this,`_statScreenShareFirstFrame`,void 0),h(this,`_debug`,void 0),h(this,`_chunks`,[]),this._participantId=e,this._onStream=t,this._onStat=n,this._onKeyFrameRequested=i,this._statScreenShareFirstFrame=new ci(e,r),this._debug=a}appendChunk(t){let n=this._chunks.length;if(t.start)this._measureFreezeDuration(!1),this._measureFreezeDuration(!0),n&&(this._debug.warn(`[FrameBuilder] Cleanup buffer`,Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!n||(this._chunks[n-1].sequence+1)%li!==t.sequence){this._debug.warn(`[FrameBuilder] Got incorrect chunk`);return}if(this._chunks.push(t),t.end){let n=this._processFrameData(),{width:r,height:i}=e.getFrameSize(n);this._processFrame({timestamp:t.timestamp,frameData:n,isVP9:t.isVP9,keyframe:t.keyframe,width:r,height:i}),this._statScreenShareFirstFrame.measure(r,i)}}destroy(){G.clearMark(ui),G.clearMark(G.getMarkNameScreenshareFirstFrame(this._participantId)),this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((e,t)=>e+t.data.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(new Uint8Array(t.data),r),r+=t.data.byteLength;return n}static getFrameSize(e){let t={width:0,height:0},n=new d.BitStream(e.buffer);n.bigEndian=!0,n.index+=2;let r=n.readBits(1),i=n.readBits(1)<<1|r;return i===3&&n.index++,n.readBits(1)===1||n.readBits(1)!==0?t:(n.index++,n.index++,n.index+=24,i>=2&&n.index++,n.readBits(3)===7?(i===1||i===3)&&n.index++:(n.index++,(i===1||i===3)&&(n.index+=3)),t.width=n.readBits(16)+1,t.height=n.readBits(16)+1,t)}static isBrowserSupported(){throw Error("Method `isBrowserSupported` is not implemented")}_measureFreezeDuration(e){if(e){G.setMark(ui);return}let t=G.measureMark(ui);t!==null&&t>1e3&&this._onStat({freeze_duration:t})}},fi=class{constructor(e){h(this,`_onStream`,void 0),this._onStream=e}async drawFrame(e){throw Error("Method `drawFrame` is not supported by this implementation")}async drawImage(e){throw Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw Error("Method `isBrowserSupported` is not implemented")}},pi=class extends fi{constructor(e,t=z){super(e),h(this,`_useImageBitmap`,void 0),h(this,`_canvas`,null),h(this,`_canvasContext`,null),h(this,`_stream`,null),h(this,`_track`,null),h(this,`_debug`,void 0),this._debug=t,this._debug.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{}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}async _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,this._useImageBitmap){let t;if(e instanceof ImageBitmap)t=e;else{let{width:n,height:r,data:i}=e,a=n*r*4;if(i.byteLength!==a){this._debug.warn(`Bad frame buffer`,{w:n,h:r,got:i.byteLength,expected:a});return}t=await createImageBitmap(e,0,0,e.width,e.height)}if(!this._canvasContext){this._debug.warn(`Canvas context is null`),t.close();return}this._canvasContext.transferFromImageBitmap(t),t.close()}else{let n=this._canvasContext;n.clearRect(0,0,t.width,t.height),n.putImageData(e,0,0)}this._requestCanvasFrame()}async drawFrame(e){let t=`createImageBitmap`in e?await e.createImageBitmap():await createImageBitmap(e);await this._drawImage(t)}async drawImage(e){await this._drawImage(e)}destroy(){this._removeStream(),this._debug.debug(`CanvasRenderer destroyed`)}static isBrowserSupported(){return(`CanvasCaptureMediaStream`in window||`CanvasCaptureMediaStreamTrack`in window)&&!(E.browserName()===`Safari`&&Number(E.browserVersion())===15)}},mi=class extends fi{constructor(e,t=z){super(e),h(this,`_generator`,void 0),h(this,`_writer`,void 0),h(this,`_stream`,void 0),h(this,`_debug`,void 0),this._debug=t,this._debug.debug(`TrackGeneratorRenderer started`),this._generator=new MediaStreamTrackGenerator({kind:A.video}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}async drawFrame(e){await this._writer.write(e)}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),this._debug.debug(`TrackGeneratorRenderer destroyed`)}static isBrowserSupported(){return`VideoFrame`in window&&`MediaStreamTrackGenerator`in window&&oi.isBrowserSupported()}},hi=class extends di{constructor(e,t,n,r,i,a=z,o=null){super(e,t,n,r,i,a),h(this,`_renderer`,void 0),h(this,`_decoder`,void 0),h(this,`_decoderReady`,!1),h(this,`_decoderBusy`,!1),h(this,`_decoderQueue`,[]),h(this,`_webCodecsRetryAttempted`,!1),h(this,`_fpsMeter`,void 0),h(this,`_logger`,void 0),this._logger=o,this._debug.debug(`StreamBuilder started for participant [${e}]`),this._initFpsMeter(),this._initRenderer(),this._initDecoder()}_processFrame(e){e.keyframe&&(this._decoderQueue=[]),this._decoderQueue.push(e),this._decodeQueue()}_initFpsMeter(){this._fpsMeter=new si(e=>this._debug.log(`[StreamBuilder][${this._participantId}] fps: ${e}`),2e4)}_initRenderer(e=!1){e||!mi.isBrowserSupported()?this._renderer=new pi(this._onStream,this._debug):this._renderer=new mi(this._onStream,this._debug)}_initDecoder(e=!1){e||!oi.isBrowserSupported()?this._decoder=new ai(this._debug,this._logger):this._decoder=new oi(this._debug,this._logger),this._decoder.init(async e=>{this._decoderBusy=!1,`VideoFrame`in window&&e instanceof VideoFrame?await this._renderer.drawFrame(e):await this._renderer.drawImage(e),this._fpsMeter.increment(),this._decodeQueue()},e=>{if(this._decoderBusy=!1,this._decoder instanceof oi&&typeof e==`string`&&e.includes(`EncodingError`)){this._decoderQueue=[],!this._webCodecsRetryAttempted&&e.includes(`reset because error during decoding`)?(this._webCodecsRetryAttempted=!0,this._debug.warn(`StreamBuilder retry WebCodecs with software decoder`),this._onKeyFrameRequested?.()):this._switchToLibVPXDecoder();return}this._decodeQueue()},this._onKeyFrameRequested).then(()=>{this._decoderReady=!0,this._decodeQueue()}).catch(e=>{this._debug.warn(`StreamBuilder decoder init failed`,e),this._decoder instanceof oi&&this._switchToLibVPXDecoder()})}_switchToLibVPXDecoder(){this._debug.warn(`StreamBuilder switch to LibVPX decoder`),this._decoderQueue=[],this._fpsMeter&&this._fpsMeter.destroy(),this._decoder&&(this._decoderReady=!1,this._decoderBusy=!1,this._decoder.destroy()),this._renderer&&this._renderer.destroy(),this._initFpsMeter(),this._initRenderer(!0),this._initDecoder(!0),this._onKeyFrameRequested?.()}_decodeQueue(){if(!this._decoderReady||this._decoderBusy)return;let e=this._decoderQueue.shift();e&&(this._decoderBusy=!0,this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe))}destroy(){super.destroy(),this._fpsMeter.destroy(),this._decoder.destroy(),this._renderer.destroy(),this._debug.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return pi.isBrowserSupported()||mi.isBrowserSupported()}},gi=1,_i=1,vi=2,yi=0,bi=1,xi=2,Si=4,Ci=8;function wi(e,t,n,r,i,a,o){let s=0;t&&(s|=bi),n&&(s|=xi),r&&(s|=Si),o||(s|=Ci);let c=new ArrayBuffer(11),l=new DataView(c);if(l.setUint8(0,gi),l.setUint16(1,i),l.setUint32(3,e),l.setUint8(7,+!!a),l.setUint16(8,yi),l.setUint8(10,s),!o)return c;let u=new Uint8Array(c.byteLength+o.byteLength);return u.set(new Uint8Array(c),0),u.set(new Uint8Array(o),c.byteLength),u.buffer}function Ti(e){let t=new DataView(e),n=t.getUint8(0),r=t.getUint16(1),i=t.getUint32(3),a=t.getUint8(7)===1,o=t.getUint16(8),s=t.getUint8(10),c=!!(s&bi),l=!!(s&xi),u=!!(s&Si),d=!!(s&Ci);if(n!==gi)throw Error(`Unexpected protocol version. Got ${n}, expected ${gi}`);return{timestamp:i,start:c,end:l,keyframe:u,sequence:r,isVP9:a,ssrc:o,eos:d,data:e.slice(11)}}function Ei(e){if(!e||!e.byteLength||e.byteLength!==4)return!1;let t=new DataView(e);return!(t.getUint8(0)!==gi||t.getUint8(1)!==_i||t.getUint16(2)!==yi)}function Di(e){if(!e||!e.byteLength||e.byteLength!==10)return null;let t=new DataView(e);return t.getUint8(0)!==gi||t.getUint8(1)!==vi||t.getUint16(2)!==yi?null:{seq:t.getUint16(4),ts2:t.getUint32(6)}}function Oi(e){let t=new ArrayBuffer(4),n=new DataView(t);return n.setUint8(0,gi),n.setUint8(1,_i),n.setUint16(2,e),t}var ki=2**15-1,Ai=1,ji=5,Mi=5,Ni=class e{constructor(e,t=z){h(this,`_mediaSource`,void 0),h(this,`_codec`,void 0),h(this,`_sourceBuffer`,null),h(this,`_queue`,[]),h(this,`_clearBufferTill`,0),h(this,`_debug`,void 0),this._mediaSource=new MediaSource,this._codec=e,this._debug=t;let n=()=>{this._mediaSource.removeEventListener(`sourceopen`,n),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener(`sourceopen`,n,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let e=this._sourceBuffer.buffered.start(0);e<this._clearBufferTill&&(this._sourceBuffer.remove(e,this._clearBufferTill),this._debug.debug(`[WebmBuilder] SourceBuffer cleanup from ${e} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let t=this._queue;this._queue=[];let n=e._buildQueue(t);this._sourceBuffer.appendBuffer(n)}static _buildQueue(e){if(!e.length)return new Uint8Array;if(e.length===1)return f.build(e[0]);let t=e.reduce((e,t)=>e+t.countSize(),0),n=new Uint8Array(t),r=0;for(let t of e){let e=f.build(t);n.set(e,r),r+=e.byteLength}return n}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode=`sequence`,this._sourceBuffer.addEventListener(`updateend`,()=>this._handleQueue())}changeType(e){return this._codec=e,this._sourceBuffer?.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){this._mediaSource?.readyState===`open`&&this._sourceBuffer?.abort();let e=this._sourceBuffer?.buffered,t=e?.length;if(!t)return;let n=e.start(0),r=Math.max(0,e.end(t-1)-ji);r-n>Mi&&(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(){return this._sourceBuffer?.buffered}},Pi=class e extends di{constructor(e,t,n,r,i=z){super(e,t,n,r,void 0,i),h(this,`_mediaBuffer`,null),h(this,`_video`,null),h(this,`_stream`,null),h(this,`_earliestTimestamp`,0),h(this,`_clusterStartTime`,0),h(this,`_lastFrameTimestamp`,0),this._debug.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return f.element(f.ID.EBML,[f.element(f.ID.EBMLVersion,f.number(1)),f.element(f.ID.EBMLReadVersion,f.number(1)),f.element(f.ID.EBMLMaxIDLength,f.number(4)),f.element(f.ID.EBMLMaxSizeLength,f.number(8)),f.element(f.ID.DocType,f.string(`webm`)),f.element(f.ID.DocTypeVersion,f.number(2)),f.element(f.ID.DocTypeReadVersion,f.number(2))])}static _genSegmentHeader(e,t,n){let r=f.element(f.ID.Info,[f.element(f.ID.TimecodeScale,f.number(1e6)),f.element(f.ID.MuxingApp,f.string(`vk-webm-builder`)),f.element(f.ID.WritingApp,f.string(`vk-webm-builder`))]),i=[f.element(f.ID.PixelWidth,f.number(e)),f.element(f.ID.PixelHeight,f.number(t))],a=f.element(f.ID.Tracks,f.element(f.ID.TrackEntry,[f.element(f.ID.TrackNumber,f.number(Ai)),f.element(f.ID.TrackUID,f.number(Ai)),f.element(f.ID.TrackType,f.number(1)),f.element(f.ID.FlagLacing,f.number(0)),f.element(f.ID.DefaultDuration,f.number(1e9)),f.element(f.ID.CodecID,f.string(`V_${n.toUpperCase()}`)),f.element(f.ID.Video,i)]));return f.unknownSizeElement(f.ID.Segment,[r,a])}static _genClusterHeader(e){return f.unknownSizeElement(f.ID.Cluster,[f.element(f.ID.Timecode,f.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new Ni(e,this._debug),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){this._debug.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let e=this._video.seekable;e.length&&(this._video.currentTime=e.end(e.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>this._debug.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video?.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(t){let n=t.isVP9?`vp9`:`vp8`;this._mediaBuffer?this._mediaBuffer.codec!==n&&this._mediaBuffer.changeType(n):this._createVideo(n);let r=t.timestamp;if(r<=this._lastFrameTimestamp&&(r=this._lastFrameTimestamp+10,this._debug.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=r,this._earliestTimestamp)r-=this._earliestTimestamp;else{if(!t.keyframe)return;this._earliestTimestamp=r,r=0}if(t.keyframe){this._clusterStartTime=r,this._mediaBuffer?.cleanup(),this._debug.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let i=e._genWebmHeader();this._mediaBuffer?.append(i);let a=e._genSegmentHeader(t.width,t.height,n);this._mediaBuffer?.append(a)}let i=Math.round(r-this._clusterStartTime);if(i>ki&&(this._clusterStartTime=r,i=0),i===0){this._debug.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let t=e._genClusterHeader(this._clusterStartTime);this._mediaBuffer?.append(t)}let a=f.element(f.ID.SimpleBlock,[f.vintEncodedNumber(Ai),f.bytes(e._intToU16BE(i)),f.number(!!t.keyframe<<7),f.bytes(t.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),this._debug.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){return`captureStream`in window.HTMLVideoElement?.prototype&&window.MediaSource?.isTypeSupported(`video/webm; codecs="vp8"`)&&window.MediaSource?.isTypeSupported(`video/webm; codecs="vp9"`)}},Fi=class{constructor(e,t,n,r,i,a=null,o=z,s=null){h(this,`_datachannel`,void 0),h(this,`_participantIdRegistry`,null),h(this,`_streamBuilders`,{}),h(this,`_onStream`,()=>{}),h(this,`_onEos`,()=>{}),h(this,`_onStat`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_statAggregator`,void 0),this._debug=o,this._logger=s,this._statAggregator=a,this._debug.debug(`ScreenCaptureReceiver started`),this._datachannel=e,this._participantIdRegistry=t,this._onStream=n,this._onEos=r,this._onStat=i,this._datachannel.onmessage=e=>this._onDataChannelMessage(e.data)}_onDataChannelMessage(e){let t=Ti(e),n=this._participantIdRegistry?.getStreamDescription(t.ssrc)?.participantId;if(!n){this._debug.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(n),this._onEos(n);return}let r=this._streamBuilders[n];if(!r){let e=e=>this._onStream(n,e);r=N.screenShareWebmBuilder&&Pi.isBrowserSupported()?new Pi(n,e,this._onStat,this._statAggregator,this._debug):new hi(n,e,this._onStat,this._statAggregator,()=>{this._requestKeyFrame(t.ssrc)},this._debug,this._logger),this._streamBuilders[n]=r}r.appendChunk(t)}_requestKeyFrame(e){if(!(!this._datachannel||this._datachannel.readyState!==`open`))try{let t=Oi(e);this._datachannel.send(t),this._debug.debug(`ScreenCaptureReceiver request for keyframe for ssrc ${e}`)}catch(e){this._debug.warn(`Failed to send keyframe request`,e)}}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,this._debug.debug(`ScreenCaptureReceiver destroyed`)}},Ii=class{constructor(e,t,n){h(this,`_prev`,void 0),h(this,`_next`,void 0),h(this,`_data`,void 0),this._next=n,n&&(n.prev=this),this._prev=t,t&&(t.next=this),this._data=e}get prev(){return this._prev}set prev(e){this._prev=e}get next(){return this._next}set next(e){this._next=e}get data(){return this._data}},Li=class{constructor(){h(this,`_head`,null),h(this,`_tail`,null),h(this,`_length`,0)}get length(){return this._length}push(...e){for(let t of e)this._tail=new Ii(t,this._tail,null),this._head||(this._head=this._tail),this._length++}merge(e){this._tail&&(this._tail.next=e._head),this._head||(this._head=e._head),this._tail=e._tail,this._length+=e._length,e.clear()}shift(){if(!this._length||!this._head)return null;let e=this._head;return this._head=e.next,this._head&&(e.next=null,this._head.prev=null),this._length--,this.length===1?this._tail=this._head:this.length||(this._head=this._tail=null),e.data}bisect(){if(this.length){let e=this.length>1?Math.floor(this.length/2):1;for(let t=0;t<e;t++)this.shift()}}head(){return this._head?.data||null}tail(){return this._tail?.data||null}clear(){this._head=null,this._tail=null,this._length=0}toString(){let e=[],t=this._head;for(;t!==null;)e.push(t.data),t=t.next;return e.length?JSON.stringify(e,(e,t)=>t instanceof Error?String(t):t):``}},Ri=1e3,zi=class extends ii{constructor(e,t,n,r,i=z,a=null){super(i,a),h(this,`_sourceTrack`,void 0),h(this,`_onFrame`,void 0),h(this,`_useCongestionControl`,void 0),h(this,`_maxBitrate`,void 0),h(this,`_useImageCapture`,void 0),h(this,`_video`,null),h(this,`_imageCapture`,null),h(this,`_canvas`,null),h(this,`_canvasCtx`,null),h(this,`_frameReadTimeout`,0),h(this,`_lastFrame`,null),this._sourceTrack=e,this._onFrame=t,this._useCongestionControl=n,this._maxBitrate=r,this._useImageCapture=`ImageCapture`in window&&ImageCapture.prototype.grabFrame!==void 0&&`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{}this._canvasCtx=null,this._canvas=null,this._video=null}async _createStream(e){if(!this._canvas)throw Error(`Canvas not found`);if(!this._video&&!this._useImageCapture)throw Error(`Video element not found`);return new Promise((t,n)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=e=>t(),r.onerror=()=>n(Error(`Video element error`));let i=r.play(),a=()=>n(Error(`Autoplay is disabled`));i?i.catch(a):a()}})}_removeStream(){window.clearTimeout(this._frameReadTimeout),this._lastFrame?.close(),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video)throw 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._canvasCtx.getImageData(0,0,e,t)}async _getFrameBitmap(){if(!this._imageCapture)throw Error(`Destroyed`);return this._imageCapture.grabFrame()}_drawFrameData(e){if(!this._canvas||!this._canvasCtx)throw Error(`Destroyed`);let t=e.width,n=e.height;return this._canvas.width=t,this._canvas.height=n,this._canvasCtx.clearRect(0,0,t,n),this._canvasCtx.drawImage(e,0,0,t,n),this._canvasCtx?.getImageData(0,0,t,n)}async init(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;this._debug.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?`VP9`:`VP8`}`),await this._createStream(this._sourceTrack),await this._createWorker("var workerExports=(function(){var e=function(e){return 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}({});return(t,n,r,i)=>{let a;function o(o,s){return t({locateFile:n}).then(t=>{if(a=new t.VpxEncoder,a.debug(s),!a.init(o?t.VpxType.VP9:t.VpxType.VP8))throw self.postMessage({type:e.LOG_ERROR,message:`encoder-init-fail-libvpx`}),Error(`LibVPxEncoder failed to create`);if(r){let e=Math.round(i/1e3);a.setTargetBitrate(e)}else a.setMaxQuantizer(10),a.setTargetBitrate(1024)})}function s(t,n,r,i){let o=a.allocateImage(t,n);if(!o){self.postMessage({type:e.FRAME,error:`No buffer data`});return}o.set(new Uint8Array(r));let s=Math.round(performance.now());if(!a.encode(s,150,i)){self.postMessage({type:e.FRAME,error:`Encode failed`});return}let c=a.readFrame();if(!c){self.postMessage({type:e.FRAME,error:`No encoded data`});return}a.readFrame()&&(self.postMessage({type:e.DEBUG,message:`LibVPxEncoder dropped frame`}),self.postMessage({type:e.LOG_ERROR,message:`LibVPxEncoder-drop`}));let l=new Uint8Array(c.byteLength);l.set(c),self.postMessage({type:e.FRAME,frameType:i?`key`:`delta`,timestamp:s,duration:150,width:t,height:n,data:l.buffer},[l.buffer])}function c(e,t){let n=Math.round(e/1e3);a.setTargetBitrate(n)}self.onmessage=t=>{switch(t.data.type){case e.INIT:o(t.data.isVP9,t.data.debug).then(()=>self.postMessage({type:e.READY})).catch(t=>self.postMessage({type:e.ERROR,error:String(t)}));break;case e.FRAME:s(t.data.width,t.data.height,t.data.imageData,t.data.keyFrame);break;case e.SET_BITRATE:c(t.data.bitrate,t.data.useCbr);break}}}})(),exports={default:workerExports};",e=>{e.error?this._onFrame(null,e.error):this._onFrame({type:e.frameType,timestamp:e.timestamp,duration:e.duration,data:e.data,byteLength:e.data?.byteLength,width:e.width,height:e.height})},[u.default,u.default.getUrl,this._useCongestionControl,this._maxBitrate],{isVP9:this.isVP9(),debug:z.enabled()})}_encode(e,t){let n=e.data.buffer;this._sendToWorker(ri.FRAME,{width:e.width,height:e.height,imageData:n,keyFrame:t},[n])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){window.clearTimeout(this._frameReadTimeout),this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},Ri),this._getFrameBitmap().then(t=>{window.clearTimeout(this._frameReadTimeout),this._lastFrame?.close(),this._lastFrame=t;let n=this._drawFrameData(t);this._encode(n,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}setBitrate(e,t,n){this._sendToWorker(ri.SET_BITRATE,{bitrate:e,useCbr:t})}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),this._debug.debug(`LibVPxEncoder destroyed`)}},Bi=class extends ii{constructor(e,t,n,r,i,a,o=z,s=null){super(o,s),h(this,`_sourceTrack`,void 0),h(this,`_trackProcessor`,void 0),h(this,`_onFrame`,void 0),h(this,`_useCongestionControl`,void 0),h(this,`_maxBitrate`,void 0),h(this,`_useCbr`,void 0),h(this,`_frameRate`,void 0),this._sourceTrack=e,this._onFrame=t,this._useCongestionControl=n,this._maxBitrate=r,this._useCbr=i,this._frameRate=a,this._trackProcessor=new MediaStreamTrackProcessor({track:e})}async init(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,n=this._trackProcessor.readable;this._debug.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?`VP9`:`VP8`}`),await this._createWorker("var workerExports=(function(){var e=function(e){return e.VP9=`vp09.00.50.08`,e.VP8=`vp8`,e}({}),t=function(e){return 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}({});return()=>{let n,r,i,a,o,s,c=null,l=0,u=!1,d=0,f,p,m=!1,h=!1,g=null;function _(e){return e instanceof Error?[e.name,e.message,e.stack].filter(Boolean).join(`: `):String(e)}function v(e,n){try{self.postMessage({type:t.FRAME,error:`WebCodecsEncoder ${e} failed: ${_(n)}`})}catch{}}function y(e,n){try{self.postMessage({type:t.ERROR,error:`WebCodecsEncoder ${e} failed: ${_(n)}`})}catch{}}function b(e){try{n=e.readable,r=n.getReader(),i=e.width,a=e.height,o=e.isVP9,s=e.framerate,f=e.useCongestionControl,p=e.maxBitrate,f&&(d=p,m=e.useCbr),T(),C(),self.postMessage({type:t.READY})}catch(e){y(`init`,e)}}function x(e){e&&!h&&(h=!0),self.clearTimeout(l),l=self.setTimeout(()=>{c&&S(c,h)},1e3),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(l)}).then(({done:e,value:t})=>{if(c?.close(),c=null,!(e||!t)){if(!g){r.releaseLock(),n.cancel();return}c=t,S(t,h)}}).catch(e=>{v(`read`,e)}))}function S(e,t){try{let n=e.codedWidth!==i||e.codedHeight!==a;n&&(i=e.codedWidth,a=e.codedHeight,t=!0),!g||g.state===`closed`?(T(),C()):n&&C(),g?.encode(e,{keyFrame:t}),t&&(h=!1)}catch(e){g&&g.state===`closed`&&(g=null),v(`encode`,e)}}function C(){if(!g)throw Error(`encoder is not initialized`);let t={framerate:s,codec:o?e.VP9:e.VP8,width:i,height:a,latencyMode:`realtime`,bitrateMode:m?`constant`:`variable`};d>0&&(t.bitrate=d),g.configure(t)}function w(e,t,n){try{d=e,m=t,s=n,(!g||g.state===`closed`)&&T(),C()}catch(e){v(`setBitrate`,e)}}function T(){g=new VideoEncoder({output:e=>{try{let n;e.data?n=e.data:(n=new ArrayBuffer(e.byteLength),e.copyTo(n)),self.postMessage({type:t.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,width:i,height:a,data:n},[n])}catch(e){v(`output`,e)}},error:e=>{g&&g.state===`closed`&&(g=null),v(`codec`,e)}})}self.onmessage=e=>{try{switch(e.data.type){case t.INIT:b(e.data);break;case t.FRAME:x(e.data.keyFrame);break;case t.SET_BITRATE:w(e.data.bitrate,e.data.useCbr,e.data.fps);break}}catch(e){v(`message`,e)}}}})(),exports={default:workerExports};",e=>{e.error?this._onFrame(null,e.error):this._onFrame({type:e.frameType,timestamp:e.timestamp,duration:e.duration,data:e.data,byteLength:e.data?.byteLength,width:e.width,height:e.height})},[],{readable:n,width:e,height:t,isVP9:this.isVP9(),framerate:this._frameRate,useCongestionControl:this._useCongestionControl,maxBitrate:this._maxBitrate,useCbr:this._useCbr},[n])}requestFrame(e=!1){this._sendToWorker(ri.FRAME,{keyFrame:e})}setBitrate(e,t,n){this._sendToWorker(ri.SET_BITRATE,{bitrate:e,useCbr:t,fps:n})}isVP9(){return!0}destroy(){this._removeWorker(),this._debug.debug(`WebCodecsEncoder destroyed`)}static isBrowserSupported(){return`VideoEncoder`in window&&`Worker`in window&&`EncodedVideoChunk`in window&&`MediaStreamTrackProcessor`in window}},Vi=2100,Hi=600,Ui=1.2,Wi=.8,Gi=2e3,Ki=8e3,qi=8e3,Ji=16e3,Yi=4,Xi=2e3,Zi=function(e){return e[e.NONE=0]=`NONE`,e[e.UP=1]=`UP`,e[e.DOWN=2]=`DOWN`,e}(Zi||{}),Qi=class{constructor(e,t,n,r,i,a,o,s=z){h(this,`_onCongestion`,void 0),h(this,`_ccEnabled`,void 0),h(this,`_fastSharing`,void 0),h(this,`_trendDelayThreshold`,void 0),h(this,`_highDelayThreshold`,void 0),h(this,`_targetFps`,void 0),h(this,`_minBitrate`,void 0),h(this,`_maxBitrate`,void 0),h(this,`_targetBitrate`,void 0),h(this,`_lastDown`,void 0),h(this,`_lastUp`,void 0),h(this,`_lastProbing`,void 0),h(this,`_lastCheckDelay`,void 0),h(this,`_upPenalty`,0),h(this,`_probing`,void 0),h(this,`_delayAvgShort`,-1),h(this,`_delayAvgLong`,-1),h(this,`_minDelay`,Number.MAX_VALUE),h(this,`_maxDelay`,0),h(this,`_largeDelayDuration`,0),h(this,`_lastFpsCalcMs`,void 0),h(this,`_frames`,0),h(this,`_fps`,0),h(this,`_debug`,void 0),this._onCongestion=e,this._ccEnabled=r,this._debug=s,this._minBitrate=t,this._maxBitrate=n,this._fastSharing=i,this._targetFps=o,a>0?this._highDelayThreshold=a:this._highDelayThreshold=Vi,i&&(this._highDelayThreshold=Hi),this._trendDelayThreshold=Math.round(this._highDelayThreshold/3),this._targetBitrate=this._maxBitrate,this._probing=!1;let c=Date.now();this._lastDown=0,this._lastUp=c,this._lastProbing=c,this._lastCheckDelay=0,this._lastFpsCalcMs=0}checkDelay(e,t,n){let r=Date.now();if(this._calcFps(r),this._calcDelay(t,r),this._delayAvgShort<=0||this._delayAvgLong<=0||!this._ccEnabled)return;let i=0,a=this._delayAvgShort-this._delayAvgLong,o=Math.round(Math.abs(a)*100/this._delayAvgLong),s=a>40&&o>30&&this._delayAvgShort>this._trendDelayThreshold,c=this._delayAvgShort>this._highDelayThreshold;s||c?i=2:Math.abs(a)<40&&o<10&&!c&&(i=1);let l=Math.round(this._targetBitrate/1e3),u=n;e%20==0&&this._debug.debug(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Zi[i]} tr=${l} br=${n}`);let d=r-this._lastDown;if(i===2&&d>Gi){this._probing&&(this._upPenalty=Math.min(++this._upPenalty,Yi),this._probing=!1);let n=Wi*u*1e3;if(n>=this._targetBitrate&&(n=this._targetBitrate*Wi),n=Math.max(n,this._minBitrate),n<this._targetBitrate){let r=Math.round(n/1e3),s=Math.round(this._upPenalty*qi/1e3);this._debug.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Zi[i]}`),this._debug.log(`#${e}: cc: DOWN delay=${t} bitrate=${u} target=${l} -> newBitrate=${r} penalty=${s}s`),this._setBitrate(n,!0),this._targetBitrate=n}this._lastDown=r}let f=r-this._lastUp,p=Ki+this._upPenalty*qi;if(i===1&&f>p&&d>p){let n=Math.min(this._targetBitrate*Ui,this._maxBitrate);if(n>this._targetBitrate){let s=Math.round(n/1e3),c=Math.round(this._targetBitrate/1e3),l=Math.round(this._upPenalty*qi/1e3);this._debug.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Zi[i]}`),this._debug.log(`#${e}: cc: UP bitrate=${u} target=${c} -> newBitrate=${s} penalty=${l}s`),this._setBitrate(n,!1),this._targetBitrate=n,this._probing=!0,this._lastProbing=r,this._lastUp=r}}let m=r-this._lastProbing;this._probing&&m>Ji&&(this._probing=!1);let ee=r-this._lastDown;this._upPenalty>0&&ee>3*p&&(this._debug.log(`#${e}: cc: UP reset penalty: oldPenalty=${this._upPenalty}`),this._upPenalty=0)}_setBitrate(e,t){this._fastSharing&&(t=!0);let n=this._targetFps;this._fps>0&&(n=this._fps),this._onCongestion(e,t,n)}_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>Xi){let e=t-this._lastCheckDelay;this._largeDelayDuration+=e}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}_calcFps(e){this._frames++;let t=e-this._lastFpsCalcMs;if(t>5e3){this._lastFpsCalcMs=e;let n=this._fps,r=this._frames*1e3/t;this._fps===0?this._fps=Math.round(r):this._fps=Math.round((this._fps*3+r)/4),this._frames=0,this._fps!==n&&this._debug.log(`cc: fps=${this._fps}`)}}},$i=class{constructor(e){h(this,`_maxSize`,void 0),h(this,`_size`,0),h(this,`_buffer`,void 0),h(this,`_head`,0),h(this,`_tail`,0),this._maxSize=e,this._buffer=Array(e)}add(e,t,n,r,i){this._tail===this._head&&this._size>0&&(this._head=++this._head%this._maxSize);let a=this._tail;return this._buffer[this._tail]={seq:e,ts:t,size:n,sent:Date.now(),start:r,end:i,ts2:-1,recv:-1},this._tail=++this._tail%this._maxSize,this._size++,a}update(e,t){let n=this.get(e);return n===null?null:(n.ts2=t,n.recv=Date.now(),n)}get(e){let t=this._head;for(let n=0;n<this._maxSize;n++){let n=this._buffer[t];if(e===n?.seq)return n;if(t=++t%this._maxSize,t===this._tail)break}return null}getServerBitrateK(e){let t=0,n=0,r=-1,i=-1,a=this._tail;for(let t=0;t<this._maxSize;t++){a>0?--a:a=this._maxSize-1;let t=this._buffer[a];if(!t||(i===-1&&(i=t.ts2,n=0),i>=0&&(n+=t.size),r=t.ts2,i-r>=e)||a===this._head)break}if(r>=0&&i>=0){let e=i-r;t=Math.round(e>0?n*8/e:0)}return t}getCurrentDelay(){let e=this._tail;for(let t=0;t<this._maxSize;t++){e>0?--e:e=this._maxSize-1;let t=this._buffer[e];if(!t)break;if(t.recv>=0&&t.sent>=0)return t.recv-t.sent;if(e===this._head)break}return 0}getMaxBandwidth(){let e=0,t=0,n=-1,r=-1,i=this._tail;for(let a=0;a<this._maxSize;a++){i>0?--i:i=this._maxSize-1;let a=this._buffer[i];if(a){if(r===-1&&a.end&&!a.start&&(r=a.ts2,t=0),n===-1&&r>=0&&a.start&&!a.end&&(n=a.ts2),n>=0&&r>=0){let i=r-n;e=i>0?t*8/i:0;break}if(r>=0&&(t+=a.size),i===this._head)break}}return Math.round(e)}clear(){this._buffer.fill(void 0),this._size=0,this._head=0,this._tail=0}},ea=65536,ta=50,na=400,ra=1e6,ia=3e5,aa=3e4,oa=2e3,sa=5,ca=0,la=class{constructor(e,t,n,r,i=z,a=null){h(this,`_encoder`,void 0),h(this,`_datachannel`,void 0),h(this,`_signaling`,void 0),h(this,`_fastSharing`,void 0),h(this,`_destroyed`,!1),h(this,`_needKeyframe`,!0),h(this,`DATA_SIZE`,void 0),h(this,`_congestionControl`,void 0),h(this,`_frameNum`,0),h(this,`_width`,void 0),h(this,`_height`,void 0),h(this,`_feedback`,new $i(1024)),h(this,`_lastSentFrameSeq`,0),h(this,`_lastDeliveredFrameSeq`,0),h(this,`_lastFrameDelay`,0),h(this,`_lastFramerateReduced`,Date.now()),h(this,`_lastSharingStat`,Date.now()),h(this,`_congestionControlEnabled`,void 0),h(this,`_queue`,new Li),h(this,`_fpsMeter`,void 0),h(this,`_maxFrameDelay`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),this._debug=i,this._logger=a,this._debug.debug(`ScreenCaptureSender started`),this.DATA_SIZE=N.consumerScreenDataChannelPacketSize-11,this._datachannel=t,this._signaling=n,this._fastSharing=r,this._congestionControlEnabled=N.screenShareCongestionControl||this._fastSharing,this._width=e.getSettings().width,this._height=e.getSettings().height,this._maxFrameDelay=this._fastSharing?N.screenShareCongestionControlThreshold:N.screenShareCongestionControlThreshold*2;let o=N.getScreenFrameRate(this._fastSharing),{minBitrate:s,maxBitrate:c}=this._calcMinMaxBitrate(this._width,this._height),l=this._onCongestionCallback.bind(this);this._debug.log(`ScreenCaptureSender: CongestionControl: enabled=${this._congestionControlEnabled} minBitrate=${Math.round(s/1e3)}k maxBitrate=${Math.round(c/1e3)}k delayThreshold=${N.screenShareCongestionControlThreshold}`),this._congestionControl=new Qi(l,s,c,this._congestionControlEnabled,this._fastSharing,N.screenShareCongestionControlThreshold,o,this._debug);let u=(e,t)=>{if(this._destroyed)return;if(!e){this._debug.warn(`requestFrame failed, keyFrame: `+this._needKeyframe,t),this._needKeyframe=!0,this._handleQueue();return}(e.width!==this._width||e.height!==this._height)&&(this._width=e.width,this._height=e.height,this._onResize(this._width,this._height));let n=this._sliceFrame(e);this._queue.merge(n),this._handleQueue(),this._sendSharingStat()};if(Bi.isBrowserSupported()){let t=this._fastSharing;this._encoder=new Bi(e,u,this._congestionControlEnabled,c,t,o,this._debug,this._logger)}else this._encoder=new zi(e,u,this._congestionControlEnabled,c,this._debug,this._logger);this._datachannel.onmessage=e=>{Ei(e.data)&&(this._debug.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0);let t=Di(e.data);t!==null&&this._checkCcFeedback(t)},this._encoder.init().then(()=>this._handleQueue()).catch(e=>this._debug.warn(`ScreenCaptureSender init failed`,e)),this._fpsMeter=new si(e=>this._debug.log(`[ScreenCaptureSender] fps: ${e}`),5e3)}_handleQueue(){if(this._destroyed)return;let e=this._queue.shift();if(!e){if((this._lastSentFrameSeq-this._lastDeliveredFrameSeq+ea)%ea>sa&&this._lastFrameDelay>this._maxFrameDelay){let e=Date.now();e-this._lastFramerateReduced>oa&&(this._lastFramerateReduced=e,this._debug.debug(`[ScreenCaptureSender] reduce framerate: delay=${this._lastFrameDelay} maxDelay=${this._maxFrameDelay}`))}else this._requestFrame();return}if(!this._sendFrameChunk(e)){this._needKeyframe=this._needKeyframe||!this._cleanupQueue(),M.setImmediate(()=>this._handleQueue());return}if(e.isLast){this._frameNum++,this._fpsMeter.increment(),e.isKey&&this._debug.debug(`#${this._frameNum}: sharing: send keyframe size=${Math.round(e.frameSize/1e3)}k`);let t=this._feedback.getCurrentDelay(),n=this._feedback.getServerBitrateK(2e3);t>0&&this._congestionControl.checkDelay(this._frameNum,t,n)}else M.setImmediate(()=>this._handleQueue())}_cleanupQueue(){let e=this._queue.head();for(;e;){if(e.isFirst&&e.isKey)return!0;this._queue.shift(),e=this._queue.head()}return!1}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_sliceFrame(e){let t=e.type===`key`,n=e.data.byteLength,r=new Li;for(let i=0;i<n;i+=this.DATA_SIZE){let a=e.data.slice(i,i+this.DATA_SIZE),o=i===0,s=n<=i+a.byteLength,c=this._wrapHeader(e.timestamp,o,s,t,a);r.push({data:c.data,sequence:c.sequence,frameSize:n,isFirst:o,isLast:s,isKey:t,timestamp:e.timestamp})}return r}_wrapHeader(e,t,n,r,i){let a=wi(e,t,n,r,ca,this._encoder.isVP9(),i),o={sequence:ca,data:a};return ca=(ca+1)%ea,o}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null).data}_sendFrameChunk(e){if(!this._datachannel||this._datachannel.readyState!==`open`)return!1;try{return this._datachannel.send(e.data),this._feedback.add(e.sequence,e.timestamp,e.data.byteLength,e.isFirst,e.isLast),e.isLast&&(this._lastSentFrameSeq=e.sequence),!0}catch(e){return this._debug.warn(`Error sending chunk to DataChannel`,e),!1}}destroy(){this._queue.clear(),this._fpsMeter.destroy(),this._datachannel.onmessage=null,this._feedback.clear(),this._datachannel.readyState===`open`&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),this._debug.debug(`ScreenCaptureSender destroyed`)}static isBrowserSupported(){return Bi.isBrowserSupported()||zi.isBrowserSupported()}_onCongestionCallback(e,t,n){this._encoder.setBitrate(e,t,n)}_onResize(e,t){let{minBitrate:n,maxBitrate:r}=this._calcMinMaxBitrate(e,t),i=Math.round(n/1e3),a=Math.round(r/1e3);this._debug.log(`cc: resize to ${e}x${t}, minBitrate=${i} maxBitrate=${a}`),this._congestionControl.reconfigure(n,r)}_calcMinMaxBitrate(e,t){(e===void 0||e<640)&&(e=640),(t===void 0||t<360)&&(t=360);let n=e*t/256;return{minBitrate:Math.max(ia,Math.min(ra,Math.round(n*ta))),maxBitrate:Math.round(n*na)}}_checkCcFeedback(e){let t=this._feedback.update(e.seq,e.ts2);if(t===null)this._debug.debug(`cc: update failed, seq=${e.seq}`);else if(t.end){this._lastDeliveredFrameSeq=t.seq;let e=t.recv-t.sent;e>0&&(this._lastFrameDelay=e),this._handleQueue()}}_sendSharingStat(){let e=Date.now();if(e-this._lastSharingStat>aa){let t=this._congestionControl.getStat();t!==null&&(this._debug.debug(`cc: send stats: ${JSON.stringify(t)}`),this._signaling.reportSharingStat(t).catch(e=>{!(e instanceof Dn)&&!(e instanceof On)&&this._debug.warn(`Unable to send sharing stats`,e)})),this._lastSharingStat=e}}},ua=class{constructor(e,t,n,r=z,i=null){h(this,`_pc`,null),h(this,`_transceiver`,null),h(this,`_currentSimulcastInfo`,null),h(this,`_signaling`,void 0),h(this,`_mediaSource`,void 0),h(this,`_getCameraSettings`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),this._signaling=e,this._mediaSource=t,this._getCameraSettings=n,this._debug=r,this._logger=i}async configureFromRemoteOffer(e){if(this.reset(),!N.simulcast)return;let t=this._findTransceiver(e);if(!t){this._debug.debug(`SimulcastSender: Multi-encoding video transceiver not found`);return}let n=this._mediaSource.getStream(),r=n?.getVideoTracks()[0];if(!n||!r){this._debug.debug(`SimulcastSender: Camera stream or track not found`);return}this._pc=e,this._transceiver=t,t.direction=`sendonly`,await t.sender.replaceTrack(r),t.sender.setStreams(n),await this._applyCurrentMediaState(),this._debug.log(`SimulcastSender: Prepared mid=${t.mid} encodings=${JSON.stringify(t.sender.getParameters().encodings)}`)}finalizeAnswer(e){if(!this._pc||!this._transceiver?.mid)return e;this._pc.getTransceivers().forEach(e=>{e.mid===null&&e.stop()});let t=fn(e),n=this._findMediaSection(t,this._transceiver.mid);if(n){for(let e=n.start;e<n.end;e++)if(t[e].startsWith(`a=simulcast:send `)){t[e]=t[e].replaceAll(`~`,``);break}let e=this._mediaSource.getStream()?.getVideoTracks()[0];e&&this._getConfig(Zt.WIDTH,Zt.HEIGHT,e.getSettings().frameRate).simulcastInfo.streams.forEach(e=>{let r=`a=rid:${e.rid} send`;for(let i=n.start;i<n.end;i++)if(t[i]===r||t[i].startsWith(r+` `)){t[i]=`${r} max-width=${e.width};max-height=${e.height};max-fps=${e.fps};max-br=${e.bitrate}`;break}})}return pn(t)}async sync({force:e=!1}={}){if(!this._transceiver||!this._currentSimulcastInfo||!this._mediaSource.mediaSettings.isVideoEnabled)return;let t=this._mediaSource.getStream()?.getVideoTracks()[0];if(!t)return;let n=this._getTrackConfig(t);if(!e&&nn(this._currentSimulcastInfo,n.simulcastInfo))return;let r=await this._applyConfig(n,!0);r&&(this._debug.log(`SimulcastSender: Sync ${n.width}x${n.height} encodings=${JSON.stringify(r.encodings)}`),await this._changeSimulcast({mediaSource:Yt.CAMERA,simulcastInfo:n.simulcastInfo}))}replaceTrack(e){let t=this._transceiver,n=t?.sender.track;if(!t||e.kind!==A.video||!n||n.contentHint!==e.contentHint)return!1;let r=this._mediaSource.mediaSettings.isVideoEnabled;return t.sender.replaceTrack(e).then(()=>{if(!r)return;let{width:t,height:n}=e.getSettings();t&&n&&this._syncReplacedTrack(e).catch(e=>{this._debug.error(`SimulcastSender: Failed to sync replaced track`,e)})}).catch(e=>{this._debug.error(`SimulcastSender: Unable to replace track`,e),this._logger?.log(C.ERROR,`replaceTrack-single`)}),!0}reset(){this._pc=null,this._transceiver=null,this._currentSimulcastInfo=null}_findTransceiver(e){for(let t of e.getTransceivers())if((t.sender.track?.kind??t.receiver.track?.kind)===A.video&&t.sender.getParameters().encodings.length>1)return t;return null}_findMediaSection(e,t){let n=-1;for(let r=0;r<e.length;r++)if(e[r].startsWith(`m=`)&&(n=r),e[r]===`a=mid:${t}`){if(n<0||!e[n].startsWith(`m=video`))return null;let t=e.findIndex((e,t)=>t>r&&e.startsWith(`m=`));return{start:n,end:t<0?e.length:t}}return null}_getConfig(e,t,n=30){let r=this._getCameraSettings(),i=r?.maxFramerate?Math.min(n||30,r.maxFramerate):n||30,a=r?.bitrates?.generic?.length?r.bitrates.generic:void 0;return{width:e,height:t,simulcastInfo:on(e,t,a,i),maxDimension:r?.maxDimension,maxBitrate:!a&&r?.maxBitrateK?r.maxBitrateK*1024:void 0}}_getTrackConfig(e){let t=e.getSettings();return this._getConfig(t.width??Zt.WIDTH,t.height??Zt.HEIGHT,t.frameRate)}async _applyConfig(e,t=!1){let n=this._transceiver;if(!n)return null;let r=n.sender.getParameters();if(r.encodings.length<=1)return null;cn(r.encodings,e.simulcastInfo,e.maxDimension,e.maxBitrate);try{await n.sender.setParameters(r)}catch(e){if(this._debug.error(`SimulcastSender: Failed to set sender parameters`,r,e),!t)throw e}return this._currentSimulcastInfo=e.simulcastInfo,r}async _applyCurrentMediaState(){let e=this._mediaSource.getStream()?.getVideoTracks()[0];if(!e)return;let t=this._mediaSource.mediaSettings.isVideoEnabled?this._getTrackConfig(e):this._getConfig(N.videoMinWidth,N.videoMinHeight,e.getSettings().frameRate),n=await this._applyConfig(t);n&&this._debug.log(`SimulcastSender: Current media state ${t.width}x${t.height} encodings=${JSON.stringify(n.encodings)}`)}async _syncReplacedTrack(e){let t=this._getTrackConfig(e);this._currentSimulcastInfo=t.simulcastInfo,await this._changeSimulcast({mediaSource:Yt.CAMERA,simulcastInfo:t.simulcastInfo})}async _changeSimulcast(e){try{await this._signaling.changeSimulcast(e)}catch(e){if(!(e instanceof On))throw e}}},da=90,fa=4294967295,pa=class e extends Lr{constructor(e,t,n,r=z,i=null,a=null,o=null,s=null){super(e,t,s),h(this,`_producerNotification`,null),h(this,`_producerCommand`,null),h(this,`_producerScreen`,null),h(this,`_consumerScreen`,null),h(this,`_asr`,null),h(this,`_animojiDataChannel`,null),h(this,`_animojiReceiver`,null),h(this,`_animojiSender`,null),h(this,`_isOpen`,!1),h(this,`_observer`,!1),h(this,`_reconnectionPrevented`,!1),h(this,`_statInterval`,null),h(this,`_settingsInterval`,null),h(this,`_monitorRtpShareInterval`,null),h(this,`_statBytes`,{}),h(this,`_ssrcMap`,{}),h(this,`_ssrcMapUpdated`,!1),h(this,`_perfStatReporter`,void 0),h(this,`_producerOfferIsProcessing`,!1),h(this,`_producerNextOffer`,null),h(this,`_producerNextSessionId`,null),h(this,`_lastStat`,null),h(this,`_serverSettings`,void 0),h(this,`_prevConsumerSettings`,{}),h(this,`_prevConsumerFastSharingSettings`,{}),h(this,`_asrTrack`,null),h(this,`_captureSender`,null),h(this,`_captureReceiver`,null),h(this,`_participantIdRegistry`,null),h(this,`_disabledSenders`,new Set),h(this,`_rtpReceiversByStreamId`,{}),h(this,`_producerSessionId`,``),h(this,`_newAudioShareTrack`,null),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_statAggregator`,void 0),h(this,`_codecStatsAggregator`,void 0),h(this,`_simulcast`,void 0),this._debug=r,this._logger=i,this._statAggregator=a,this._codecStatsAggregator=o,this._serverSettings=n,this._simulcast=new ua(e,t,()=>this._serverSettings.camera,r,i),this.subscribe(this._signaling,Sr.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Jt.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Jt.SOURCE_CHANGED,this._onSourcesChanged.bind(this)),this.subscribe(this._mediaSource,Jt.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._createPerfStatsReporter(),this._debug.debug(`ServerTransport: Created`)}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==q.IDLE&&e!==q.CLOSED&&e!==q.FAILED&&this._startStatInterval()}open(e=!1){if(this._isOpen){this._debug.log(`ServerTransport: Already opened connections`);return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen&&(this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(this._debug.error(`ServerTransport: Closed`,e),this._setState(q.FAILED)):(this._debug.debug(`ServerTransport: Closed`),this._setState(q.CLOSED)))}removeParticipant(e){this._captureReceiver?.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){jr(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}setAnimojiTransport(e,t){if(N.vmoji&&(this._animojiReceiver=e,this._animojiSender=t,this._participantIdRegistry&&e.setParticipantIdRegistry(this._participantIdRegistry),this._animojiDataChannel)){e.setDataChannel(this._animojiDataChannel),t.setDataChannel(this._animojiDataChannel);return}}async onCameraResolutionChanged(){await this._simulcast.sync()}_createPerfStatsReporter(){this._perfStatReporter?.destroy(),this._perfStatReporter=new va(this,this._signaling,this._statAggregator,!1,this._debug)}_closeConnection(){this._signaling.resetProducerConnection(),this._ssrcMap={},this._ssrcMapUpdated=!0,this._disposeFirstMediaSentProbe(),this._stopStatInterval(),this._stopSettingsInterval(),this._stopMonitorRtpShareInterval(),this._removeAsrTrack(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._simulcast.reset(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>e.track?.stop()),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,e._closeDataChannel(this._producerNotification),e._closeDataChannel(this._producerCommand),e._closeDataChannel(this._producerScreen),e._closeDataChannel(this._consumerScreen),e._closeDataChannel(this._asr),e._closeDataChannel(this._animojiDataChannel),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(Y.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,n){this._debug.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let e=r.readyState;e===`open`?(this._debug.debug(`[${t}] data channel opened`),n(r)):this._debug.error(`[${t}] data channel open failed, state [${e}]`)},r.onerror=e=>{let n=e.error;this._debug.error(`[${t}] data channel error`,n?.errorDetail,n?.message)}}_openConnection(e=!1){this._debug.debug(`ServerTransport: Open single connection`);try{this._pc=new RTCPeerConnection}catch(e){this._debug.error(`Failed to create RTCPeerConnection:`,e),this.close(e);return}this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=M.debounce(e=>{this._pc&&this._onConnectionStateChange(this._pc,e)},500),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this,this._pc),this._participantIdRegistry=new ni(this._debug),this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._createDataChannel(this._pc,Er.producerNotification,e=>{this._producerNotification=e,this._producerNotification.binaryType=`arraybuffer`,this._signaling.setProducerNotificationDataChannel(e)}),this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,Er.producerCommand,e=>{this._producerCommand=e,this._signaling.setProducerCommandDataChannel(e)}),this._createDataChannel(this._pc,Er.producerScreenShare,e=>{this._producerScreen=e,this._producerScreen.binaryType=`arraybuffer`,this._createCaptureReceiver()}),N.asrDataChannel&&this._createDataChannel(this._pc,Er.asr,e=>{this._asr=e,this._asr.binaryType=`arraybuffer`,this._removeAsrTrack(),this._asrTrack=new $r(e,this._participantIdRegistry,e=>{this._onAsrTranscription(e)},this._debug)}),N.vmoji&&this._createDataChannel(this._pc,Er.animoji,e=>{this._animojiDataChannel=e,this._animojiDataChannel.binaryType=`arraybuffer`,this._animojiReceiver?.setDataChannel(e),this._animojiReceiver?.setParticipantIdRegistry(this._participantIdRegistry),this._animojiSender?.setDataChannel(e),this._animojiSender?.setProtocolVersion(N.vmojiOptions.protocolVersion||1)}),this._newAudioShareTrack=this._mediaSource.getAudioShareTrack();try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1),this._prevConsumerSettings={},this._prevConsumerFastSharingSettings={},this._applyConsumerSettings()}catch(e){this._debug.error(`ServerTransport: Unable to add media source tracks`,e),this._logger?.log(C.ERROR,`addTrack-single`),this.close(e);return}this._startFirstMediaSentProbe(),this._createDataChannel(this._pc,Er.consumerScreenShare,e=>{this._consumerScreen=e,this._consumerScreen.binaryType=`arraybuffer`;let t=this._mediaSource.getScreenTrack();t&&(!N.consumerFastScreenShare||!this._mediaSource.mediaSettings.isFastScreenSharingEnabled)&&this._createCaptureSender(t)}),e||this._allocateConsumer(),this._setState(q.OPENED),this._startStatInterval(),this._startSettingsInterval(),this._startMonitorRtpShareInterval()}_removeAsrTrack(){this._asrTrack?.destroy(),this._asrTrack=null}_reconnect(){this.getState()!==q.OPENED&&(this._setState(q.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(Y.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(Y.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(Y.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(Y.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&(this._ssrcMap={},this._ssrcMapUpdated=!0,fn(e.sdp).forEach(e=>{let t=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Zr.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+)|(?:${Zr.TRANSPARENT_AUDIO_TRACK_PREFIX}-[0-9]+))`,n=new RegExp(t).exec(e);n&&(this._ssrcMap[n[1]]=n[3])}))}_createCaptureSender(e){let t=this._mediaSource.mediaSettings;!e||!this._consumerScreen||!t.isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new la(e,this._consumerScreen,this._signaling,t.isFastScreenSharingEnabled,this._debug,this._logger))}_removeCaptureSender(){this._captureSender?.destroy(),this._captureSender=null}_createCaptureReceiver(){this._producerScreen&&(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new Fi(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(Y.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(Y.REMOTE_STREAM_SECOND,e,null)},e=>{this._triggerEvent(Y.SCREEN_SHARING_STAT,e)},this._statAggregator,this._debug,this._logger))}_removeCaptureReceiver(){this._captureReceiver?.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(n=>{if(!n.track||n.track.kind!==A.video||n.track.contentHint===`motion`)return;let r=!this._disabledSenders.has(n),i=e.maxDimension!==0;if(r&&!i){this._debug.log(`Disabling video upload`),this._disabledSenders.add(n),n.replaceTrack(E.getBlackMediaTrack()).catch(e=>{this._debug.error(`Could not disable video upload`,e)});return}let a=this._mediaSource.getSendVideoTrack();if(!r&&i&&a){this._debug.log(`Enabling video upload`),this._disabledSenders.delete(n);let e=n.track;e.enabled=a.enabled,n.replaceTrack(a).then(()=>e.stop()).catch(e=>{this._debug.error(`Could not enable video upload`,e)})}M.applyVideoTrackSettings(e,n,a??n.track,this._prevConsumerSettings,t,this._debug)}),this._prevConsumerSettings=t}if(this._mediaSource.mediaSettings.isFastScreenSharingEnabled&&N.consumerFastScreenShare){let e=this._serverSettings.fastScreenSharing;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(n=>{!n.track||n.track.kind!==A.video||n.track.contentHint!==`motion`||M.applyVideoTrackSettings(e,n,n.track,this._prevConsumerFastSharingSettings,t,this._debug)}),this._prevConsumerFastSharingSettings=t}}}_onScreenSharingStatus(e){e.track?(!N.consumerFastScreenShare||!this._mediaSource.mediaSettings.isFastScreenSharingEnabled)&&this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(Y.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(e=>{this._reportStats(e),this._detectStaleTracks(e),this._codecStatsAggregator?.reportUsage(e)}).catch(()=>{}),this._statInterval=window.setTimeout(e,N.statisticsInterval)};this._statInterval=window.setTimeout(e,N.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)}async _collectStat(){if(!this._pc)return Promise.reject();this._ssrcMapUpdated&&(this._lastStat=null,this._ssrcMapUpdated=!1,this._createPerfStatsReporter());let e=await G.collectStats(this._pc,this._lastStat,this._ssrcMap,!0);return this._lastStat=e,e}_reportStats(e){this._triggerEvent(Y.REMOTE_DATA_STATS,{inbound:{topology:J.SERVER,transport:e.transport,rtps:e.rtps.filter(e=>e.type===`inbound-rtp`)},outbound:{topology:J.SERVER,transport:e.transport,rtps:e.rtps.filter(e=>e.type===`outbound-rtp`)},remoteInbound:{topology:J.SERVER,transport:e.transport,rtps:e.remoteRtps??[]}})}_detectStaleTracks(e){let t=e.rtps.find(e=>e.type===`inbound-rtp`&&e.kind===`audio`&&this._ssrcMap[e.ssrc]===`mix`);if(!t)return;let n=Zr.AUDIO_MIX,r=this._statBytes[n],i=!1;if(r){let e=t.bytesReceived-r.bytesReceived;e>=0&&e<=5&&(i=!0),r.stalled!==i&&this._triggerEvent(Y.AUDIO_MIX_STALL,i)}this._statBytes[n]={bytesReceived:t.bytesReceived,stalled:i}}_allocateConsumer(){if(!this._signaling.ready)return;let e=wa.get();!N.videoTracksCount&&!this._observer&&this._debug.warn(`Setting videoTracksCount to 0 is deprecated`),this._signaling.allocateConsumer(null,e).catch(e=>{e instanceof Dn||this._debug.warn(`ServerTransport: Unable to allocate consumer`,e)})}async _processOffer(e,t){if(!this._pc)throw Error(`Interrupt allocation`);try{await this._pc.setRemoteDescription(e)}catch(e){throw this._debug.error(`[single] unable to set remote offer`,e),this._logger?.log(C.ERROR,`setRemoteDescription-single`),e}await this._simulcast.configureFromRemoteOffer(this._pc);let n;try{if(await this._handleTracks(),this._debug.debug(`[single] create local answer`),!this._pc)throw Error(`Interrupt allocation`);n=await this._pc.createAnswer()}catch(e){throw this._debug.error(`[single] unable to create answer`,e),this._logger?.log(C.ERROR,`createAnswer-single`),e}try{if(!this._pc)throw Error(`Interrupt allocation`);n.sdp=M.patchLocalSDP(n.sdp,!1,E.isBrokenH264Decoder(),!1),this._debug.debug(`[single] set local answer`,{answer:n}),await this._pc.setLocalDescription(n)}catch(e){throw this._debug.error(`[single] unable to set local answer`,e),this._logger?.log(C.ERROR,`setLocalDescription-single`),e}n.sdp=this._simulcast.finalizeAnswer(n.sdp);try{this._debug.debug(`[single] transmit local answer`,{answer:n}),this._updateSSRCMap(e),await this._signaling.acceptProducer(n,Object.keys(this._ssrcMap),t),this._debug.debug(`[single] remote offer has been processed`)}catch(e){this._debug.warn(`[single] unable to send local answer`,e),this._logger?.log(C.ERROR,`acceptProducer`)}await this._simulcast.sync({force:!0})}async _acceptProducer(e,t){if(this._producerOfferIsProcessing){this._producerNextOffer=e,this._producerNextSessionId=t,this._debug.debug(`[single] wait until other remote offer is processed`);return}this._producerOfferIsProcessing=!0;let n={type:`offer`,sdp:M.patchRemoteSDP(e,!1,!1,!1,E.isBrokenVP9Encoder(),E.isBrokenVP9Decoder())};if(this._debug.debug(`[single] set remote offer`,{offer:n}),!this._pc)throw Error(`Interrupt allocation`);try{if(await this._processOffer(n,t),this._producerOfferIsProcessing=!1,this._producerNextOffer&&this._producerNextSessionId){this._debug.debug(`[single] there is other unprocessed remote offer, process it`);let e=this._producerNextOffer,t=this._producerNextSessionId;this._producerNextOffer=null,this._producerNextSessionId=null,await this._acceptProducer(e,t)}}catch(e){this.close(e)}}async _replaceScreenShareTrack(){let e=this._pc?.getTransceivers().find(e=>e.mid?.endsWith(`s`)&&e?.receiver?.track.kind===A.video);if(!e||!e.sender){this._debug.warn(`Cannot find screenshare transceiver`);return}try{e.direction=`sendonly`,await e.sender.replaceTrack(this._mediaSource.getScreenShareTrack())}catch(e){this._debug.error(`ServerTransport: Unable to replace track`,e)}}async _handleTracks(){this._observer||(await this._handleAudioShareTrack(),await this._handleScreenShareTrack())}async _handleAudioShareTrack(){if(!this._newAudioShareTrack)return;let e=this._pc?.getTransceivers().find(e=>e.mid?.endsWith(`s`)&&e?.receiver?.track.kind===A.audio);if(!e||!e.sender){this._debug.warn(`Cannot find audioshare transceiver`);return}e.sender.track!==null&&this._debug.warn(`Unexpected track assigned to audioshare`);try{e.direction=`sendonly`,await e.sender.replaceTrack(this._newAudioShareTrack),this._newAudioShareTrack=null}catch(e){this._debug.error(`ServerTransport: Unable to replace track`,e),this._logger?.log(C.ERROR,`replaceTrack-single`)}}async _handleScreenShareTrack(){this._mediaSource.getScreenShareTrack()&&await this._replaceScreenShareTrack()}async _onSignalingNotification(e){if(this._isOpen)switch(e.notification){case K.PRODUCER_UPDATED:await this._onProducerUpdated(e);break;case K.REALLOC_CON:this._reconnect();break;case K.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case K.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case K.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case K.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}}_onAsrTranscription(e){this._triggerEvent(Y.ASR_TRANSCRIPTION,e)}async _onProducerUpdated(e){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),N.breakVideoPayloadTypes&&(this._debug.log(`test mode enabled, video switched off`),this._signaling.requestTestMode(`breakVideoPayloadTypes`,null).catch(e=>{e instanceof Dn||this._debug.warn(`Unable to enable signaling test mode`,e)})),this._producerSessionId=e.sessionId,await this._acceptProducer(e.description,e.sessionId)}_onAddTrack(e,t){this._debug.debug(`[single] remote track (added)`,{track:t.track});let n=t.streams[0];n?(n.onremovetrack||(n.onremovetrack=e=>{this._triggerEvent(Y.REMOTE_TRACK_REMOVED,n.id,n,e.track)}),n.getTracks().find(e=>e.id===t.track.id)||(this._debug.warn(`[single] remote track missing from stream, re-adding`,{streamId:n.id,trackId:t.track.id}),this._logger?.log(C.ERROR,`ontrack-empty-stream`),n.addTrack(t.track)),this._rtpReceiversByStreamId[n.id]=t.receiver,this._triggerEvent(Y.REMOTE_TRACK_ADDED,n.id,n,t.track)):this._debug.error(`[single] unable to get media stream from track event`)}_onSignalingStateChange(e,t){this._debug.debug(`[single] signaling state changed`,{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(this._debug.debug(`[single] connection state changed`,{state:e.connectionState},t),this._logger?.log(C.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case`failed`:this._reconnectionPrevented?this.close(Error(`Ice connection failed`)):this._reconnect();break;case`connecting`:let t=this.getState();t===q.IDLE||t===q.OPENED?this._setState(q.CONNECTING):e.iceConnectionState===`checking`&&this._setState(q.RECONNECTING);break;case`disconnected`:this._reconnectionPrevented?this.close(Error(`Ice connection disconnected`)):this._setState(q.RECONNECTING);break;case`connected`:this._setState(q.CONNECTED),M.getPeerConnectionHostInfo(e).then(e=>{e?.local&&(this._logger?.log(C.ICE_CONNECTION_TYPE,e.local.type),this._debug.debug(`Selected ICE candidates`,e))});break}}_onReplacedTrack(e,t){if(this._pc){this._debug.debug(`_onReplacedTrack: newTrack=${e}, sendTrack=${t}`),t&&(e=t);let n=(e,t)=>{e.replaceTrack(t).catch(e=>{this._debug.error(`ServerTransport: Unable to replace track`,e),this._logger?.log(C.ERROR,`replaceTrack-single`)})};if(this._debug.log(`_onReplacedTrack: newTrack=${e.getSettings().width}x${e.getSettings().height}`),!this._simulcast.replaceTrack(e)){let t=this._pc?.getSenders().find(t=>t.track&&t.track.kind===e.kind&&!this._disabledSenders.has(t)&&t.track.contentHint===e.contentHint);t?.track?n(t,e):e.kind===A.audio&&e.contentHint===`music`&&(this._newAudioShareTrack=e)}}this._applyConsumerSettings()}async _onSourcesChanged({kind:e}){e===A.screen&&N.consumerFastScreenShare&&this._mediaSource.mediaSettings.isFastScreenSharingEnabled&&await this._replaceScreenShareTrack(),this._applyConsumerSettings()}getStreamWaitingTimeMs(e,t){if(!this._pc)return this._logger?.log(C.PAT_WAITING_TIME_ERROR,`noConnection`),this._debug.error(`Cannot get stream waiting time, peer connection is not initialized`),0;if(!RTCRtpReceiver.prototype.getSynchronizationSources)return this._logger?.log(C.PAT_WAITING_TIME_ERROR,`oldBrowser`),this._debug.error(`Cannot get stream waiting time, RTCRtpReceiver.getSynchronizationSources is not supported`),0;let n=this._rtpReceiversByStreamId[e];if(!n)return this._logger?.log(C.PAT_WAITING_TIME_ERROR,`noReceiver`),this._debug.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=n.getSynchronizationSources();if(!r||!r.length)return this._debug.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let i=r[0].rtpTimestamp;if(!Number.isInteger(i))return this._logger?.log(C.PAT_WAITING_TIME_ERROR,`timestampNotInteger`),this._debug.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${i}`),0;let a=t-i&fa,o=Math.ceil(a/da);return Math.min(100,Math.max(0,o))}async _monitorRtpShare(){let e=ti.getInstance().value;if(!this._mediaSource.mediaSettings.isFastScreenSharingEnabled||!N.consumerFastScreenShare||e<.6)return;let t=this._pc?.getSenders().find(e=>e.track?.kind===A.video&&e.track?.contentHint===`motion`);t&&(await t.getStats()).forEach(e=>{if(e.type===`outbound-rtp`&&this._serverSettings.fastScreenSharing&&e.frameWidth<this._serverSettings.fastScreenSharing.maxDimension&&e.frameWidth<window.screen.width){let n=t.getParameters();n.degradationPreference=`maintain-resolution`,t.setParameters(n),this._debug.log(`
|
|
7
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("webrtc-adapter");c=s(c);let l=require("messagepack"),u=require("@vkontakte/libvpx");u=s(u);let d=require("bit-buffer"),f=require("simple-ebml-builder");f=s(f);let p=require("fflate");p=s(p);var m=class{log(e,t,n=!1){}destroy(){}};function ee(e){"@babel/helpers - typeof";return ee=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},ee(e)}function te(e,t){if(ee(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(ee(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ne(e){var t=te(e,`string`);return ee(t)==`symbol`?t:t+``}function h(e,t,n){return(t=ne(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var re=25*1024*1024,ie=10,ae=`_okcls_logs_session_`,oe=3e4,se=`ok-calls-sdk-debug-logs`,ce=1,g=`sessions`,_=`chunks`,le=120*1e3,ue=new Set([`WARN`,`ERROR`]);function de(){return`${Date.now()}_${Math.random().toString(36).slice(2)}`}function fe(){let e=de();return pe(e),e}function pe(e){We.has(e)||We.set(e,[]),Ge.has(e)||Ge.set(e,0),Ke.has(e)||Ke.set(e,null)}function me(e){return Ke.get(e)??null}function he(e){let t=Ge.get(e)??0;return Ge.set(e,t+1),t}function ge(e,t){return`${e}:${String(t).padStart(12,`0`)}`}function _e(e){return new Blob([e]).size}function ve(){try{let e=window.localStorage;for(let t of Object.keys(e))t.indexOf(ae)===0&&e.removeItem(t)}catch(e){console.error(`Storage is blocked`,e)}}var v=new class{constructor(){h(this,`_db`,null),h(this,`_dbPromise`,null),h(this,`_dbName`,se),h(this,`_supported`,this.isSupported())}get supported(){return this._supported}open(){return this.isSupported()?(this._dbPromise||(this._dbPromise=new Promise(e=>{let t=window.indexedDB.open(this._dbName,ce);t.onupgradeneeded=()=>{this.createSchema(t.result)},t.onsuccess=()=>{this._db=t.result,this._supported=!0,this._db.onversionchange=()=>{this.close()},e(this._db)},t.onerror=()=>{console.warn(`Failed to open debug log storage`,t.error),this._supported=!1,this._dbPromise=null,e(null)},t.onblocked=()=>{console.warn(`Debug log storage opening is blocked`)}})),this._dbPromise):(this._supported=!1,Promise.resolve(null))}close(){this._db&&(this._db.close(),this._db=null),this._dbPromise=null}async clearForTests(){if(this._supported=this.isSupported(),this._dbName===se&&(this._dbName=`${se}-test-${Math.random().toString(36).slice(2)}`,this.close()),this._supported){let e=await this.open();if(e){let t=e.transaction([g,_],`readwrite`);t.objectStore(g).clear(),t.objectStore(_).clear(),await this.txDone(t).catch(e=>console.warn(`Failed to clear debug log storage`,e))}}this.close()}async getAllSessions(){let e=await this.open();if(!e)return[];let t=e.transaction(g,`readonly`),n=await this.requestToPromise(t.objectStore(g).getAll());return await this.txDone(t),n}async getSessionsByConversationId(e){let t=await this.open();if(!t)return[];let n=t.transaction(g,`readonly`),r=await this.requestToPromise(n.objectStore(g).index(`conversationId`).getAll(e));return await this.txDone(n),r.sort((e,t)=>e.startTime-t.startTime)}async getSessionBySessionId(e){let t=await this.open();if(!t)return[];let n=t.transaction(g,`readonly`),r=await this.requestToPromise(n.objectStore(g).get(e));return await this.txDone(n),r?[r]:[]}async getChunksBySession(e){let t=await this.open();if(!t)return[];let n=t.transaction(_,`readonly`),r=await this.requestToPromise(n.objectStore(_).index(`sessionId`).getAll(e));return await this.txDone(n),r.sort((e,t)=>e.sequence-t.sequence)}async putSession(e){let t=await this.open();if(!t)return!1;let n=t.transaction(g,`readwrite`);return n.objectStore(g).put(e),await this.txDone(n),!0}async putSessionAndChunk(e,t){let n=await this.open();if(!n)return!1;let r=n.transaction([g,_],`readwrite`);return r.objectStore(g).put(e),r.objectStore(_).put(t),await this.txDone(r),!0}async updateSessionConversationId(e,t){let[n]=await this.getSessionBySessionId(e);n&&await this.putSession({...n,conversationId:t,updatedAt:Math.max(n.updatedAt,Date.now())})}async deleteSession(e){let t=await this.open();if(!t)return 0;let n=await this.getChunksBySession(e),r=t.transaction([g,_],`readwrite`),i=r.objectStore(_),a=0;for(let e of n)a+=e.bytes,i.delete(e.id);return r.objectStore(g).delete(e),await this.txDone(r),a}async deleteChunks(e){let t=await this.open();if(!t||!e.length)return;let n=t.transaction(_,`readwrite`),r=n.objectStore(_);for(let t of e)r.delete(t.id);await this.txDone(n)}async estimateStorage(){return navigator.storage?.estimate?navigator.storage.estimate().catch(()=>null):null}async getStorageSummary(){let e=await this.getAllSessions();return{sessions:e,callsCount:this.groupSessions(this.getCallSessions(e)).length,usedBytes:e.reduce((e,t)=>e+t.bytes,0)}}async enforceRetentionPolicy(){let e=await this.getAllSessions(),t=this.groupSessions(this.getCallSessions(e)),n=this.getGlobalSessions(e),r=e.reduce((e,t)=>e+t.bytes,0);for(;r>re&&n.length;){let e=n.shift();if(!e)break;r-=await this.deleteSession(e.sessionId)}for(;t.length>ie||t.length>1&&r>re;){let e=t.shift();if(!e)return;for(let t of e.sessions)r-=await this.deleteSession(t.sessionId)}t.length===1&&r>re&&await this.trimOldestChunks(t[0],r-re),e=await this.getAllSessions(),t=this.groupSessions(this.getCallSessions(e)),n=this.getGlobalSessions(e),(t.length>ie||e.reduce((e,t)=>e+t.bytes,0)>re)&&await this.enforceRetentionPolicy()}createSchema(e){if(!e.objectStoreNames.contains(g)){let t=e.createObjectStore(g,{keyPath:`sessionId`});t.createIndex(`conversationId`,`conversationId`,{unique:!1}),t.createIndex(`updatedAt`,`updatedAt`,{unique:!1})}e.objectStoreNames.contains(_)||e.createObjectStore(_,{keyPath:`id`}).createIndex(`sessionId`,`sessionId`,{unique:!1})}isSupported(){return typeof window<`u`&&!!window.indexedDB}requestToPromise(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}txDone(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}getCallKey(e){return e.conversationId||e.sessionId}getCallSessions(e){return e.filter(e=>e.conversationId!==null)}getGlobalSessions(e){return e.filter(e=>e.conversationId===null).sort((e,t)=>e.updatedAt===t.updatedAt?e.startTime===t.startTime?e.sessionId.localeCompare(t.sessionId):e.startTime-t.startTime:e.updatedAt-t.updatedAt)}groupSessions(e){let t=new Map;for(let n of e){let e=this.getCallKey(n),r=t.get(e);r||(r={key:e,sessions:[],bytes:0,startTime:n.startTime,updatedAt:0},t.set(e,r)),r.sessions.push(n),r.bytes+=n.bytes,r.startTime=Math.min(r.startTime,n.startTime),r.updatedAt=Math.max(r.updatedAt,n.updatedAt)}return Array.from(t.values()).sort((e,t)=>e.updatedAt===t.updatedAt?e.startTime===t.startTime?e.key.localeCompare(t.key):e.startTime-t.startTime:e.updatedAt-t.updatedAt)}async updateSessionFromChunks(e){let t=await this.getChunksBySession(e.sessionId);if(!t.length){await this.deleteSession(e.sessionId);return}let n=t.reduce((e,t)=>e+t.bytes,0),r=t.reduce((e,t)=>e+t.items.length,0),i=t[0].startTime,a=t[t.length-1].endTime;await this.putSession({...e,startTime:i,endTime:a,updatedAt:a,bytes:n,entriesCount:r})}async trimOldestChunks(e,t){let n=[];for(let t of e.sessions){let e=await this.getChunksBySession(t.sessionId);n.push(...e.map(e=>({...e,session:t})))}n.sort((e,t)=>e.startTime===t.startTime?e.sequence-t.sequence:e.startTime-t.startTime);let r=n.slice(0,Math.max(n.length-1,0)),i=0,a=new Map,o=[];for(let e of r)if(o.push(e),i+=e.bytes,a.set(e.sessionId,e.session),i>=t)break;await this.deleteChunks(o);for(let e of a.values())await this.updateSessionFromChunks(e);return i}};async function ye(e){return e.sessionId?v.getSessionBySessionId(e.sessionId):e.conversationId?v.getSessionsByConversationId(e.conversationId):[]}async function be(e,t,n,r){if(!r.length)return;let i=me(e)||t,a=r,o=JSON.stringify(a),s=_e(o);for(;s>re&&a.length>1;)a=a.slice(Math.floor(a.length/2)),o=JSON.stringify(a),s=_e(o);if(s>re)return;let c=a[0].t,l=a[a.length-1].t,[u]=await v.getSessionBySessionId(e),d=u||{sessionId:e,conversationId:i,startTime:c,endTime:l,updatedAt:l,bytes:0,entriesCount:0},f={...d,conversationId:i||d.conversationId,startTime:Math.min(d.startTime,c),endTime:Math.max(d.endTime,l),updatedAt:Math.max(d.updatedAt,l),bytes:d.bytes+s,entriesCount:d.entriesCount+a.length},p={id:ge(e,n),sessionId:e,sequence:n,startTime:c,endTime:l,bytes:s,items:a};await v.putSessionAndChunk(f,p)&&await v.enforceRetentionPolicy()}function xe(e){let t=new WeakSet;try{return JSON.parse(JSON.stringify(e,(e,n)=>{if(n instanceof Error||typeof n==`bigint`||typeof n==`function`||typeof n==`symbol`)return String(n);if(n&&typeof n==`object`){if(t.has(n))return`[Circular]`;t.add(n)}return n}))}catch{return e.map(e=>String(e))}}function Se(e){let t=We.get(e);if(!t?.length)return Ye;let n=t.splice(0),r=me(e),i=he(e);return Ye=Ye.then(()=>be(e,r,i,n)).catch(e=>{console.warn(`Failed to write debug log to storage`,e)}),Ye}function Ce(e){if(e)return Se(e);for(let e of We.keys())Se(e);return Ye}async function we(e){let t=[];for(let n of e.sort((e,t)=>e.startTime-t.startTime)){let e=await v.getChunksBySession(n.sessionId);for(let n of e)t.push(...n.items)}return t}async function Te(e){let t=await we(e);if(!t.length)return t;let n=t.sort(De),r=n[0].t,i=n[n.length-1].t;return[...await Ee(r,i,new Set(e.map(e=>e.sessionId))),...n].sort(De)}async function Ee(e,t,n){let r=(await v.getAllSessions()).filter(r=>!n.has(r.sessionId)&&r.conversationId===null&&r.endTime>=e-le&&r.startTime<=t),i=[];for(let n of r){let r=await v.getChunksBySession(n.sessionId);for(let n of r)n.endTime<e-le||n.startTime>t||i.push(...n.items.filter(n=>n.t>=e-le&&n.t<=e?!0:n.t>=e&&n.t<=t&&ue.has(n.l)))}return i}function De(e,t){return e.t-t.t}function Oe(e,t){let n=document.createElement(`a`),r=new Blob([e],{type:`text/json`}),i=URL.createObjectURL(r);n.href=i,n.download=t,n.click(),URL.revokeObjectURL(i)}function ke(){Ce()}function Ae(){document.visibilityState===`hidden`&&Ce()}function je(e,t,n=qe){Ue||Me(),pe(n);let r=new Date,i={t:r.getTime(),l:e,d:xe(t),h:r.toLocaleString(`ru-RU`,{dateStyle:`short`,timeStyle:`long`})};return We.get(n)?.push(i),Je||(Je=window.setTimeout(()=>{Je=null,Ce()},oe)),i}function Me(){Ue||(Ue=!0,ve(),v.open(),window.addEventListener(`pagehide`,ke),document.addEventListener(`visibilitychange`,Ae))}function Ne(){return Ue||Me(),Ce(),fe()}function Pe(e,t=qe){t&&(pe(t),Ke.set(t,e),e&&v.updateSessionConversationId(t,e))}async function Fe(){return await Ce(),(await v.getAllSessions()).sort((e,t)=>t.updatedAt-e.updatedAt)}async function Ie(e){return await Ce(),Te(await ye(e))}async function Le(e){return JSON.stringify(await Ie(e))}async function Re(e){let t=await Le(e),n=`logs_${e.sessionId||e.conversationId}_${Date.now()}.json`;return Oe(t,n),n}async function ze(e){await Ce();let t=e?await ye(e):await v.getAllSessions();for(let e of t)await v.deleteSession(e.sessionId)}async function Be(){await Ce();let e=await v.getStorageSummary(),t=await v.estimateStorage();return{supported:v.supported,callsCount:e.callsCount,sessionsCount:e.sessions.length,usedBytes:e.usedBytes,maxBytes:re,maxCalls:ie,quotaBytes:t?.quota,usageBytes:t?.usage}}async function Ve(){await Ce();let e=await we(await v.getAllSessions());return JSON.stringify(e.sort(De))}async function He(){let e=await Ve(),t=`logs_${Date.now()}.json`;return Oe(e,t),t}var Ue=!1,We=new Map,Ge=new Map,Ke=new Map,qe=fe(),Je=null,Ye=Promise.resolve();window.__VKCallsSDKLogs__=(e=!1)=>(Ue||Me(),e?Ve():He());var y=class e{static get sessionKey(){return e._sessionKey}static set sessionKey(t){e._sessionKey=t}static get sessionSecretKey(){return e._sessionSecretKey}static set sessionSecretKey(t){e._sessionSecretKey=t}static get accessToken(){return e._accessToken}static set accessToken(t){e._accessToken=t}static get userId(){return e._userId}static set userId(t){e._userId=t}static isEmpty(){return!e._sessionKey}static reauthorize(t){return e._reauthorizePromise||(e._reauthorizePromise=t().finally(()=>{e._reauthorizePromise=null})),e._reauthorizePromise}};h(y,`_sessionKey`,void 0),h(y,`_sessionSecretKey`,void 0),h(y,`_accessToken`,void 0),h(y,`_userId`,null),h(y,`_reauthorizePromise`,null);var b=class{constructor(){h(this,`_handlers`,{}),h(this,`_listeners`,[])}_triggerEvent(e,...t){if(Object.hasOwn(this._handlers,e))for(let n of this._handlers[e])n.apply(this,t)}addEventListener(e,t){if(typeof t!=`function`)throw Error(`Listener should be a function`);return Object.hasOwn(this._handlers,e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!Object.hasOwn(this._handlers,e))return;t||delete this._handlers[e];let n=this._handlers[e].indexOf(t);n>=0&&this._handlers[e].splice(n,1)}subscribe(e,t,n){let r=e.addEventListener(t,n);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}},x=function(e){return e.MIC_CAMERA_PERMISSION=`mic_camera`,e.CAMERA_PERMISSION=`camera`,e.MIC_PERMISSION=`mic`,e.CAMERA_ACCESS=`cameralock`,e.MIC_ACCESS=`miclock`,e.MIC_NOT_FOUND=`nomic`,e.SCREEN_PERMISSION=`screenpermission`,e.SCREEN_ACCESS=`screenlock`,e.CONNECTION=`connection`,e.NETWORK=`network`,e.UNKNOWN=`unknown`,e.UNSUPPORTED=`unsupported`,e.SIGNALING_FAILED=`signalingfailed`,e.API=`api`,e.AUTH=`auth`,e.OVERCONSTRAINED=`overconstrained`,e}(x||{}),S=function(e){return e.AUDIO=`AUDIO`,e.VIDEO=`VIDEO`,e.SCREEN_SHARING=`SCREEN_SHARING`,e.MOVIE_SHARING=`MOVIE_SHARING`,e.AUDIO_SHARING=`AUDIO_SHARING`,e.ANIMOJI=`ANIMOJI`,e}(S||{}),C=function(e){return e.ACCEPT_CONCURRENT=`callAcceptConcurrent`,e.ACCEPT_INCOMING=`callAcceptIncoming`,e.ACCEPTED_OUTGOING=`callAcceptedOutgoing`,e.ADD_PARTICIPANT=`callAddParticipant`,e.CALL_SPEC_ERROR=`callSpecError`,e.DECLINE_INCOMING=`callDeclineIncoming`,e.DEVICE_CHANGED=`callDeviceChanged`,e.DEVICES=`callDevices`,e.ERROR=`callError`,e.HANGUP=`callHangup`,e.ICE_CONNECTION_STATE=`callIceConnectionState`,e.ICE_CONNECTION_TYPE=`callIceConnectionType`,e.ICE_RESTART=`callIceRestart`,e.JOIN_CONVERSATION=`callJoinConversation`,e.MEDIA_STATUS=`callMediaStatus`,e.OUTGOING_CALL=`callStart`,e.OUTGOING_MULTIPARTY_CALL=`callStartMultiparty`,e.PAT_ALLOCATED=`patAllocate`,e.PAT_DEALLOCATED=`patDeallocate`,e.PAT_ERROR=`patError`,e.PAT_OUTDATED_RESPONSE=`patOutdatedResponse`,e.PAT_WAITING_TIME_ERROR=`patWaitingTimeError`,e.POOR_CONNECTION=`callPoorConnection`,e.PUSH=`callPush`,e.RECONNECT=`callReconnect`,e.RELAY_POLICY=`callForceRelay`,e.REMOVE_PARTICIPANT=`callRemoveParticipant`,e.SOCKET_ACTION=`callSocketAction`,e.TOPOLOGY_CHANGE_REQUESTED=`callTopologyChangeRequested`,e}(C||{}),Xe=e=>e.stop(),Ze=e=>e.getTracks().forEach(Xe),Qe=e=>e.getVideoTracks().forEach(Xe);async function $e(e,t){try{let n=typeof t.width==`number`?t.width:void 0,r=typeof t.height==`number`?t.height:void 0;await e.applyConstraints({...t,...n&&{width:{max:n,ideal:n}},...r&&{height:{max:r,ideal:r}}})}catch(e){R.warn(`setVideoConstraints failed`,e)}}var et=class{constructor(){h(this,`_cameraPermissionStatus`,void 0),h(this,`_microphonePermissionStatus`,void 0),h(this,`_listener`,void 0)}static isSupported(){return T.browserName()!==`Firefox`&&`permissions`in navigator&&`PermissionStatus`in window}async init(e){try{let[t,n]=await Promise.all([navigator.permissions.query({name:`camera`}),navigator.permissions.query({name:`microphone`})]);this._cameraPermissionStatus=t,this._microphonePermissionStatus=n,this._listener=e,this._cameraPermissionStatus.onchange=e=>this.handlePermissionChange(e),this._microphonePermissionStatus.onchange=e=>this.handlePermissionChange(e)}catch(e){R.warn(`NavigatorPermissions init error`,e)}}handlePermissionChange(e){let t=e.target;if(t instanceof PermissionStatus){let{name:e,state:n}=t;switch(e){case`audio_capture`:this._listener(`microphone`,n);break;case`video_capture`:this._listener(`camera`,n);break}}}getPermissionState(e){switch(e){case`camera`:return this._cameraPermissionStatus?.state??null;case`microphone`:return this._microphonePermissionStatus?.state??null}return null}},tt=`_okcls_`,nt=(()=>{try{let e=Date.now().toString(),t=window.localStorage,n=!1;return t.setItem(e,e),n=t.getItem(e)===e,t.removeItem(e),n?t:null}catch{return null}})();function rt(e){let t=nt?nt.getItem(tt+e):null;if(t===null)return null;try{return JSON.parse(t)}catch{return null}}function it(e,t){try{nt&&nt.setItem(tt+e,JSON.stringify(t))}catch{}}function at(e){nt&&nt.removeItem(tt+e)}var ot;(function(e){function t(e){return rt(e)||null}e.get=t;function n(e,t){it(e,t)}e.set=n;function r(e){at(e)}e.remove=r})(ot||(ot={}));var st=ot,ct=null,lt=null,ut=null,dt=[],ft=[],pt=[],mt=null,ht=null,gt=null,_t=!1,vt=!1,yt,bt,xt,St=null,Ct=null,wt=``,Tt=null,Et=[],Dt=null,Ot=navigator.appVersion,kt=navigator.appName,At=navigator.userAgent,jt={};function Mt(e,t){return Number(t.deviceId===`default`)-Number(e.deviceId===`default`)}var Nt=function(e){return e.USER=`user`,e.ENVIRONMENT=`environment`,e}({});(function(e){function t(e){return Object.values(Nt).includes(e)}e.contains=t})(Nt||(Nt={}));var Pt=class{constructor(e,t=!1,n=M.videoMaxWidth,r=M.videoMaxHeight,i=M.videoFrameRate){h(this,`audio`,void 0),h(this,`video`,void 0),h(this,`needVideo`,void 0),h(this,`lastSimplifyWasReached`,void 0),h(this,`supportedConstraints`,void 0),h(this,`isVideoRequested`,()=>this.needVideo),this.supportedConstraints=navigator.mediaDevices.getSupportedConstraints();let a=!1;if(e){a={noiseSuppression:M.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let t=w.getMicrophones(),n,r;if(ht&&(r=ht.groupId,n=ht.deviceId),typeof e==`string`)r=t.find(t=>t.deviceId===e)?.groupId,n=e;else if(!ht&&w.os()===`MacOS`&&t.find(e=>e.label.includes(`iPhone`))){let e=t.find(e=>!e.label.includes(`Virtual`)&&!e.label.includes(`iPhone`));e&&(r=e.groupId,n=e.deviceId)}r&&this.supportedConstraints.groupId?a.groupId={exact:r}:n&&(a.deviceId={exact:n})}let o=!1;if(t){o={width:{min:M.videoMinWidth,max:n,ideal:n},height:{min:M.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:M.videoAspectRatio},frameRate:{ideal:i}};let e=w.getCameras(),a,s;if(mt&&(s=mt.groupId,a=mt.deviceId),typeof t==`string`)s=e.find(e=>e.deviceId===t)?.groupId,a=t;else if(!mt&&w.os()===`MacOS`&&e.find(e=>e.label.includes(`iPhone`))){let t=e.find(e=>!e.label.includes(`Virtual`)&&!e.label.includes(`iPhone`));t&&(s=t.groupId,a=t.deviceId)}s&&this.supportedConstraints.groupId?o.groupId={exact:s}:a&&(o.deviceId={exact:a}),M.videoFacingMode&&(o.facingMode={ideal:M.videoFacingMode},delete o.deviceId,delete o.groupId)}this.audio=a,this.video=o,this.needVideo=!!o,this.lastSimplifyWasReached=!1}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.groupId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.groupId,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||this.audio.groupId)&&(delete this.audio.deviceId,delete this.audio.groupId)),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.audio&&!this.video&&(this.lastSimplifyWasReached=!0,this.audio=!this.isVideoRequested(),this.video=this.isVideoRequested()),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.groupId)||this.video;return!!(typeof this.audio==`object`&&(this.audio.deviceId||this.audio.groupId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)&&!this.lastSimplifyWasReached}isVideo(){return!!this.video}isAudio(){return!!this.audio}},Ft=class extends Pt{constructor(e,t,n,r){if(super(!1,!0),h(this,`captureController`,void 0),this.captureController=`CaptureController`in window?new CaptureController:null,typeof this.video==`object`?(delete this.video.deviceId,delete this.video.groupId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode,delete this.video.width,delete this.video.height):this.video={},this.video.cursor=`motion`,e&&(this.video.width=e),t&&(this.video.height=t),this.video.frameRate=n,this.video.displaySurface=M.displaySurface,w.browserName()===`Safari`){let n=Number(w.browserVersion());n===16?(e&&(this.video.width={max:e}),t&&(this.video.height={max:t})):n===17&&(delete this.video.width,delete this.video.height)}r&&(this.audio={noiseSuppression:!1,echoCancellation:!1,autoGainControl:!1})}getNative(){return Object.assign(super.getNative(),{systemAudio:M.audioShareSystemInclude?`include`:`exclude`,windowAudio:M.audioShareWindowInclude?`include`:`exclude`,controller:this.captureController})}},It=class e{constructor(){h(this,`_lockId`,Math.round(Math.random()*99998)+1)}busy(t=null){if(e._lockId)throw t?.log(C.ERROR,`change_device`),R.warn(`Device change failed: MediaSource is busy`),Error(`MediaSource is busy`);e._lockId=this._lockId}free(){e._lockId===this._lockId&&(e._lockId=0)}};h(It,`_lockId`,0);async function Lt(){vt=!1,_t=!1,ct=null;let e={camera:w.getSavedCamera(),microphone:w.getSavedMicrophone(),output:w.getSavedOutput()};await zt(),Rt(`devicechange`,e),L.onDeviceChange()}function Rt(e,...t){if(jt[e])for(let n of jt[e])n(...t)}async function zt(){return ct||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!lt&&navigator.mediaDevices.addEventListener&&(lt=j.debounce(Lt,M.enumerateDevicesDelay),navigator.mediaDevices.addEventListener(`devicechange`,lt)),!ut&&et.isSupported()&&(ut=new et,await ut.init((e,t)=>{switch(t){case`denied`:case`prompt`:lt?.();break}})),ct=navigator.mediaDevices.enumerateDevices().then(e=>{dt=e.filter(e=>e.kind===`videoinput`?((e.label||ut?.getPermissionState(`camera`)===`granted`)&&(_t=!0),!0):!1),dt.sort(Mt),ft=e.filter(e=>e.kind===`audioinput`?((e.label||ut?.getPermissionState(`microphone`)===`granted`)&&(vt=!0),!0):!1),ft.sort(Mt),pt=e.filter(e=>e.kind===`audiooutput`),pt.sort(Mt);let t=mt?.deviceId??st.get(`videoinput`),n=ht?.deviceId??st.get(`audioinput`),r=gt?.deviceId??st.get(`audiooutput`);return mt=dt.find(e=>e.deviceId===t)||null,ht=ft.find(e=>e.deviceId===n)||null,gt=pt.find(e=>e.deviceId===r)||pt[0]||null,ct=Promise.resolve(e),e}).catch(()=>(ct=null,[]))))}async function Bt(){if(`userAgentData`in navigator)try{let{platformVersion:e}=await navigator.userAgentData.getHighEntropyValues([`platformVersion`]);if(!e){R.warn(`Can't to get OS version`);return}let t=parseInt(e.split(`.`)[0]);Tt=isNaN(t)?null:t}catch(e){R.warn(`Failed to get OS version`,e)}}function Vt(e){if(mt&&ht)return;let t=(e,t)=>{let n=t.getSettings()?.deviceId;return e.find(e=>e.deviceId===n||e.label===t.label)||null};e?.getTracks().forEach(e=>{!ht&&e.kind===k.audio?ht=t(w.getMicrophones(),e):!mt&&e.kind===k.video&&(mt=t(w.getCameras(),e))})}async function Ht(e,t,n=R,r=null){n.debug(`Try to get media`,JSON.parse(JSON.stringify(e.getNative())));let i=(!e.isVideo()||w.hasCameraPermission())&&(!e.isAudio()||w.hasMicrophonePermission());!i&&!t&&L.onPermissionsRequested();let a=new It;try{a.busy(r);let t=await navigator.mediaDevices.getUserMedia(e.getNative());return w.releaseFirefoxMicrophonePermissionWarmup(),a.free(),i||await Lt(),Vt(t),t}catch(i){switch(a.free(),n.error(`getUserMedia error`,i),i.name){case`PermissionDeniedError`:case`PermissionDismissedError`:case`NotAllowedError`:case`SecurityError`:case`DOMException`:case`NotFoundError`:t=e.isVideoRequested()?x.CAMERA_PERMISSION:x.MIC_PERMISSION;break;case`OverconstrainedError`:t=x.OVERCONSTRAINED;break;case`TypeError`:t=x.UNKNOWN;break;case`AbortError`:case`NotReadableError`:t=e.isVideoRequested()?x.CAMERA_ACCESS:x.MIC_ACCESS;break;case`Error`:if(i.message===`MediaSource is busy`){t=e.isVideoRequested()?x.CAMERA_ACCESS:x.MIC_ACCESS;break}}if(e.canSimplify())return Ht(e.simplify(),t,n,r);let o=t||x.UNKNOWN;throw L.onPermissionsError(o,i),o}}async function Ut(e=R){if(!(St||w.browserName()!==`Firefox`||!navigator.mediaDevices?.getUserMedia))try{w.hasMicrophonePermission()||L.onPermissionsRequested(),St=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(t){e.warn(`Firefox microphone permission warmup failed`,t)}}async function Wt(e,t=R,n=null){t.debug(`Try to get screen`,JSON.parse(JSON.stringify(e.getNative())));let r=new It;try{r.busy(n);let i=await navigator.mediaDevices.getDisplayMedia(e.getNative()),a=i?.getVideoTracks()[0];if(a){let n=a.getSettings()?.displaySurface;if(t.debug(`Got display media track: ${a.id} (${n})`),a.contentHint=`text`,e.captureController&&(n===`browser`||n===`window`))try{e.captureController.setFocusBehavior(`no-focus-change`)}catch(e){t.warn(`Failed to set focus behavior`,e)}}return i}catch(e){switch(e.name){case`PermissionDeniedError`:case`NotAllowedError`:case`SecurityError`:throw x.SCREEN_PERMISSION;case`AbortError`:case`NotReadableError`:throw x.SCREEN_ACCESS;default:throw e}}finally{r.free()}}function Gt(){return Et.length||(Et=(()=>{let e,t=!1,n=0,r=`0`,i=At.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(i[1]===`Safari`){if(e=At.match(/\bCriOS\/(\d+)/),e)return[`Chrome`,e[1],!0,Number(e[1]),r];if(e=At.match(/\bFxiOS\/(\d+)/),e)return[`Firefox`,e[1],!1,n,r];if(e=At.match(/\bYaBrowser\/(\d+)/),e)return[`Yandex`,e[1],!1,n,r];if(e=At.match(/\bOPT\/(\d+)/),e)return[`Opera`,e[1],!1,n,r]}if(i[1]===`Chrome`){if(t=!0,n=Number(i[2]),e=At.match(/\bOPR\/(\d+)/),e)return[`Opera`,e[1]||`Unknown`,t,n,r];if(e=At.match(/\bYaBrowser\/(\d+)/),e)return[`Yandex`,e[1]||`Unknown`,t,n,r];if(e=At.match(/\bSferum\/((\d+)(?:\.\d+)*)/),e)return[`Sferum`,e[1]||`Unknown`,t,n,r];if(e=At.match(/\bEdge?\/(\d+)/),e)return[`Edge`,e[1]||`Unknown`,t,n,r];if(window.opr!==void 0&&/^(.+\.)?ok.ru$/.test(window.location.host))return[`Opera`,`Hidden`,t,n,r]}return e=At.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),e&&e[2]!==void 0&&(r=e[2]),[i[2]?i[1]:kt,e&&e[1]||i[2]||Ot,t,n,r]})()),Et}var w;(function(e){async function t(){await zt(),await Bt()}e.init=t;function n(){return dt}e.getCameras=n;function r(){return ft}e.getMicrophones=r;function i(){return pt}e.getOutput=i;function a(){return dt.length>0}e.hasCamera=a;function o(){return ft.length>0}e.hasMicrophone=o;function s(){return mt}e.getSavedCamera=s;function c(){return ht}e.getSavedMicrophone=c;function l(){return gt}e.getSavedOutput=l;function u(){return M.videoFacingMode}e.getVideoFacingMode=u;function d(){return _t}e.hasCameraPermission=d;function f(){return vt}e.hasMicrophonePermission=f;function p(){return ut?.getPermissionState(`microphone`)??null}e.getMicrophonePermissionState=p;function m(e=!1){return f()?a()&&e?d():!0:!1}e.hasPermissions=m;function ee(){St&&(Ze(St),St=null)}e.releaseFirefoxMicrophonePermissionWarmup=ee;async function te(e=!1,t=!0,n=!0,r=R,i=null){!e&&!t&&await Ut(r);let s=o()&&t,c=a()&&e,l;if(!s&&!c)l=new MediaStream;else try{l=await Ht(new Pt(s,c),void 0,r,i)}catch{l=new MediaStream}return!l.getVideoTracks().length&&n&&l.addTrack(w.getBlackMediaTrack()),!l.getAudioTracks().length&&n&&l.addTrack(w.getSilentMediaTrack()),l}e.getUserMedia=te;async function ne(e,t,n=R,r=null){return Wt(new Ft(e&&!M.consumerFastScreenShare?M.fastScreenShareWidth:0,e&&!M.consumerFastScreenShare?M.fastScreenShareHeight:0,M.getScreenFrameRate(e),t),n,r)}e.getScreenMedia=ne;async function h(e=!1,t,n=R,r=null){return Ht(new Pt(!1,!0,e?M.videoEffectMaxWidth:M.videoMaxWidth,e?M.videoEffectMaxHeight:M.videoMaxHeight,t),void 0,n,r)}e._getUserVideo=h;async function re(e,t,n=R,r=null){let i=t?.width||M.videoMaxWidth,a=t?.height||M.videoMaxHeight;return Ht(new Pt(!1,e||!0,i,a),void 0,n,r)}e.getUserVideo=re;async function ie(e,t=R,n=null){return Ht(new Pt(e||!0,!1),void 0,t,n)}e.getUserAudio=ie;async function ae(e,t){let[n]=e.getVideoTracks();if(!n)throw Error(`Video track not found in stream`);return $e(n,t)}e.setResolution=ae;async function oe(e,t){let n=(await zt()).find(n=>n.kind===e&&n.deviceId===t);return n?(e===`videoinput`?mt=n:e===`audioinput`?ht=n:e===`audiooutput`&&(gt=n),st.set(e,t),n):null}e._saveDeviceId=oe;function se(){if(!xt||xt.readyState===`ended`){let e=w.getAudioContext(),t=e.createMediaStreamDestination(),n=e.createGain();n.gain.value=1e-5,n.connect(t),w.browserName()===`Safari`&&n.connect(e.destination);let r=e.createOscillator();r.type=`sine`,r.frequency.value=0,r.connect(n),r.start(),xt=t.stream.getAudioTracks()[0]}return Object.assign(xt.clone(),{enabled:!1})}e.getSilentMediaTrack=se;function ce(e=M.videoMinWidth,t=M.videoMinHeight){bt||(bt=document.createElement(`canvas`)),bt.width=e,bt.height=t;let n=bt.getContext(`2d`);return n.rect(0,0,e,t),n.fillStyle=`black`,n.fill(),(!yt||yt.readyState===`ended`)&&(yt=bt.captureStream(M.videoFrameRate).getVideoTracks()[0]),Object.assign(yt.clone(),{enabled:!1})}e.getBlackMediaTrack=ce;function g(){return _()===null}e.isBrowserSupported=g;function _(){try{let e=window;return e.navigator.mediaDevices?`getUserMedia`in e.navigator.mediaDevices?e.RTCPeerConnection?e.RTCIceCandidate?e.RTCSessionDescription?e.HTMLCanvasElement?e.HTMLCanvasElement.prototype.captureStream?e.RTCRtpSender?e.RTCRtpSender.prototype.replaceTrack?e.RTCRtpSender.prototype.getParameters?`sendBeacon`in e.navigator?null:`send-beacon-unavailable`:`rtp-sender-get-parameters-unavailable`:`rtp-sender-replace-track-unavailable`:`rtp-sender-unavailable`:`canvas-capture-stream-unavailable`:`html-canvas-unavailable`:`rtc-session-description-unavailable`:`rtc-ice-candidate-unavailable`:`rtc-peer-connection-unavailable`:`get-user-media-unavailable`:`media-devices-unavailable`}catch{return`support-check-failed`}}e.getBrowserSupportFailure=_;function le(){return!!navigator.mediaDevices.getDisplayMedia}e.isScreenCapturingSupported=le;function ue(){let e=w.browserName()===`Opera`,t=w.browserName()===`Yandex`;return e||t}e.isBrokenH264Decoder=ue;function de(){return w.browserName()===`Yandex`&&w.os()===`Windows`||M.simulcast}e.isBrokenVP9Encoder=de;function fe(){let e=w.browserName()===`Safari`&&Number(w.browserVersion())===17&&[4,5,6].includes(Number(w.browserSubVersion())),t=w.osVersion(),n=w.os()===`Windows`&&t!=null&&t>0&&t<13;return e||n}e.isBrokenVP9Decoder=fe;function pe(){return!(w.baseChromeVersion()&&w.isMobile())}e.canPreferH264=pe;function me(){let e=w.browserName(),t=Number(w.browserVersion());return e===`Safari`?t>=18:e===`Firefox`?t>=134:!0}e.isSimulcastSupportedByBrowser=me;function he(){return wt||(wt=(()=>{let e={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 t in e)if(Object.hasOwn(e,t)&&e[t].test(At))return t;return`Unknown`})()),wt}e.os=he;function ge(){return Tt}e.osVersion=ge;function _e(){return Ct===null&&(Ct=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Ot)),Ct}e.isMobile=_e;function ve(){return Gt()[0]}e.browserName=ve;function v(){return Gt()[1]}e.browserVersion=v;function ye(){return Gt()[3]}e.baseChromeVersion=ye;function be(){return Dt||(Dt=new(window.AudioContext||window.webkitAudioContext)),Dt.resume().catch(()=>{R.warn(`Failed to resume AudioContext`)}),Dt}e.getAudioContext=be;function xe(){return Gt()[4]}e.browserSubVersion=xe;function Se(){return w.baseChromeVersion()>=105&&!w.isMobile()}e.isAudioShareSupported=Se;function Ce(e,t){jt[e]||(jt[e]=[]),jt[e].push(t)}e.addEventListener=Ce;function we(e,t){if(jt[e])if(!t)delete jt[e];else{let n=jt[e].indexOf(t);n>-1&&jt[e].splice(n,1)}}e.removeEventListener=we})(w||(w={}));var T=w;function Kt(e,t){return!(e.isAudioEnabled!==t.isAudioEnabled||e.isVideoEnabled!==t.isVideoEnabled||e.isScreenSharingEnabled!==t.isScreenSharingEnabled||e.isFastScreenSharingEnabled!==t.isFastScreenSharingEnabled||e.isAudioSharingEnabled!==t.isAudioSharingEnabled||e.isAnimojiEnabled!==t.isAnimojiEnabled)}function E(e){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,isFastScreenSharingEnabled:!1,isAudioSharingEnabled:!1,isAnimojiEnabled:!1},e||{})}var D=function(e){return e.CANCELED=`CANCELED`,e.REJECTED=`REJECTED`,e.REMOVED=`REMOVED`,e.HUNGUP=`HUNGUP`,e.MISSED=`MISSED`,e.BUSY=`BUSY`,e.FAILED=`FAILED`,e.NETWORK_ERROR=`NETWORK_ERROR`,e.KILLED=`KILLED`,e.BANNED=`BANNED`,e.HAS_ACTIVE_CALL=`HAS_ACTIVE_CALL`,e.CALLER_IS_BLOCKED=`CALLER_IS_BLOCKED`,e.NOT_FRIENDS=`NOT_FRIENDS`,e.CALLEE_IS_OFFLINE=`CALLEE_IS_OFFLINE`,e.CALLEE_UNAVAILABLE=`CALLEE_UNAVAILABLE`,e.CALLER_IS_REJECTED=`CALLER_IS_REJECTED`,e.UNKNOWN_ERROR=`UNKNOWN_ERROR`,e.UNSUPPORTED=`UNSUPPORTED`,e.SERVICE_DISABLED=`SERVICE_DISABLED`,e.SERVICE_UNAVAILABLE=`SERVICE_UNAVAILABLE`,e.EXTERNAL_API_ERROR=`EXTERNAL_API_ERROR`,e.SOCKET_CLOSED=`SOCKET_CLOSED`,e.ENDED=`ENDED`,e.KILLED_WITHOUT_DELETE=`KILLED_WITHOUT_DELETE`,e.ANOTHER_DEVICE=`ANOTHER_DEVICE`,e.NOT_FOUND=`NOT_FOUND`,e.VCHAT_DETAILED_ERROR=`VCHAT_DETAILED_ERROR`,e.TIMEOUT=`TIMEOUT`,e.PARTICIPANT_LIMIT_REACHED=`PARTICIPANT_LIMIT_REACHED`,e.FAST_START_ERROR=`FAST_START_ERROR`,e.FAST_JOIN_ERROR=`FAST_JOIN_ERROR`,e.CALL_TIMEOUT=`CALL_TIMEOUT`,e.OBSOLETE_CLIENT=`OBSOLETE_CLIENT`,e}(D||{}),O=class e extends Error{constructor(t,n){super(),h(this,`message`,void 0),h(this,`hangup`,void 0),h(this,`error`,void 0),h(this,`code`,void 0),h(this,`remote`,void 0),h(this,`custom_error`,void 0),h(this,`callError`,void 0),this.name=`HangupReason`,this.code=n&&n.code||0,this.remote=n&&n.remote||!1,this.custom_error=n?.custom_error??null,this.callError=n?.callError??null,Object.values(D).indexOf(t)>-1?this.hangup=t:this.error=t;let r=[];this.error&&r.push(`error`),this.remote&&r.push(`remote`),this.code&&r.push(`code: ${this.code}`),n&&n.message&&r.push(`message: '${n.message}'`),this.message=t+(r.length?` (${r.join(`, `)})`:``),Error.captureStackTrace&&Error.captureStackTrace(this,e)}},qt=function(e){return e.FpsLimit=`fps-limit`,e}({}),Jt=class extends b{constructor(e=R){super(),h(this,`FPS_LIMITS`,[13,20,Math.max(M.videoFrameRate,25)]),h(this,`THRESHOLD`,.8),h(this,`HISTORY_LENGTH`,10),h(this,`_fpsMeterUnsubscribe`,null),h(this,`_fpsHistory`,{cursor:0,arr:[]}),h(this,`_fpsLimitCursor`,this.FPS_LIMITS.length-1),h(this,`_debug`,void 0),this._debug=e}get fpsLimit(){return this.FPS_LIMITS[this._fpsLimitCursor]}watch(e){this._cleanup();try{e&&(this._assertsVideoEffect(e),this._fpsMeterUnsubscribe=e.addFpsMeterListener(this._handleFpsMeter.bind(this)))}catch(e){this._debug.warn(`VideoEffectsFpsLimiter error`,e)}}_handleFpsMeter(e){if(this._fpsHistory.arr[this._fpsHistory.cursor]=e,this._fpsHistory.cursor=(this._fpsHistory.cursor+1)%this.HISTORY_LENGTH,this._fpsHistory.arr.length===this.HISTORY_LENGTH&&this._fpsLimitCursor){let e=this._fpsHistory.arr.reduce((e,t)=>e+t,0)/this.HISTORY_LENGTH,t=this.FPS_LIMITS[this._fpsLimitCursor];e<t*this.THRESHOLD&&(this._fpsLimitCursor=Math.max(0,this._fpsLimitCursor-1)),t!==this.fpsLimit&&this._triggerEvent(`fps-limit`,this.fpsLimit)}}_assertsVideoEffect(e){if(!(`addFpsMeterListener`in e))throw Error(`Outdated VideoEffect version`)}addEventListener(e,t){return super.addEventListener(e,t)}_cleanup(){this._fpsMeterUnsubscribe?.(),this._fpsMeterUnsubscribe=null}destroy(){this._cleanup(),super.unsubscribe()}},Yt=function(e){return e.SOURCE_CHANGED=`SOURCE_CHANGED`,e.SOURCE_READY=`SOURCE_READY`,e.TRACK_REPLACED=`TRACK_REPLACED`,e.SCREEN_STATUS=`SCREEN_STATUS`,e.ANIMOJI_STATUS=`ANIMOJI_STATUS`,e}({}),k=function(e){return e.audio=`audio`,e.video=`video`,e.screen=`screen`,e.audioshare=`audioshare`,e}({}),Xt=function(e){return e[e.CAMERA=1]=`CAMERA`,e[e.SCREEN=2]=`SCREEN`,e}({}),Zt=class extends b{constructor(e=R,t=null){super(),h(this,`_stream`,null),h(this,`_screenTrack`,null),h(this,`_audioShareTrack`,null),h(this,`_screenShareTrack`,null),h(this,`_sendVideoTrack`,null),h(this,`_cameraVideoTrack`,null),h(this,`_micAudioTrack`,null),h(this,`_audioEffectsTrack`,null),h(this,`_mediaSettings`,E()),h(this,`_lastMediaSettings`,null),h(this,`_videoStatusOnScreenCapturingEnabled`,!1),h(this,`_effect`,null),h(this,`_audioEffectParams`,null),h(this,`_onDeviceChange`,void 0),h(this,`_animojiEnabled`,!1),h(this,`_videoEffectsFpsLimiter`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_cameraTrackSetAt`,0),h(this,`_cameraMuteRecoveredAt`,0),h(this,`videoTrackMuteHandler`,()=>{!this._mediaSettings.isVideoEnabled||this._cameraMuteRecoveredAt>=this._cameraTrackSetAt||T.browserName()!==`Safari`||(this._cameraMuteRecoveredAt=Date.now(),this._logger?.log(C.ERROR,`camera_mute_recover`),this._debug.log(`[MediaSource] Safari camera mute recovery`),this.toggleVideo(!0).then(()=>this._logger?.log(C.ERROR,`camera_mute_recover_success`)).catch(e=>{this._logger?.log(C.ERROR,`camera_mute_recover_fail`),this._debug.warn(`[MediaSource] Camera mute recovery failed`,e)}))}),this._debug=e,this._logger=t,this._initDeviceChangeListener(),M.audioShare&&(this._audioShareTrack=this.getSilentAudioShareTrack()),M.enableVideoEffectsFpsDegradation&&(this._videoEffectsFpsLimiter=new Jt(this._debug),this._videoEffectsFpsLimiter.addEventListener(qt.FpsLimit,this.handleVideoEffectsLowFps.bind(this)))}get cameraVideoTrack(){return this._cameraVideoTrack}set cameraVideoTrack(e){this._cameraVideoTrack&&this._cameraVideoTrack.removeEventListener(`mute`,this.videoTrackMuteHandler),this._cameraVideoTrack=e,this._cameraVideoTrack&&(this._cameraTrackSetAt=Date.now(),this._cameraVideoTrack.addEventListener(`mute`,this.videoTrackMuteHandler)),M.consumerFastScreenShare&&(this._screenShareTrack=this.getBlackScreenShareTrack())}async request(e=[S.AUDIO],t=!0){if(this._stream)return;let n=e.includes(S.VIDEO),r=e.includes(S.AUDIO),i=e.includes(S.ANIMOJI),a=T.getBrowserSupportFailure();if(a)throw new O(x.UNSUPPORTED,{callError:{scope:`internal`,code:`environment`,description:a}});try{this._stream=await T.getUserMedia(n,r,t,this._debug,this._logger),this.cameraVideoTrack?.stop(),this.cameraVideoTrack=this._stream.getVideoTracks()[0],this._micAudioTrack?.stop(),this._micAudioTrack=this._stream.getAudioTracks()[0],this._audioEffectsTrack?.stop(),this._mediaSettings.isVideoEnabled=n&&this._stream.getVideoTracks().filter(e=>e.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=r&&this._stream.getAudioTracks().filter(e=>e.enabled).length>0||!1,this._mediaSettings.isAnimojiEnabled=i&&!this._mediaSettings.isVideoEnabled||!1,this._animojiEnabled=i,this._triggerEvent(`SOURCE_READY`)}catch(e){throw new O(e)}}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(){let e=this._stream?.getAudioTracks().filter(e=>!e.contentHint)??[];return e.find(e=>e.enabled)??e[0]??null}get isAnimojiRequested(){return this._animojiEnabled&&!this._mediaSettings.isVideoEnabled}addTrackToPeerConnection(e,t,n){let r=this.getStream(),i=this.getSendAudioTrack(),a=this.getSendVideoTrack(n);if(!r||!i&&!a&&!t)throw Error(`No local stream found`);i&&!t&&e.addTrack(i,r),a&&!t&&e.addTrack(a,r)}getMediaSettings(){return this._mediaSettings}get mediaSettings(){return this._mediaSettings}async changeDevice(e){switch(e){case`videoinput`:if(this._mediaSettings.isVideoEnabled)return this._changeVideoInput();break;case`audioinput`:if(this._mediaSettings.isAudioEnabled)return this._changeAudioInput();break;default:return Promise.reject(x.UNKNOWN)}}stopVideoTrack(){this._mediaSettings.isVideoEnabled&&(this._stopEffect(),this._stream&&Qe(this._stream),this.cameraVideoTrack?.stop())}async setVideoStream(e,t){return t?this._changeScreen(!1,!1,e):this._changeVideoInput(e)}_initDeviceChangeListener(){!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener||(this._onDeviceChange=async e=>{if(!this._stream)return;let t=T.getSavedMicrophone(),n=T.getSavedCamera(),r=this._mediaSettings.isAudioEnabled&&t?.groupId!==e.microphone?.groupId,i=this._mediaSettings.isVideoEnabled&&n?.groupId!==e.camera?.groupId;try{r&&await this._changeAudioInput(),i&&await this._changeVideoInput()}catch{}},T.addEventListener(`devicechange`,this._onDeviceChange))}_destroyDeviceChangeListener(){this._onDeviceChange&&T.removeEventListener(`devicechange`,this._onDeviceChange)}async _changeVideoInput(e){try{let t=e?`stream`:`video`,n=e||await T._getUserVideo(!!this._effect,this._frameRate,this._debug,this._logger);if(this.cameraVideoTrack?.stop(),this.cameraVideoTrack=n.getVideoTracks()[0],!this._stream)Ze(n);else{let e=await this._setEffect(this._effect,this.cameraVideoTrack);this._logger?.log(C.DEVICE_CHANGED,t),this._debug.log(`Video stream changed`),await this._replaceLocalTrack(e),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent(`SOURCE_CHANGED`,{kind:`video`})}}catch(e){throw this._logger?.log(C.ERROR,`change_video`),this._debug.warn(`Camera change failed`,e),e}}async setAudioStream(e){return this._changeAudioInput(e)}async _changeAudioInput(e=null){try{let t=e||await T.getUserAudio(void 0,this._debug,this._logger);if(this._micAudioTrack?.stop(),this._micAudioTrack=t.getAudioTracks()[0],!this._stream)Ze(t);else{let e=await this._applyAudioEffect();this._logger?.log(C.DEVICE_CHANGED,`audio`),this._debug.log(`Audio stream changed`,e),await this._replaceLocalTrack(e),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent(`SOURCE_CHANGED`,{kind:`audio`})}}catch(e){throw this._logger?.log(C.ERROR,`change_audio`),this._debug.error(`Microphone change failed`,e),e}}async _changeScreen(e,t,n){try{if(n=n||await T.getScreenMedia(e,t,this._debug,this._logger),!this._stream)Ze(n);else{let r=n.getVideoTracks()[0];if(r.addEventListener(`ended`,()=>{this._mediaSettings.isScreenSharingEnabled&&this.disableScreenCapturing()},!1),this._logger?.log(C.DEVICE_CHANGED,`screen`),this._debug.log(`Screen capturing started`),this._screenTrack=r,this._mediaSettings.isScreenSharingEnabled=!0,this._mediaSettings.isFastScreenSharingEnabled=e,M.consumerFastScreenShare&&this._mediaSettings.isFastScreenSharingEnabled&&(r.contentHint=`motion`,this._screenShareTrack=r),n.getAudioTracks().length>0){let e=n.getAudioTracks()[0];e.contentHint=`music`,this._audioShareTrack=e,await this._addLocalTrack(e),this._mediaSettings.isAudioSharingEnabled=!0}t&&!this._mediaSettings.isAudioSharingEnabled&&this._debug.debug(`Audio share requested but not captured`),this._triggerEvent(`SCREEN_STATUS`,{track:r}),this._triggerEvent(`SOURCE_CHANGED`,{kind:`screen`})}}catch(e){throw this._logger?.log(C.ERROR,`screen`),this._debug.warn(`Screen capturing failed`,e),e}}async _disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._screenShareTrack&&(this._screenShareTrack.stop(),this._screenShareTrack=this.getBlackScreenShareTrack()),await this.stopAudioShareTrack(),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._mediaSettings.isFastScreenSharingEnabled=!1,this._triggerEvent(`SCREEN_STATUS`,{track:null}),this._triggerEvent(`SOURCE_CHANGED`,{kind:`screen`}))}async stopAudioShareTrack(){if(this._audioShareTrack){let e=this.getSilentAudioShareTrack();await this._replaceTrack(this._audioShareTrack,e),this._mediaSettings.isAudioSharingEnabled=!1}}async _applyAudioEffect(){if(!M.audioEffects||!this._audioEffectParams)return M.audioEffects?.pause(),this._micAudioTrack;M.audioEffects.isInitialized||await M.audioEffects.init(),M.audioEffects.resume(),M.audioEffects.setEffects(this._audioEffectParams.effects,this._audioEffectParams.isPreset),M.audioEffects.setSource(this._micAudioTrack);let e=M.audioEffects.outputStream.getAudioTracks()[0];return(!this._audioEffectsTrack||this._audioEffectsTrack.id!==e.id)&&(this._audioEffectsTrack=e),this._audioEffectsTrack}getSilentAudioShareTrack(){let e=T.getSilentMediaTrack();return e.contentHint=`music`,e.stop(),e}getBlackScreenShareTrack(){let e=T.getBlackMediaTrack();return e.contentHint=`motion`,e.stop(),e}async _replaceLocalTrack(e,t){if(!this._stream)return;let n=this._stream.getTracks().filter(t=>t.kind===e.kind),r=n.find(t=>t.contentHint===e.contentHint)??n.find(e=>e!==this._audioEffectsTrack);r?.id!==e.id&&(r?await this._replaceTrack(r,e,t):await this._addLocalTrack(e,t))}async _replaceTrack(e,t,n){this._stream&&(e!==this._audioEffectsTrack&&e.stop(),this._stream.removeTrack(e),this._stream.addTrack(t),this._triggerEvent(`TRACK_REPLACED`,t,n))}async _addLocalTrack(e,t){this._stream&&(this._stream.addTrack(e),this._triggerEvent(`TRACK_REPLACED`,e,t))}async _setEffect(e,t){if(this._videoEffectsFpsLimiter?.watch(M.videoEffects),!M.videoEffects)return t;try{return M.videoEffects.setEffect(e,t)}catch(e){return this._debug.warn(`Video effect failed`,e),t}}_stopEffect(){if(M.videoEffects)try{M.videoEffects.stopEffect()}catch(e){this._debug.warn(`Video effect failed`,e)}}destroy(){this._destroyDeviceChangeListener(),T.releaseFirefoxMicrophonePermissionWarmup(),M.videoEffects&&(this._effect=null,M.videoEffects.destroy()),M.audioEffects&&M.audioEffects.destroy(),this._stream&&(Ze(this._stream),this._stream=null),this.cameraVideoTrack?.stop(),this._micAudioTrack?.stop(),this._audioEffectsTrack?.stop(),this._disableScreenCapture(),T.getAudioContext()?.suspend().catch(e=>this._debug.error(e)),this._videoEffectsFpsLimiter?.destroy()}async stopLocalMedia(){this._mediaSettings.isScreenSharingEnabled&&await this.disableScreenCapturing(),this._stream&&(this._lastMediaSettings={...this._mediaSettings},this._stream.getAudioTracks().length>0&&await this.toggleAudio(!1),this._stream.getVideoTracks().length>0&&await this.toggleVideo(!1),this.cameraVideoTrack=null,this._micAudioTrack=null)}async resumeLocalMedia(e){if(!this._lastMediaSettings)return;let t=[];if((e?e.isAudioEnabled:this._lastMediaSettings.isAudioEnabled)&&(t.push(S.AUDIO),await this.toggleAudio(!0)),await this.request(t),this._lastMediaSettings=null,this._stream)for(let e of this._stream.getTracks())this._triggerEvent(`TRACK_REPLACED`,e)}async toggleScreenCapturing(e){if(e.captureScreen){await this._changeScreen(e.fastScreenSharing,e.captureAudio);return}return this._disableScreenCapture()}async disableScreenCapturing(){return this.toggleScreenCapturing({captureScreen:!1,fastScreenSharing:!1,captureAudio:!1})}async toggleVideo(e){if(!this._stream)return;this.cameraVideoTrack?.stop();let t;if(e){let e=await T._getUserVideo(!!this._effect,this._frameRate,this._debug,this._logger);this.cameraVideoTrack=e.getVideoTracks()[0],t=await this._setEffect(this._effect,this.cameraVideoTrack)}else t=T.getBlackMediaTrack(M.videoMinWidth,M.videoMinHeight),this._stopEffect();if(this._mediaSettings.isVideoEnabled=e,await this._replaceLocalTrack(t),this._animojiEnabled){this._triggerEvent(`ANIMOJI_STATUS`,!e);return}this._triggerEvent(`SOURCE_CHANGED`,{kind:`video`})}async toggleAudio(e){if(!this._stream)return;this._micAudioTrack?.stop();let t=async(e,t)=>{await this._replaceLocalTrack(e),this._mediaSettings.isAudioEnabled=t,this._triggerEvent(`SOURCE_CHANGED`,{kind:`audio`})};if(e)try{let e=await T.getUserAudio(void 0,this._debug,this._logger);this._micAudioTrack=e.getAudioTracks()[0],await t(await this._applyAudioEffect(),!0)}catch(e){throw M.audioEffects?.pause(),await t(T.getSilentMediaTrack(),!1),typeof e==`string`?Error(e):e}else M.audioEffects?.pause(),await t(T.getSilentMediaTrack(),!1)}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`})}async setResolution({video:e,effect:t}){if(!this._mediaSettings.isVideoEnabled)return;if(!this._stream)throw Error(`Local stream not found`);if(!this.cameraVideoTrack)throw Error(`Local video track not found`);let n=this._effect&&t||e;await this._applyVideoConstraints(this.cameraVideoTrack,n)}getCameraVideoTrack(){return this.cameraVideoTrack}async updateNoiseSuppression(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks().find(e=>!e.contentHint);if(!e)throw Error(`Local audio track not found`);if(e.enabled)return e.applyConstraints({noiseSuppression:M.noiseSuppression})}async videoEffect(e){if(!M.videoEffects)throw Error(`Video Effects library is not set`);if(this._logger?.log(C.DEVICE_CHANGED,`effect_${e?.effect||`none`}`),!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect&&this.cameraVideoTrack){let t=this._effect;this._effect=e;try{let e=this.cameraVideoTrack.clone(),t=new MediaStream([e]);await this._applyVideoConstraints(e),await this._changeVideoInput(t)}catch(e){this._effect=t;let n=this.cameraVideoTrack.clone(),r=new MediaStream([n]);throw await this._changeVideoInput(r),e}}}async audioEffect(e){if(!M.audioEffects)throw Error(`Audio Effects library is not set`);if(!this._mediaSettings.isAudioEnabled){this._audioEffectParams=e;return}if(this._stream&&(!e&&this._audioEffectParams||e&&!this._audioEffectParams||!j.isArraysEquals(e?.effects||[],this._audioEffectParams?.effects||[]))&&this._micAudioTrack){let t=this._audioEffectParams;this._audioEffectParams=e;try{let e=this._micAudioTrack.clone(),t=new MediaStream([e]);await this._changeAudioInput(t)}catch(e){this._audioEffectParams=t;let n=this._micAudioTrack.clone(),r=new MediaStream([n]);throw await this._changeAudioInput(r),e}}}getAudioShareTrack(){return this._audioShareTrack}handleVideoEffectsLowFps(e){this._mediaSettings.isVideoEnabled&&this.cameraVideoTrack&&e<M.videoFrameRate&&this._applyVideoConstraints(this.cameraVideoTrack).catch(e=>{this._debug.warn(`MediaSource handleVideoEffectsLowFps error`,e)})}get _frameRate(){let e=this._videoEffectsFpsLimiter?.fpsLimit??M.videoFrameRate;return this._effect?Math.min(e,M.videoFrameRate):void 0}async _applyVideoConstraints(e,t){await $e(e,{width:this._effect?M.videoEffectMaxWidth:M.videoMaxWidth,height:this._effect?M.videoEffectMaxHeight:M.videoMaxHeight,...this._frameRate&&{frameRate:{ideal:this._frameRate}},...t})}getScreenShareTrack(){return this._screenShareTrack}},A=function(e){return e.USER=`USER`,e.GROUP=`GROUP`,e}(A||{}),Qt={HEIGHT:720,WIDTH:1280,BITRATE:1e6},$t=`L1T2`,en=1.35,tn=[{dimension:320,bitrate:18e4},{dimension:520,bitrate:4e5},{dimension:640,bitrate:5e5},{dimension:960,bitrate:9e5},{dimension:1280,bitrate:12e5},{dimension:1920,bitrate:25e5},{dimension:2560,bitrate:35e5},{dimension:3840,bitrate:5e6}];function nn(e,t){return!e||!t?e===t:e.streams.length===t.streams.length?e.streams.every((e,n)=>{let r=t.streams[n];return e.rid===r.rid&&e.width===r.width&&e.height===r.height&&e.fps===r.fps&&e.bitrate===r.bitrate}):!1}function rn(e,t){for(let n of t)if(e<=n.dimension)return n.bitrate;return t.length>0?t[t.length-1].bitrate:tn[0].bitrate}function an(e=Qt.WIDTH,t=Qt.HEIGHT,n=tn,r=30){let i=Math.max(e,t),a=1;i>=960?a=3:i>=480&&(a=2);let o=[`h`,`m`,`l`].slice(3-a),s=[],c=rn(i,n);for(let i=0;i<a;i++){let a=o[i];s.push({rid:a,width:e,height:t,fps:r,bitrate:c}),e=Math.round(e/2),t=Math.round(t/2),c=rn(Math.max(e,t),n)}return{streams:s.reverse()}}function on(e,t){let n=t.streams.findIndex(t=>t.rid===e);return n>=0?2**(t.streams.length-n-1):1}function sn(e,t,n,r){let i=n?Math.round(n*en):1/0;if(e.forEach(e=>{let n=t.streams.find(t=>t.rid===e.rid);e.scaleResolutionDownBy=on(e.rid,t),e.scalabilityMode=$t,n?(e.active=n.rid===`l`||Math.max(n.width,n.height)<i,e.maxBitrate=n.bitrate,e.maxFramerate=n.fps):(e.active=!1,e.maxBitrate=0,delete e.maxFramerate)}),r)for(let n=t.streams.length-1;n>=0;n--){let{rid:i}=t.streams[n],a=e.find(e=>e.rid===i);if(a?.active){a.maxBitrate=r;break}}}var cn=typeof Object.fromEntries==`function`?Object.fromEntries:function(e){if(!e||!e[Symbol.iterator])throw Error(`Object.fromEntries() requires a single iterable argument`);let t={};for(let[n,r]of e)t[n]=r;return t};async function ln(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>{t(e.target?.result)},r.onerror=n,r.readAsArrayBuffer(e)})}var un=/\r?\n/;function dn(e){return e.split(un)}function fn(e){return e.join(`\r
|
|
8
|
+
`)}var pn=533,mn=`a=fmtp:`,hn=`sps-pps-idr-in-keyframe=1`,gn;(function(e){function t(e,t){let n=RegExp(`a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+`),r,i=[];for(r=0;r<e.length;++r){let a=e[r].match(n);a&&a.length===3&&a[2]===t&&i.push(a[1])}return i}function n(e,t,n){let r=e.split(` `),i=r.slice(0,3),a;for(a=3;a<r.length;a++)n.includes(r[a])&&i.push(r[a]);for(a=3;a<r.length;a++)!n.includes(r[a])&&!t.includes(r[a])&&i.push(r[a]);return i.join(` `)}function r(e,t,r,i){let a,o=`m=`+t;for(a=0;a<e.length;++a)e[a].startsWith(o)&&(e[a]=n(e[a],r,i))}function i(e,t){let n=RegExp(`a=fmtp:(\\d+)`);for(let r=0;r<e.length;++r){let i=e[r].match(n);if(i&&i.length===2&&t.includes(i[1])){let t=e[r].trim()===mn+i[1]?` `:`;`;e[r]+=t+hn}}}function a(e,n,i=`video`){let a=t(e,n);if(!a.length)return;let o=a.slice(0),s=RegExp(`a=fmtp:(\\d+) apt=(\\d+)`),c;for(c=0;c<e.length;++c){let t=e[c].match(s);t&&t.length===3&&o.includes(t[2])&&o.push(t[1])}let l=RegExp(`a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*`);for(c=e.length;c--;){let t=e[c].match(l);t&&t.length===3&&o.includes(t[2])&&e.splice(c,1)}r(e,i,o,[])}function o(e,t,n,r){let i=RegExp(`a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+`),a,o=[];for(a=t;a<n;++a){let t=e[a].match(i);t&&t.length===3&&t[2]===r&&o.push(t[1])}if(!o.length)return o;let s=RegExp(`a=fmtp:(\\d+) apt=(\\d+)`);for(a=t;a<n;++a){let t=e[a].match(s);t&&t.length===3&&o.includes(t[2])&&o.push(t[1])}return o}function s(e,t,r,i){let a=o(e,t,r,i);if(!a.length)return r+1;let s=RegExp(`a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*`),c=0,l=r;for(;l>=t;){let t=e[l].match(s);t&&t.length===3&&a.includes(t[2])&&(e.splice(l,1),c++),l--}return e[t]=n(e[t],a,[]),r-c+1}function c(e,t,n,r){let i=-1,a=-1,o=!1;for(let c=0;c<e.length;++c)if(i>=0&&e[c].startsWith(`m=`)&&(a=c-1,o&&(c=s(e,i,a,t)),i=-1,a=-1,o=!1),e[c].startsWith(`m=video`)&&(i=c),i>=0){let t=n===`remote`&&r===`encoder`||n===`local`&&r===`decoder`?`recvonly`:`sendonly`;(e[c].startsWith(`a=${t}`)||e[c].startsWith(`a=sendrecv`))&&(o=!0)}a=e.length-1,i>=0&&o&&s(e,i,a,t)}function l(e,n){let a=t(e,`H264`);n&&r(e,`video`,[],a),i(e,a)}function u(e){r(e,`video`,[],t(e,`VP9`))}function d(e){[`G722`,`PCMU`,`PCMA`,`CN`,`telephone-event`].forEach(t=>{a(e,t,`audio`)})}function f(e,n,i,a,o=!1){let s=dn(e);if(d(s),!n&&!i&&!a&&!o)return fn(s);function f(e){let t=[`a=rtcp-fb:111 nack`,`a=rtcp-fb:111 nack pli`],n=e.findIndex(e=>e.startsWith(`a=rtcp-fb:111`));return~n&&(e[n]=e[n]+`\r
|
|
9
|
+
`+fn(t)),e}function p(e){let n=t(e,`red`);n.length>0&&r(e,`audio`,[],n)}return i?c(s,`H264`,`local`,`decoder`):l(s,n),a&&u(s),p(s),o&&f(s),fn(s)}e.patchLocalSDP=f;function p(e,t,n,r,i,o){let s=dn(e);return n?a(s,`H264`):t&&l(s,t),i&&o?a(s,`VP9`):i?c(s,`VP9`,`remote`,`encoder`):o?c(s,`VP9`,`remote`,`decoder`):r&&u(s),d(s),fn(s)}e.patchRemoteSDP=p;function m(e){return e?`${e.type||`WEB_SOCKET`}_${e.id}`:`_`}e.getPeerIdString=m;function ee(e,t){return e&&e.id===t.id&&(e.type||`WEB_SOCKET`)===(t.type||`WEB_SOCKET`)}e.comparePeerId=ee;async function te(e){let t={local:null,remote:null};if(!e||!e.getStats)return t;try{let n=await e.getStats(null),r=null;if(n.forEach(e=>{e.type===`transport`&&e.selectedCandidatePairId?r=n.get(e.selectedCandidatePairId):e.type===`candidate-pair`&&e.state===`succeeded`&&!r&&(!Object.hasOwn(e,`selected`)||e.selected)&&(r=e)}),r?.localCandidateId){let e=n.get(r.localCandidateId);e&&(t.local={type:e.candidateType,ip:e.ip||e.ipAddress,port:e.port||e.portNumber})}if(r?.remoteCandidateId){let e=n.get(r.remoteCandidateId);e&&(t.remote={type:e.candidateType,ip:e.ip||e.ipAddress,port:e.port||e.portNumber})}return t}catch{return t}}e.getPeerConnectionHostInfo=te;let ne=/^-?[0-9]+$/,h=/^([gu])(-?[0-9]+)$/;function re(e,t=A.USER){let n=String(e);return h.test(n)?(R.warn(`Already composite id [${e}] type supplied [${t}]`),n):t===A.GROUP?`g`+n:t===A.USER?`u`+n:(R.warn(`Unknown type [${t}] for id [${e}]`),n.match(ne)?`u`+n:n)}e.composeUserId=re;function ie(e,t,n=0){return ae(re(e,t),n)}e.composeParticipantId=ie;function ae(e,t){return t?e+`:d`+t:e}e.compose=ae;function oe(e){return ie(e.id,e.idType||A.USER,e.deviceIdx)}e.composeId=oe;function se(e){if(e.decorativeUserId)return ie(e.decorativeUserId,e.idType||A.USER,e.deviceIdx)}e.composeDecorativeId=se;function ce(e){return e.participant?oe(e.participant):ie(e.participantId,e.participantType||A.USER,e.deviceIdx)}e.composeMessageId=ce;function g(e){return typeof e==`string`?_(le(e).compositeUserId).id:e}e.extractOkId=g;function _(e){let t=String(e),n=t.match(h);return n?{id:Number(n[2]),type:n[1]===`g`?A.GROUP:A.USER}:(R.warn(`Unsupported compositeId [${e}]`),{id:Number(t),type:A.USER})}e.decomposeId=_;function le(e){let t=e.split(`:d`);return{compositeUserId:t[0],deviceIdx:t.length>1?parseInt(t[1],10):0}}e.decomposeParticipantId=le;function ue(){let e=window.crypto?.randomUUID?.();if(e)return e;let t=`0123456789abcdefghijklmnopqrstuvwxyz`.split(``),n=Array(36),r=0,i,a;for(a=0;a<36;a++)a===8||a===13||a===18||a===23?n[a]=`-`:a===14?n[a]=`4`:(r<=2&&(r=33554432+Math.random()*16777216|0),i=r&15,r>>=4,n[a]=t[a===19?i&3|8:i]);return n.join(``)}e.uuid=ue;function de(e,t){let n;function r(...r){let i=this;n&&window.clearTimeout(n),n=window.setTimeout(()=>{e.apply(i,r)},t)}return r}e.debounce=de;function fe(e){if(!window.BigInt)return null;let t=``,n=dn(e);for(let e of n)if(e.startsWith(`a=fingerprint`)){let n=e.split(` `);if(n.length===2){t=n[1];break}}if(!t)return BigInt(-1);let r=t.split(`:`),i=BigInt(0);for(let e=Math.min(7,r.length-1);e>=0;e--){let t=BigInt(parseInt(r[e],16));i<<=BigInt(8),i|=t}return BigInt.asIntN(64,i)}e.sdpFingerprint=fe;async function pe(e,{signal:t}={}){return new Promise((n,r)=>{if(t?.aborted)return r(t.reason);let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(t?.reason)};t?.addEventListener(`abort`,a,{once:!0})})}e.delay=pe;function me(e,t,n,r=R){let i=[];return e.getSenders().forEach(e=>he(t,e,e.track,n,i,r)),i}e.applySettings=me;function he(e,t,n,r,i,a=R){if(!RTCRtpSender.prototype.getParameters||!RTCRtpSender.prototype.setParameters||!e||!n||n.kind!==k.video)return;let o=n.getSettings();if(!o)return;let s=e.maxBitrateK?e.maxBitrateK*1024:null,c=o.width,l=o.height,u=c&&l&&e.maxDimension?Math.max(1,Math.max(c,l)/e.maxDimension):null,d=e.maxFramerate||null;if(c&&l&&e.maxDimension&&e.maxDimension>Math.max(c,l)){let e=Math.round(c*l/256),t=(Math.round(e*pn/1e4)+1)*1e4;s=s===null?t:Math.min(t,s)}let f=e.degradationPreference||`balanced`,p=r[n.id];if(p&&p.bitrate===s&&p.scaleResolutionDownBy===u&&p.maxFramerate===d&&p.degradationPreference===f){i[n.id]=p;return}i[n.id]={bitrate:s,scaleResolutionDownBy:u,maxFramerate:d,degradationPreference:f};let m=t.getParameters();if(m.encodings||(m.encodings=[{}]),m.encodings.length>1&&c&&l&&e.maxDimension){let t=Math.round(e.maxDimension*1.35),n=e.bitrates?.generic?.length?e.bitrates.generic:void 0,r=o.frameRate||30,i=an(c,l,n,d?Math.min(r,d):r);a.log(`applyVideoTrackSettings: maxDim=${e.maxDimension} targetDim=${t} track=${c}x${l} sim=${JSON.stringify(i)}`),sn(m.encodings,i,e.maxDimension,n?void 0:s??void 0)}else m.encodings.forEach(t=>{e?.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),s?t.maxBitrate=s:delete t.maxBitrate,u?t.scaleResolutionDownBy=u:delete t.scaleResolutionDownBy,d?t.maxFramerate=d:delete t.maxFramerate});m.degradationPreference=f,m.encodings.length>0&&t.setParameters?.(m).then(()=>{let e=t.getParameters();a.log(`applyVideoTrackSettings: actual encodings= ${JSON.stringify(e.encodings)}`)},e=>{a.error(`Failed to set sender parameters`,m,e)})}e.applyVideoTrackSettings=he;function ge(e,t){Array.isArray(t)||(t=[t]);for(let n of t)if(e.includes(n))return!0;return!1}e.includesOneOf=ge;function _e(e){return Object.entries(e.participantState?.state||{}).reduce((t,[n,r])=>(e.participantState&&(t[n]={ts:e.participantState.stateUpdateTs[n],state:r}),t),{})}e.mapParticipantState=_e;function ve(e){let t=e.map(e=>({uid:e.externalId,mediaSettings:e.mediaSettings,status:e.connectionStatus.lastEffective,muteStates:e.muteStates,unmuteOptions:e.unmuteOptions,participantState:e.participantState,markers:e.markers,movieShareInfos:e.movieShareInfos,roles:e.roles}));return M.filterObservers?t.filter(e=>!e.uid.observer):t}e.mapSharedParticipants=ve;function v(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let i of n)if(!Object.hasOwn(r,i)||e[i].state!==t[i].state||e[i].ts!==t[i].ts)return!1;return!0}e.isEqualParticipantState=v;function ye(e,t,n=!1){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let i of r){if(!Object.hasOwn(t,i))return!1;let r=e[i],a=t[i];if(n&&Te(r)&&Te(a))return ye(r,a,n);if(r!==a)return!1}return!0}e.isObjectsEquals=ye;function be(e,t){if(e.length!==t.length)return!1;for(let n of e)if(t.indexOf(n)<0)return!1;return!0}e.isArraysEquals=be;function xe(e){return!Object.keys(e).length}e.isEmptyObject=xe;function Se(e,t){if(!e&&!t)return 0;if(!e||!t)return e?-1:1;return r(t.rank,e.rank)||r(e.ts,t.ts)||n(e,t);function n(e,t){let n={[A.USER]:0,[A.GROUP]:1},{compositeUserId:i,deviceIdx:a}=le(e.id),{compositeUserId:o,deviceIdx:s}=le(t.id),{id:c,type:l}=_(i),{id:u,type:d}=_(o);return r(n[l],n[d])||r(c,u)||r(a,s)}function r(e,t){return e<t?-1:e===t?0:1}}e.participantMarkerCompare=Se;function Ce(e,t){return cn(Object.entries(e).filter(([,e])=>Array.isArray(t)?!t.includes(e):e!==t))}e.objectFilterOutValues=Ce;function we(e,t,n){let r=n;for(let n in e)Object.hasOwn(e,n)&&(r=t(r,e[n],n));return r}e.objectReduce=we,e.setImmediate=(()=>{let e=1,t={},n=null;return typeof MessageChannel<`u`&&(n=new MessageChannel,n.port1.onmessage=e=>{let n=e.data;t[n]&&(t[n](),delete t[n])}),function(r){if(n&&document.visibilityState===`hidden`){let i=e;return e=e>=2**53-1?1:e+1,t[i]=r,n.port2.postMessage(i),()=>{t[i]&&delete t[i]}}let i=setTimeout(r,0);return()=>clearTimeout(i)}})();function Te(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}e.isObject=Te})(gn||(gn={}));var j=gn,_n=`__CALLS_SDK_DEVTOOLS_`,vn=class{set(e,t){try{this.getStorage().setItem(_n+e,JSON.stringify(t))}catch(t){R.warn(`DevTools: Failed to save option`,e,t)}}get(e){try{let t=this.getStorage().getItem(_n+e);return t===null?null:JSON.parse(t)}catch(t){return R.warn(`DevTools: Failed to read option`,e,t),null}}remove(e){try{this.getStorage().removeItem(_n+e)}catch(t){R.warn(`DevTools: Failed to remove option`,e,t)}}clear(){try{let e=this.getStorage(),t=Object.keys(e);for(let n of t)n.startsWith(_n)&&e.removeItem(n)}catch(e){R.warn(`DevTools: Failed to clear options`,e)}}getAll(){try{let e=this.getStorage(),t=Object.keys(e),n={};for(let r of t)if(r.startsWith(_n)){let t=r.substring(21),i=e.getItem(r);if(i!==null)try{n[t]=JSON.parse(i)}catch{}}return n}catch(e){return R.warn(`DevTools: Failed to get all options`,e),{}}}getStorage(){return window.localStorage}},yn=class{constructor(e){h(this,`storage`,void 0),this.storage=e}set(e,t){this.storage.set(e,t),console.debug(`DevTools: ${String(e)} override set to ${t}`)}get(e){return this.storage.get(e)}clear(e){this.storage.remove(e),console.debug(`DevTools: ${String(e)} override cleared`)}clearAll(){this.storage.clear(),console.debug(`DevTools: All overrides cleared`)}getAll(){return this.storage.getAll()}applyOverrides(e){let t=this.getAll(),n={...e},r=Object.keys(t);if(r.length>0){console.debug(`DevTools: Current overrides:`,t);for(let e of r)t[e]!==void 0&&(n[e]=t[e]);console.debug(`DevTools: Overrides applied`)}return n}},bn=class e{static getInstance(){return e.instance||(e.instance=new e),e.instance}constructor(){h(this,`params`,void 0),h(this,`storage`,void 0),this.storage=new vn,this.params=new yn(this.storage)}};h(bn,`instance`,null);var xn=bn.getInstance(),M=class e{static set(t){Object.hasOwn(t,`voiceParams`)&&(Object.assign(e._params.voiceParams,t.voiceParams),delete t.voiceParams),Object.hasOwn(t,`specListenerParams`)&&(Object.assign(e._params.specListenerParams,t.specListenerParams),delete t.specListenerParams),Object.hasOwn(t,`apiAuth`)&&(y.accessToken=t.apiAuth.accessToken,y.sessionKey=t.apiAuth.sessionKey,y.sessionSecretKey=t.apiAuth.sessionSecretKey);let n=xn.params.applyOverrides(t);Object.assign(e._params,j.objectFilterOutValues(n,void 0))}static getScreenFrameRate(t){return t?e._params.fastScreenShareFrameRate:e._params.screenFrameRate}static get(t){return e._params[t]}static get appName(){return`ok.calls.sdk.js`}static get appVersion(){return e._params.appVersion}static get apiClientVersion(){return 1.1}static get sdkVersion(){return`2.8.13-dev.d5fda3ae.0`}static get debug(){return e._params.debug}static get protocolVersion(){return e._params.joinFromMultipleDevices?6:5}static get platform(){return e._params.platform}static set platform(t){e._params.platform=t}static get clientStatsPlatform(){return e._params.clientStatsPlatform}static set clientStatsPlatform(t){e._params.clientStatsPlatform=t}static get autoStartStats(){return e._params.autoStartStats}static get statQueueEnabled(){return e._params.statQueueEnabled}static get clientType(){return e._params.clientType}static set clientType(t){e._params.clientType=t}static get externalUserType(){return e._params.externalUserType}static set externalUserType(t){e._params.externalUserType=t}static get device(){return e._params.device}static get apiKey(){return e._params.apiKey}static get apiEnv(){return e._params.apiEnv}static get apiBaseUrl(){return e._params.apiBaseUrl}static set apiBaseUrl(t){e._params.apiBaseUrl=t}static apiEndpoint(t){switch(t??e.apiEnv){case`AUTO`:case`PROD`:return`https://api.mycdn.me`;case`CALLS`:return`https://calls.okcdn.ru`;case`PROD_OK`:return`https://api.ok.ru`;case`TEST`:return`https://apitest.ok.ru/api`;case`VIDEOTEST`:return`https://videotestapi.ok.ru/api`;case`CALLSTEST`:return`https://calls-test.okcdn.ru/api`;case`CALLS_BETA`:return`https://api-beta.calls-test.oneme.ru/api`;case`CALLS_BENDER`:return`https://api-bender.calls-test.oneme.ru/api`;case`CALLS_MAMES`:return`https://calls-mames.okcdn.ru/api`;case`CALLS_MARS`:return`https://api-mars.calls-test.oneme.ru/api`;default:return e._params.apiEnv}}static get apiTimeout(){return e._params.apiTimeout}static get apiMaxAttempt(){return e._params.apiMaxAttempt}static get authToken(){return e._params.authToken}static set authToken(t){e._params.authToken=t}static get anonymToken(){return e._params.anonymToken}static set anonymToken(t){e._params.anonymToken=t}static get domain(){return e._params.domain}static get externalDomain(){return e._params.externalDomain}static get iceServers(){return e._params.iceServers}static set iceServers(t){e._params.iceServers=t}static get wssBase(){return e._params.wssBase}static set wssBase(t){e._params.wssBase=t}static get wtsBase(){return e._params.wtsBase}static set wtsBase(t){e._params.wtsBase=t}static get wssToken(){return e._params.wssToken}static set wssToken(t){e._params.wssToken=t}static get signalingReconnectDelay(){return e._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return e._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return e._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return e._params.waitConnectionDelay}static get waitResponseDelay(){return e._params.waitResponseDelay}static get waitMessageDelay(){return e._params.waitMessageDelay}static get waitAnotherTabDelay(){return e._params.waitAnotherTabDelay}static get calleeUnavailableWaitingTime(){return e._params.calleeUnavailableWaitingTime}static get debugLog(){return e._params.debugLog}static get forceRelayPolicy(){return e._params.forceRelayPolicy}static set forceRelayPolicy(t){e._params.forceRelayPolicy=t}static get videoMinWidth(){return e._params.videoMinWidth}static get videoMaxWidth(){return e._params.videoMaxWidth}static set videoMaxWidth(t){e._params.videoMaxWidth=t}static get videoMinHeight(){return e._params.videoMinHeight}static get videoMaxHeight(){return e._params.videoMaxHeight}static set videoMaxHeight(t){e._params.videoMaxHeight=t}static get videoAspectRatio(){return e._params.videoAspectRatio}static get videoFrameRate(){return e._params.videoFrameRate}static get videoFacingMode(){return e._params.videoFacingMode||(T.isMobile()?Nt.USER:null)}static set videoFacingMode(t){e._params.videoFacingMode=t}static get displaySurface(){return e._params.displaySurface}static get audioEffects(){return e._params.audioEffects}static set audioEffects(t){e._params.audioEffects=t,e._params.audioEffects?.setLogger((e,...t)=>R.send(e,...t))}static get vad(){return e._params.vad}static set vad(t){e._params.vad=t}static get vadOptions(){return e._params.vadOptions}static set vadOptions(t){e._params.vadOptions=t}static get videoEffects(){return e._params.videoEffects}static set videoEffects(t){e._params.videoEffects=t,e._params.videoEffects?.setLogger((e,...t)=>R.send(e,...t))}static get videoEffectMaxWidth(){return e._params.videoEffectMaxWidth}static set videoEffectMaxWidth(t){e._params.videoEffectMaxWidth=t}static get videoEffectMaxHeight(){return e._params.videoEffectMaxHeight}static set videoEffectMaxHeight(t){e._params.videoEffectMaxHeight=t}static get vmoji(){return e._params.vmoji?.isBrowserSupported()?e._params.vmoji:null}static set vmoji(t){e._params.vmoji=t}static get vmojiOptions(){return e._params.vmojiOptions||{protocolVersion:1,renderingOptions:{}}}static set vmojiOptions(t){e._params.vmojiOptions=t}static get voiceParams(){return e._params.voiceParams}static get specListenerParams(){return e._params.specListenerParams}static get iceRestartWaitTime(){return e._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return e._params.transportConnectionWaitTime}static get switchTopologyOnReconnectFromAnySide(){return e._params.switchTopologyOnReconnectFromAnySide}static get statisticsInterval(){return e._params.statisticsInterval}static set statisticsInterval(t){e._params.statisticsInterval=t}static get networkStatisticsInterval(){return e._params.networkStatisticsInterval}static get perfStatReportEnabled(){return e._params.perfStatReportEnabled}static get callStatReportEnabled(){return e._params.callStatReportEnabled}static get enableLogPerfStatReport(){return e._params.enableLogPerfStatReport}static get asrDataChannel(){return e._params.asrDataChannel}static get consumerScreenDataChannelPacketSize(){return e._params.consumerScreenDataChannelPacketSize}static get screenShareWebmBuilder(){return e._params.screenShareWebmBuilder}static get noiseSuppression(){return e._params.noiseSuppression}static get preferH264(){return e._params.preferH264}static get preferVP9(){return e._params.preferVP9}static get audioNack(){return e._params.audioNack}static get movieShare(){return e._params.movieShare&&e.videoTracksCount>0}static get videoTracksCount(){return Number(e._params.videoTracksCount)}static get requestDisplayLayoutThrottleMs(){return Number(e._params.requestDisplayLayoutThrottleMs)}static get breakVideoPayloadTypes(){return e._params.breakVideoPayloadTypes}static get useCallsToContacts(){return e._params.useCallsToContacts}static get useParticipantListChunk(){return e._params.useParticipantListChunk&&e.videoTracksCount>0}static get useRooms(){return e._params.useRooms}static get useChatRooms(){return e._params.useChatRooms}static get addParticipant(){return e._params.addParticipant}static get waitForAdminInGroupCalls(){return e._params.waitForAdminInGroupCalls}static get hold(){return e._params.hold}static get maxParallelCalls(){return e._params.maxParallelCalls}static get participantListChunkInitIndex(){return e._params.participantListChunkInitIndex??0}static get participantListChunkInitCount(){return e._params.participantListChunkInitCount??null}static get filterObservers(){return e._params.filterObservers}static get muteMode(){return e._params.muteMode}static get preserveAudioTracks(){return e._params.preserveAudioTracks}static get audioShare(){return T.isAudioShareSupported()&&e._params.audioShare}static get audioShareWindowInclude(){return e._params.audioShareWindowInclude}static get audioShareSystemInclude(){return e._params.audioShareSystemInclude}static get fastScreenShare(){return e._params.fastScreenShare}static get screenShareCongestionControl(){return e._params.screenShareCongestionControl}static get screenShareCongestionControlThreshold(){return e._params.screenShareCongestionControlThreshold}static get fastScreenShareWidth(){return e._params.fastScreenShareWidth}static get fastScreenShareHeight(){return e._params.fastScreenShareHeight}static get consumerFastScreenShare(){return e._params.consumerFastScreenShare}static get consumerFastScreenShareQualityOnDemand(){return e._params.consumerFastScreenShareQualityOnDemand}static get videoSuspend(){return e._params.videoSuspend}static get enumerateDevicesDelay(){return e._params.enumerateDevicesDelay}static get switchVideoAtBadNetwork(){return e._params.switchVideoAtBadNetwork}static get enableVideoEffectsFpsDegradation(){return e._params.enableVideoEffectsFpsDegradation}static get simulcast(){return T.isSimulcastSupportedByBrowser()&&e._params.simulcast}static get webtransport(){return e._params.webtransport}static get waitForRecordResponse(){return e._params.waitForRecordResponse}static get transparentAudio(){return e._params.transparentAudio}static get enableSessionStateUpdates(){return e._params.enableSessionStateUpdates}static get safariAudioElement(){return e._params.safariAudioElement}static get forwardEmptyIceCandidate(){return e._params.forwardEmptyIceCandidate}static toJSON(){return{apiKey:e._params.apiKey,apiEnv:e._params.apiEnv,audioShare:e._params.audioShare,audioShareWindowInclude:e._params.audioShareWindowInclude,audioShareSystemInclude:e._params.audioShareSystemInclude,useCallsToContacts:e._params.useCallsToContacts,useParticipantListChunk:e._params.useParticipantListChunk,useRooms:e._params.useRooms,useChatRooms:e._params.useChatRooms,addParticipant:e._params.addParticipant,fastScreenShare:e._params.fastScreenShare,participantListChunkInitCount:e._params.participantListChunkInitCount,screenShareCongestionControl:e._params.screenShareCongestionControl,screenShareCongestionControlThreshold:e._params.screenShareCongestionControlThreshold,videoTracksCount:e._params.videoTracksCount,requestDisplayLayoutThrottleMs:e._params.requestDisplayLayoutThrottleMs,asrDataChannel:e._params.asrDataChannel,videoMaxHeight:e._params.videoMaxHeight,videoMaxWidth:e._params.videoMaxWidth,videoEffectMaxHeight:e._params.videoEffectMaxHeight,videoEffectMaxWidth:e._params.videoEffectMaxWidth,videoSuspend:e._params.videoSuspend,debugLog:e._params.debugLog,callStatReportEnabled:e._params.callStatReportEnabled,joinFromMultipleDevices:e._params.joinFromMultipleDevices,movieShare:e._params.movieShare,clientType:e._params.clientType,clientStatsPlatform:e._params.clientStatsPlatform,appVersion:e._params.appVersion,autoStartStats:e._params.autoStartStats,statQueueEnabled:e._params.statQueueEnabled,consumerScreenDataChannelPacketSize:e._params.consumerScreenDataChannelPacketSize,switchVideoAtBadNetwork:e._params.switchVideoAtBadNetwork,simulcast:e._params.simulcast,webtransport:e._params.webtransport,waitForRecordResponse:e._params.waitForRecordResponse,transparentAudio:e._params.transparentAudio,enableSessionStateUpdates:e._params.enableSessionStateUpdates,safariAudioElement:e._params.safariAudioElement,forwardEmptyIceCandidate:e._params.forwardEmptyIceCandidate}}};h(M,`_params`,{platform:`WEB`,clientStatsPlatform:``,appVersion:`0.0.0`,autoStartStats:!0,statQueueEnabled:!1,clientType:`PORTAL`,externalUserType:``,device:`browser`,apiKey:``,authToken:``,anonymToken:``,apiEnv:`AUTO`,apiBaseUrl:null,domain:``,externalDomain:``,iceServers:[],wssBase:``,wtsBase:``,wssToken:``,signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:10,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,debug:!1,apiTimeout:5e3,apiMaxAttempt:10,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoFacingMode:null,displaySurface:`monitor`,audioEffects:null,vad:null,vadOptions:{},videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,vmoji:null,vmojiOptions:null,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,switchTopologyOnReconnectFromAnySide:!1,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,enableLogPerfStatReport:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},asrDataChannel:!1,consumerScreenDataChannelPacketSize:64*1024,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!1,audioNack:!0,videoTracksCount:30,requestDisplayLayoutThrottleMs:750,movieShare:!1,useCallsToContacts:!1,useParticipantListChunk:!1,useRooms:!1,useChatRooms:!1,addParticipant:!1,waitForAdminInGroupCalls:!1,hold:!1,maxParallelCalls:2,participantListChunkInitIndex:0,participantListChunkInitCount:null,breakVideoPayloadTypes:!1,joinFromMultipleDevices:!1,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1,audioShare:!1,audioShareWindowInclude:!1,audioShareSystemInclude:!1,fastScreenShare:!1,screenShareCongestionControl:!1,screenShareCongestionControlThreshold:2100,consumerFastScreenShare:!1,consumerFastScreenShareQualityOnDemand:!1,fastScreenShareFrameRate:24,fastScreenShareWidth:1280,fastScreenShareHeight:720,videoSuspend:!1,enumerateDevicesDelay:2e3,switchVideoAtBadNetwork:!1,enableVideoEffectsFpsDegradation:!1,simulcast:!1,webtransport:!1,waitForRecordResponse:!1,transparentAudio:!1,enableSessionStateUpdates:!1,safariAudioElement:!0,forwardEmptyIceCandidate:!1});var N=function(e){return e.WAITING_HALL=`WAITING_HALL`,e.WAIT_FOR_ADMIN=`WAIT_FOR_ADMIN`,e.WAITING=`WAITING`,e.CONNECTING=`CONNECTING`,e.CONNECTED=`CONNECTED`,e.RECONNECT=`RECONNECT`,e.ERROR=`ERROR`,e.HANGUP=`HANGUP`,e.PERMISSIONS=`PERMISSIONS`,e.ONHOLD=`ONHOLD`,e}({});function P(e,...t){let n=M.get(e);typeof n==`function`&&setTimeout(n,0,...t)}function F(e,t,...n){if(M.filterObservers){if(Array.isArray(t)){if(t=t.filter(e=>!e.observer),!t.length)return}else if(t.observer)return}P(e,t,...n)}function I(e){return Object.assign({},e)}function Sn(e){return e.slice()}var Cn;(function(e){function t(e,t,n){P(`onLocalStream`,e,I(t),n)}e.onLocalStream=t;function n(e,t,n){P(`onScreenStream`,e,I(t),n)}e.onScreenStream=n;function r(e,t,n){P(`onVmojiStream`,e,I(t),n)}e.onVmojiStream=r;function i(e,t){P(`onVmojiError`,e,t)}e.onVmojiError=i;function a(e,t,n){P(`onLocalStreamUpdate`,I(e),t,n)}e.onLocalStreamUpdate=a;function o(e,t){R.debug(`Local status:`,e),P(`onLocalStatus`,e,t)}e.onLocalStatus=o;function s(e,t,n){F(`onRemoteStream`,e,t,n)}e.onRemoteStream=s;function c(e,t,n){F(`onRemoteLive`,e,t,n)}e.onRemoteLive=c;function l(e,t,n){F(`onLocalLive`,e,t,n)}e.onLocalLive=l;function u(e,t,n){F(`onRemoteLiveUpdate`,e,t,n)}e.onRemoteLiveUpdate=u;function d(e,t,n){F(`onLocalLiveUpdate`,e,t,n)}e.onLocalLiveUpdate=d;function f(e,t,n){F(`onRemoteScreenStream`,e,t,n)}e.onRemoteScreenStream=f;function p(e,t,n){F(`onRemoteVmojiStream`,e,t,n)}e.onRemoteVmojiStream=p;function m(e,t,n,r){F(`onRemoteStreamSuspended`,e,t,n,r)}e.onRemoteStreamSuspended=m;function ee(e,t,n,r,i,a){F(`onConversation`,e,I(t),I(n),r,i,a)}e.onConversation=ee;function te(e,t){e&&P(`onConversationParticipantListChunk`,e,t)}e.onConversationParticipantListChunk=te;function ne(e,t,n,r){F(`onRemoteMediaSettings`,e,I(t),n,r)}e.onRemoteMediaSettings=ne;function h(e,t,n){F(`onLocalMediaSettings`,e,I(t),n)}e.onLocalMediaSettings=h;function re(e,t,n,r){F(`onRemoteSharedMovieInfo`,e,I(t),n,r)}e.onRemoteSharedMovieInfo=re;function ie(e,t,n,r){F(`onRemoteSharedMovieStoppedInfo`,e,I(t),n,r)}e.onRemoteSharedMovieStoppedInfo=ie;function ae(e,t,n,r){F(`onLocalSharedMovieInfo`,e,I(t),n,r)}e.onLocalSharedMovieInfo=ae;function oe(e,t,n,r){F(`onLocalSharedMovieStoppedInfo`,e,I(t),n,r)}e.onLocalSharedMovieStoppedInfo=oe;function se(e,t,n,r){F(`onRemoteSharedUrl`,e,t,n,r)}e.onRemoteSharedUrl=se;function ce(e,t,n){F(`onParticipantAdded`,e,t,n)}e.onParticipantAdded=ce;function g(e,t,n){F(`onParticipantJoined`,e,t,n)}e.onParticipantJoined=g;function _(e,t=!1,n){P(`onLocalParticipantState`,I(e),t,n)}e.onLocalParticipantState=_;function le(e,t,n,r){F(`onRemoteParticipantState`,e,I(t),n,r)}e.onRemoteParticipantState=le;function ue(e,t,n){P(`onRemoteParticipantsState`,e,t,n)}e.onRemoteParticipantsState=ue;function de(e,t,n=null,r){R.debug(`Remote status:`,t,e),F(`onRemoteStatus`,e,t,n,r)}e.onRemoteStatus=de;function fe(){P(`onPermissionsRequested`)}e.onPermissionsRequested=fe;function pe(e,t){P(`onPermissionsError`,e,t)}e.onPermissionsError=pe;function me(e,t,n){F(`onRemoteRemoved`,e,t,n)}e.onRemoteRemoved=me;function he(e,t,n,r){P(`onCallState`,e,t,I(n),r)}e.onCallState=he;function ge(e,t,n){P(`onDeviceSwitched`,e,t,n)}e.onDeviceSwitched=ge;function _e(e,t,n,r=!1,i=!1,a=null,o=null,s,c,l=null,u){let d=c?Sn(c):void 0;P(`onMuteStates`,I(e),Sn(t),Sn(n),r,i,a,o,s,d,l,u)}e.onMuteStates=_e;function ve(e,t,n=!1,r){F(`onRolesChanged`,e,Sn(t),n,r)}e.onRolesChanged=ve;function v(e,t=!1,n){P(`onLocalRolesChanged`,Sn(e),t,n)}e.onLocalRolesChanged=v;function ye(e,t,n,r,i){F(`onPinnedParticipant`,e,t,n,r,i)}e.onPinnedParticipant=ye;function be(e,t,n){P(`onLocalPin`,e,t,n)}e.onLocalPin=be;function xe(e,t){P(`onOptionsChanged`,Sn(e),t)}e.onOptionsChanged=xe;function Se(e){P(`onCallAccepted`,e)}e.onCallAccepted=Se;function Ce(e){P(`onCallActive`,e)}e.onCallActive=Ce;function we(e,t,n){F(`onAcceptedCall`,e,t,n)}e.onAcceptedCall=we;function Te(e){P(`onRateNeeded`,e)}e.onRateNeeded=Te;function Ee(e,t){F(`onSpeakerChanged`,e,t)}e.onSpeakerChanged=Ee;function De(e,t){P(`onVolumesDetected`,Sn(e),t)}e.onVolumesDetected=De;function Oe(e,t){P(`onLocalVolume`,e,t)}e.onLocalVolume=Oe;function ke(e,t,n){P(`onJoinStatus`,e,t,n)}e.onJoinStatus=ke;function Ae(e,t){P(`onHangup`,e,t)}e.onHangup=Ae;function je(e){P(`onMultipartyChatCreated`,I(e))}e.onMultipartyChatCreated=je;function Me(){P(`onDeviceChange`)}e.onDeviceChange=Me;function Ne(e){P(`onFingerprintChange`,e)}e.onFingerprintChange=Ne;function Pe(){P(`onTokenExpired`)}e.onTokenExpired=Pe;function Fe(e,t,n=!1,r){P(`onChatMessage`,e,t,n,r)}e.onChatMessage=Fe;function Ie(e,t,n=!1,r){P(`onCustomData`,e,t,n,r)}e.onCustomData=Ie;function Le(e,t,n,r,i,a,o=null,s){P(`onRecordStarted`,e,t,n,r,i,a,o,s)}e.onRecordStarted=Le;function Re(e=null,t,n){P(`onRecordStopped`,e,t,n)}e.onRecordStopped=Re;function ze(e,t){P(`onLocalNetworkStatusChanged`,e,t)}e.onLocalNetworkStatusChanged=ze;function Be(e,t){P(`onNetworkStatusChanged`,e,t)}e.onNetworkStatusChanged=Be;function Ve(e,...t){P(`onDebugMessage`,e,...t)}e.onDebugMessage=Ve;function He(e,t,...n){P(`onDebugMessageWithContext`,e,t,...n)}e.onDebugMessageWithContext=He;function Ue(e,t){P(`onStatistics`,Object.assign({},e,{memory:t}))}e.onStatistics=Ue;function We(){P(`onAutoplayError`)}e.onAutoplayError=We;function Ge(e,t,n,r,i,a){P(`onChatRoomUpdated`,e,t,n,r,i,a)}e.onChatRoomUpdated=Ge;function Ke(e,t){P(`onPromoted`,e,t)}e.onPromoted=Ke;function qe(e,t){P(`onRemoteMixedAudioStream`,e,t)}e.onRemoteMixedAudioStream=qe;function Je(e,t){P(`onJoinLinkChanged`,e,t)}e.onJoinLinkChanged=Je;function Ye(e,t){P(`onRoomsUpdated`,e,t)}e.onRoomsUpdated=Ye;function y(e,t,n,r,i){P(`onRoomUpdated`,e,t,n,r,i)}e.onRoomUpdated=y;function b(e,t){P(`onRoomParticipantsUpdated`,e,t)}e.onRoomParticipantsUpdated=b;function x(e,t){P(`onRoomSwitched`,e,t)}e.onRoomSwitched=x;function S(e,t){P(`onRoomStart`,e,t)}e.onRoomStart=S;function C(e,t=null,n){P(`onFeedback`,e,t,n)}e.onFeedback=C;function Xe(e,t){P(`onFeaturesPerRoleChanged`,e,t)}e.onFeaturesPerRoleChanged=Xe;function Ze(e,t){P(`onParticipantVmojiUpdate`,e,t)}e.onParticipantVmojiUpdate=Ze;function Qe(e,t,n){P(`onAsrSet`,e,t,n)}e.onAsrSet=Qe;function $e(e,t,n,r){P(`onAsrStarted`,e,t,n,r)}e.onAsrStarted=$e;function et(e,t){P(`onAsrStopped`,e,t)}e.onAsrStopped=et;function tt(e,t,n,r,i){P(`onAsrTranscription`,e,t,n,r,i)}e.onAsrTranscription=tt;function nt(e,t,n){P(`onParticipantIdChanged`,e,t,n)}e.onParticipantIdChanged=nt;function rt(e,t){P(`onVideoSuspendSuggest`,e,t)}e.onVideoSuspendSuggest=rt;function it(e){P(`onSignalingMessage`,typeof e==`string`?e:I(e))}e.onSignalingMessage=it;function at(e,t){P(`onPromotionApproved`,e,t)}e.onPromotionApproved=at;function ot(e,t){P(`onPeerRegistered`,e,t)}e.onPeerRegistered=ot;function st(e,t){P(`onNonFatalError`,e,t)}e.onNonFatalError=st})(Cn||(Cn={}));var L=Cn,wn=function(e){return e.DEBUG=`DEBUG`,e.LOG=`LOG`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),Tn;(function(e){let t=`📞`,n=()=>({sessionId:null,conversationId:null}),r=(e,t,...n)=>{L.onDebugMessage(t,...n),L.onDebugMessageWithContext(t,{conversationId:e.conversationId},...n)},i=console.debug.bind(console,t),a=console.log.bind(console,t),o=console.warn.bind(console,t),s=console.error.bind(console,t),c=!1;function l(e){if(!e)return n();try{return e()}catch{return n()}}function u(e,t,n){let u=l(n);if(M.debugLog&&je(e,t,u.sessionId||void 0),c)switch(e){case`DEBUG`:i(...t);break;case`LOG`:a(...t);break;case`WARN`:o(...t);break;case`ERROR`:s(...t);break}else r(u,e,...t)}function d(...e){u(`DEBUG`,e)}e.debug=d;function f(...e){u(`LOG`,e)}e.log=f;function p(...e){u(`WARN`,e)}e.warn=p;function m(...e){u(`ERROR`,e)}e.error=m;function ee(){return c}e.enabled=ee;function te(e){c=e,M.debugLog&&Me()}e.toggle=te;function ne(e,...t){switch(e){case`DEBUG`:d(...t);break;case`LOG`:f(...t);break;case`WARN`:p(...t);break;case`ERROR`:m(...t);break}}e.send=ne;function h(e){return{debug:(...t)=>u(`DEBUG`,t,e),log:(...t)=>u(`LOG`,t,e),warn:(...t)=>u(`WARN`,t,e),error:(...t)=>u(`ERROR`,t,e)}}e.createLogger=h;function re(e=null){let t=null,n=e;function r(){!M.debugLog||t||(t=Ne(),n&&Pe(n,t))}let i=()=>(r(),{sessionId:t,conversationId:n});return{get sessionId(){return t},get conversationId(){return n},setConversationId(e){n=e,t&&Pe(n,t)},send:(e,...t)=>u(e,t,i),debug:(...e)=>u(`DEBUG`,e,i),log:(...e)=>u(`LOG`,e,i),warn:(...e)=>u(`WARN`,e,i),error:(...e)=>u(`ERROR`,e,i)}}e.createSessionLogger=re;function ie(e,...t){}e.test=ie})(Tn||(Tn={}));var R=Tn,z=new class{constructor(){h(this,`_conversations`,new Map),h(this,`_reserved`,new Set),h(this,`_activeId`,null),h(this,`_mutex`,!1),h(this,`_pendingRemovals`,new Set)}reserve(e){if(this._conversations.has(e)||this._reserved.has(e))throw Error(`CallRegistry: conversation ${e} already exists`);this._reserved.add(e)}add(e){let t=e.id;if(this._conversations.has(t)){R.warn(`CallRegistry: conversation ${t} already exists, skip duplicate add`),this._reserved.delete(t);return}this._conversations.set(t,e),this._reserved.delete(t)}remove(e){if(e){if(this._reserved.delete(e),this._mutex){this._pendingRemovals.add(e);return}this._conversations.delete(e),this._activeId===e&&(this._activeId=null)}}get(e){return this._conversations.get(e)}getActive(){return this._activeId?this._conversations.get(this._activeId)??null:null}getFirst(){return this._conversations.values().next().value??null}getActiveId(){return this._activeId}has(e){return this._conversations.has(e)||this._reserved.has(e)}getAll(){return Array.from(this._conversations.values())}get callsLength(){return this._conversations.size}async setActive(e){if(!(this._activeId===e||!this._conversations.has(e)||this._mutex)){this._mutex=!0;try{let t=this.getActive(),n;if(t){n=t.mediaSettings;try{await t.hold(!0)}catch(e){throw R.error(`Can't hold previous active, error: ${e}`),Error(`Cannot switch call: hold failed`)}}this._conversations.has(e)&&(this._activeId=e,L.onCallActive(e));let r=this._conversations.get(e);if(r&&r?.isCallHeld)try{await r.hold(!1,n)}catch(e){throw R.error(`Can't hold next active, error: ${e}`),Error(`Cannot switch call: hold failed`)}}finally{this._mutex=!1,this._flushPendingRemovals()}}}async setHold(e){if(!(this._activeId!==e||!this._conversations.has(e)||this._mutex)){this._mutex=!0;try{let e=this.getActive();if(e)try{await e.hold(!0)}catch(e){throw R.error(`Can't hold previous active, error: ${e}`),Error(`Cannot switch call: hold failed`)}this._activeId=null}finally{this._mutex=!1,this._flushPendingRemovals()}}}async switchCall(e){this._activeId===e?await this.setHold(e):await this.setActive(e)}clear(){this._conversations.clear(),this._reserved.clear(),this._pendingRemovals.clear(),this._activeId=null}_flushPendingRemovals(){if(this._pendingRemovals.size!==0){for(let e of this._pendingRemovals)this._conversations.delete(e),this._activeId===e&&(this._activeId=null);this._pendingRemovals.clear()}}},En=class extends Error{constructor(e){super(e?`Signaling disposed. Command ${e}`:`Signaling disposed`),this.name=`SignalingDisposedError`}},Dn=class extends Error{constructor(e){super(e?`Producer connection closed. Command ${e}`:`Producer connection closed`),this.name=`ProducerConnectionClosedError`}},On=class extends b{constructor(...e){super(...e),h(this,`_abortSignal`,void 0)}setAbortSignal(e){this._abortSignal=e}get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setWebTransportEndpoint(e){}readyToSend(e=!0){}async requestTestMode(e,t){}getNextCommandSequenceNumber(){return 0}},B=function(e){return e.RECOVER=`recover`,e.ACCEPT_CALL=`accept-call`,e.ADD_PARTICIPANT=`add-participant`,e.REMOVE_PARTICIPANT=`remove-participant`,e.HANGUP=`hangup`,e.TRANSMIT_DATA=`transmit-data`,e.ACCEPT_PRODUCER=`accept-producer`,e.ALLOCATE_CONSUMER=`allocate-consumer`,e.CHANGE_MEDIA_SETTINGS=`change-media-settings`,e.CHANGE_PARTICIPANT_STATE=`change-participant-state`,e.CHANGE_STREAM_PRIORITIES=`change-streams-priorities`,e.UPDATE_DISPLAY_LAYOUT=`update-display-layout`,e.REPORT_PERF_STAT=`report-perf-stat`,e.REPORT_SHARING_STAT=`report-sharing-stat`,e.REPORT_NETWORK_STAT=`report-network-stat`,e.RECORD_START=`record-start`,e.RECORD_STOP=`record-stop`,e.RECORD_PUBLISH=`record-publish`,e.RECORD_SET_CONF=`record-set-conf`,e.RECORD_GET_STATUS=`record-get-status`,e.SWITCH_MICRO=`switch-micro`,e.SWITCH_TOPOLOGY=`switch-topology`,e.REQUEST_REALLOC=`request-realloc`,e.CHAT_MESSAGE=`chat-message`,e.CHAT_HISTORY=`chat-history`,e.CUSTOM_DATA=`custom-data`,e.GRANT_ROLES=`grant-roles`,e.MUTE_PARTICIPANT=`mute-participant`,e.ENABLE_FEATURE_FOR_ROLES=`enable-feature-for-roles`,e.PIN_PARTICIPANT=`pin-participant`,e.UPDATE_MEDIA_MODIFIERS=`update-media-modifiers`,e.CHANGE_OPTIONS=`change-options`,e.GET_WAITING_HALL=`get-waiting-hall`,e.GET_PARTICIPANT_LIST_CHUNK=`get-participant-list-chunk`,e.GET_PARTICIPANTS=`get-participants`,e.PROMOTE_PARTICIPANT=`promote-participant`,e.REQUEST_TEST_MODE=`request-test-mode`,e.ADD_MOVIE=`add-movie`,e.UPDATE_MOVIE=`update-movie`,e.REMOVE_MOVIE=`remove-movie`,e.START_URL_SHARING=`start-url-sharing`,e.STOP_URL_SHARING=`stop-url-sharing`,e.GET_ROOMS=`get-rooms`,e.UPDATE_ROOMS=`update-rooms`,e.ACTIVATE_ROOMS=`activate-rooms`,e.REMOVE_ROOMS=`remove-rooms`,e.SWITCH_ROOM=`switch-room`,e.FEEDBACK=`feedback`,e.ASR_START=`asr-start`,e.ASR_STOP=`asr-stop`,e.REQUEST_ASR=`request-asr`,e.REQUEST_PROMOTION=`request-promotion`,e.ACCEPT_PROMOTION=`accept-promotion`,e.GET_HAND_QUEUE=`get-hand-queue`,e.ENABLE_VIDEO_SUSPEND=`enable-video-suspend`,e.ENABLE_VIDEO_SUSPEND_SUGGEST=`enable-video-suspend-suggest`,e.HOLD=`hold`,e.PUT_HANDS_DOWN=`put-hands-down`,e.CHANGE_SIMULCAST=`change-simulcast`,e}(B||{});function kn(e){return e.stopStream}function An(e){return e.keyFrameRequested}function jn(e){if(kn(e))return`ss`;if(An(e))return`kf`;let t=``;return e.priority!==void 0&&(t+=`p=`+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==``&&(t+=`:`),t+=`sz=`+Math.round(e.width)+`x`+Math.round(e.height)),e.fit!==void 0&&(t!==``&&(t+=`:`),t+=`fit=`+e.fit),t}var V=function(e){return e.CAMERA=`CAMERA`,e.SCREEN=`SCREEN`,e.STREAM=`STREAM`,e.MOVIE=`MOVIE`,e.ANIMOJI=`ANIMOJI`,e.SHARED_URL=`SHARED_URL`,e}({}),Mn=`s`,Nn=`m`;function Pn(e){return e.participantId+(e.mediaType?`:`+Mn+e.mediaType:``)+(e.streamName?`:`+Nn+e.streamName:``)}function Fn(e){let t=e.split(`:`),n=t.shift();if(!n)throw Error(`Illegal stream description: `+e);let r=null,i,a=0;for(let n of t)switch(n.charAt(0)){case Mn:r=In(n.slice(1));break;case Nn:i=n.slice(1);break;case`d`:a=Number.parseInt(n.slice(1),10);break;default:throw Error(`Unexpected parameter type `+n.charAt(0)+` in stream description `+e)}return{participantId:j.compose(n,a),mediaType:r,streamName:i}}function In(e){for(let t of Object.keys(V))if(t===e)return V[t];return null}function Ln(){let e=new DataView(new ArrayBuffer(64)),t=0;function n(n){if(t+n>e.byteLength){let r=new Uint8Array(Math.max(t+n,e.byteLength+64));r.set(new Uint8Array(e.buffer.slice(0,t))),e=new DataView(r.buffer)}}return{put(r){if(n(r.byteLength),Rn(r)){let n=r.buffer;new Uint8Array(e.buffer).set(new Uint8Array(n),t)}else new Uint8Array(e.buffer).set(new Uint8Array(r),t);t+=r.byteLength},putI8(r){n(1),e.setInt8(t,r),++t},putI16(r){n(2),e.setInt16(t,r),t+=2},putI32(r){n(4),e.setInt32(t,r),t+=4},putI64(r){n(8);let i=r<0;i&&(r=-r);let a=r/4294967296|0,o=r%4294967296|0;i&&(o=~o+1|0,a=o===0?~a+1|0:~a),e.setUint32(t,a),e.setUint32(t+4,o),t+=8},putUi8(r){n(1),e.setUint8(t,r),++t},putUi16(r){n(2),e.setUint16(t,r),t+=2},putUi32(r){n(4),e.setUint32(t,r),t+=4},putUi64(r){n(8),e.setUint32(t,r/4294967296|0),e.setUint32(t+4,r%4294967296),t+=8},putF(r){n(8),e.setFloat64(t,r),t+=8},ui8array(){return new Uint8Array(e.buffer.slice(0,t))}}}function Rn(e){return e.buffer!==void 0}function zn(e){let t=ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),n=0;return{peek(){return t.getUint8(n)},get(e){n+=e;let r=t.byteOffset;return t.buffer.slice(r+n-e,r+n)},getI8(){return t.getInt8(n++)},getI16(){return n+=2,t.getInt16(n-2)},getI32(){return n+=4,t.getInt32(n-4)},getI64(){n+=8;let e=t.getInt32(n-8),r=t.getUint32(n-4);return e*4294967296+r},getUi8(){return t.getUint8(n++)},getUi16(){return n+=2,t.getUint16(n-2)},getUi32(){return n+=4,t.getUint32(n-4)},getUi64(){n+=8;let e=t.getUint32(n-8),r=t.getUint32(n-4);return e*4294967296+r},getF32(){return n+=4,t.getFloat32(n-4)},getF64(){return n+=8,t.getFloat64(n-8)}}}var Bn=0,Vn=1,Hn=2,Un=3,Wn=4,Gn=5,Kn=6,qn=7,Jn=0,Yn=1,Xn=2,Zn=0,Qn=0,$n=0,er=1,tr=class{constructor(e=R){h(this,`participantIdRegistry`,null),h(this,`_debug`,void 0),this._debug=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}serializeUpdateDisplayLayout(e,t){let n=Ln();l.Int.enc(n,Bn),l.Int.enc(n,Zn),l.Int.enc(n,e),l.Nil.enc(n,null);let r=[];for(let e in t)Object.hasOwn(t,e)&&this.writeLayout(t,e,r);return l.Arr.enc(n,r),l.Nil.enc(n,null),n.ui8array().buffer}writeLayout(e,t,n){let r=e[t],i=Ln();if(this.writeStreamDesc(t,i),kn(r))l.Int.enc(i,Yn);else if(An(r))l.Int.enc(i,Xn);else if(l.Int.enc(i,Jn),r.priority===void 0?l.Nil.enc(i,null):l.Int.enc(i,r.priority),r.width!==void 0&&r.height!==void 0?(l.Int.enc(i,Math.round(r.width)),l.Int.enc(i,Math.round(r.height))):(l.Nil.enc(i,null),l.Nil.enc(i,null)),r.fit!==void 0)switch(r.fit){case`cv`:l.Int.enc(i,$n);break;case`cn`:l.Int.enc(i,er);break;default:l.Nil.enc(i,null)}else l.Nil.enc(i,null);n.push(i.ui8array().buffer)}writeStreamDesc(e,t){if(this.participantIdRegistry){let n=this.participantIdRegistry.getCompactId(e);if(n!==void 0){l.Int.enc(t,n);return}}l.Str.enc(t,e)}serializePerfStatReport(e,t){let n=Ln();return l.Int.enc(n,Vn),l.Int.enc(n,Zn),l.Int.enc(n,e),l.Int.enc(n,t.framesDecoded),l.Int.enc(n,t.framesReceived),n.ui8array().buffer}serializeSharingStatReport(e,t){let n=Ln();return l.Int.enc(n,Hn),l.Int.enc(n,Zn),l.Int.enc(n,e),l.Int.enc(n,t.minDelay),l.Int.enc(n,t.maxDelay),l.Int.enc(n,t.avgDelay),l.Int.enc(n,t.largeDelayDuration),n.ui8array().buffer}serializeRequestAsr(e,t){let n=Ln();return l.Int.enc(n,Un),l.Int.enc(n,Zn),l.Int.enc(n,e),l.Bool.enc(n,t.request),n.ui8array().buffer}serializeNetworkStatReport(e,t){let n=Ln();return l.Int.enc(n,Wn),l.Int.enc(n,Zn),l.Int.enc(n,e),l.Int.enc(n,t.timestamp),l.Int.enc(n,t.sendBitrate),n.ui8array().buffer}serializeEnableVideoSuspend(e,t){let n=Ln();return l.Int.enc(n,Gn),l.Int.enc(n,Zn),l.Int.enc(n,e),l.Bool.enc(n,t.enabled),n.ui8array().buffer}serializeEnableVideoSuspendSuggest(e,t){let n=Ln();return l.Int.enc(n,Kn),l.Int.enc(n,Zn),l.Int.enc(n,e),l.Bool.enc(n,t.enabled),n.ui8array().buffer}serializeChangeSimulcast(e,t){let n=Ln();l.Int.enc(n,qn),l.Int.enc(n,Zn),l.Int.enc(n,e);let r=t.simulcastInfo.streams.length;l.Int.enc(n,t.mediaSource),l.Int.enc(n,r);for(let e of t.simulcastInfo.streams)l.Str.enc(n,e.rid),l.Int.enc(n,e.width),l.Int.enc(n,e.height),l.Int.enc(n,e.fps),l.Int.enc(n,e.bitrate/1e3);return n.ui8array().buffer}async deserializeCommandResponse(e){let t;t=e instanceof Blob?zn(`arrayBuffer`in Blob.prototype?await e.arrayBuffer():await ln(e)):zn(e);let n=l.Int.dec(t),r=l.Int.dec(t);if(r!==Zn){this._debug.warn(`Unsupported version for command type: `+n+`, version `+r);return}if(l.Int.dec(t)!==Qn){this._debug.warn(`Error code: `+n+`received for command type: `+n+`, version `+r);return}switch(n){case Bn:return this.deserializeUpdateDisplayLayoutResponse(t);case Vn:return this.deserializeReportPerfStatResponse(t);default:this._debug.warn(`unsupported command response commandType: `+n);return}}deserializeUpdateDisplayLayoutResponse(e){let t=l.Int.dec(e),n=l.Arr.dec(e),r={};return n.forEach(e=>{let t=zn(e),n=l.Any.dec(t);if(typeof n==`string`)r[n]=l.Int.dec(t);else{let e=n,i=Pn(this.participantIdRegistry?.getStreamDescription(e));r[i]=l.Int.dec(t)}}),{type:`response`,sequence:t,response:B.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:r}}deserializeReportPerfStatResponse(e){let t=l.Int.dec(e),n=l.Int.dec(e);return{type:`response`,sequence:t,response:B.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:n}}},H=function(e){return e.CALL_INIT=`call_init`,e.CALL_START=`call_start`,e.CALL_ACCEPTED_OUTGOING=`call_accepted_outgoing`,e.CALL_ACCEPTED_INCOMING=`call_accepted_incoming`,e.FIRST_MEDIA_SENT=`first_media_sent`,e.CALL_FINISH=`call_finish`,e.CODEC_USAGE=`codec_usage`,e.SIGNALING_CONNECTED=`signaling_connected`,e.SCREENSHARE_FIRST_FRAME=`screen_share_first_frame`,e.FIRST_MEDIA_RECEIVED=`first_media_received`,e.CALL_DECLINED_OR_HANGED_LOCALLY=`CallDeclinedOrHangedLocally`,e.USER_FEEDBACK_RECEIVED=`UserFeedbackReceived`,e.SIGNALING_PING_SUMMARY=`signaling_ping_summary`,e.SIGNALING_COMMAND_SUMMARY=`signaling_command_summary`,e.API_CALL=`api_call`,e.WEBSOCKET_CONNECTED=`websocket_connected`,e.WEBSOCKET_RECONNECTED=`websocket_reconnected`,e.WEBSOCKET_FAILED_PINGS=`websocket_failed_pings`,e.WEBSOCKET_FAILED_EXCEPTION=`websocket_failed_exception`,e.WEBSOCKET_TIMEOUT=`websocket_timeout`,e.WEBSOCKET_RESTART=`websocket_restart`,e.WEBTRANSPORT_CONNECTED=`webtransport_connected`,e.WEBTRANSPORT_RECONNECTED=`webtransport_reconnected`,e.WEBTRANSPORT_FAILED_PINGS=`webtransport_failed_pings`,e.WEBTRANSPORT_FAILED_EXCEPTION=`webtransport_failed_exception`,e.WEBTRANSPORT_TIMEOUT=`webtransport_timeout`,e.WEBTRANSPORT_RESTART=`webtransport_restart`,e}(H||{}),nr=1e3;function U(e,t,n=0){return t in e&&e[t]?e[t]:n}function rr(...e){return t=>{for(let n of e)if(n(t))return!0;return!1}}function ir(e,t){return n=>n[e]===t}function ar(e){return(t,n)=>n[e]-t[e]}function or(e,t){return t.reduce((t,n)=>(t[n[e]]=n,t),{})}function sr(e){let t={},n=[];for(let r of e)t[r.id]||(t[r.id]=!0,n.push(r));return n}function cr(e){return Object.keys(e).filter(t=>e[t]!==void 0).map(t=>[t,e[t]]).reduce((e,t)=>(e[t[0]]=j.isObject(t[1])?cr(t[1]):t[1],e),{})}function lr(e){let t=[];for(let n of e)n.forEach(e=>t.push(e));return t}async function ur(e){let t=[];return RTCRtpReceiver.prototype.getStats?(t.push(...e.getReceivers().map(e=>e.getStats())),t.push(...e.getSenders().map(e=>e.getStats()))):t.push(e.getStats()),Promise.all(t).then(lr).then(sr)}function dr(e){let t=e.filter(ir(`type`,`candidate-pair`)).sort(ar(`priority`)).find(rr(ir(`nominated`,!0),ir(`selected`,!0)));if(!t)return{timestamp:0,availableOutgoingBitrate:0,totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let n={timestamp:t.timestamp,availableOutgoingBitrate:t.availableOutgoingBitrate||0,totalRoundTripTime:t.totalRoundTripTime||0,currentRoundTripTime:t.currentRoundTripTime||0,bytesSent:t.bytesSent||0,bytesReceived:t.bytesReceived||0},r=e.find(ir(`id`,t.remoteCandidateId));r&&Object.assign(n,{remote:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol}});let i=e.find(ir(`id`,t.localCandidateId));return i&&Object.assign(n,{local:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol,relayProtocol:i.relayProtocol,networkType:i.networkType}}),cr(n)}function fr(e,t,n=!1){let r=or(`id`,e);return(n?e.filter(rr(ir(`type`,`remote-inbound-rtp`))):e.filter(rr(ir(`type`,`inbound-rtp`),ir(`type`,`outbound-rtp`)))).map(e=>{let n=Number(e.ssrc),i=e.mediaType||e.kind,a=e.remoteId||e.trackId,o=e.type,s=e.codecId;if(!o||!n||!i)return null;let c={ssrc:n,type:o,kind:i,bytesReceived:U(e,`bytesReceived`),bytesSent:U(e,`bytesSent`),headerBytesReceived:U(e,`headerBytesReceived`),headerBytesSent:U(e,`headerBytesSent`),jitter:U(e,`jitter`),packetsLost:U(e,`packetsLost`),packetsReceived:U(e,`packetsReceived`),packetsSent:U(e,`packetsSent`),fractionLost:U(e,`fractionLost`),pliCount:U(e,`pliCount`),firCount:U(e,`firCount`),nackCount:U(e,`nackCount`),userId:t[n],freezeCount:U(e,`freezeCount`,0),totalFreezesDuration:U(e,`totalFreezesDuration`,0)},l=`mid`in e&&typeof e.mid==`string`?e.mid:void 0,u=`rid`in e&&typeof e.rid==`string`?e.rid:void 0;if(l&&(c.mid=l),u&&(c.rid=u),i===`video`){let t=U(e,`framesDecoded`),n=U(e,`totalInterFrameDelay`),r=U(e,`totalSquaredInterFrameDelay`),i=U(e,`encoderImplementation`),a=U(e,`decoderImplementation`);i&&(c.encoderImplementation=i),a&&(c.decoderImplementation=a),c.interframeDelayVariance=(r-n*n/t)/t}if(i===`video`&&c.type===`outbound-rtp`&&(c.totalEncodeTime=U(e,`totalEncodeTime`)??0),i===`audio`&&(c.totalSamplesReceived=U(e,`totalSamplesReceived`),c.concealedSamples=U(e,`concealedSamples`),c.insertedSamplesForDeceleration=U(e,`insertedSamplesForDeceleration`),c.removedSamplesForAcceleration=U(e,`removedSamplesForAcceleration`),c.silentConcealedSamples=U(e,`silentConcealedSamples`),c.concealmentEvents=U(e,`concealmentEvents`),c.totalAudioEnergy=U(e,`totalAudioEnergy`)),s&&r[s]){let e=r[s];c.clockRate=e.clockRate,c.mimeType=e.mimeType,i===`audio`&&e.sdpFmtpLine&&(c.sdpFmtpLine=e.sdpFmtpLine)}if(a&&r[a]){let e=r[a];c.frameHeight=e.frameHeight,c.frameWidth=e.frameWidth,c.framesDecoded=e.framesDecoded,c.framesReceived=e.framesReceived,c.framesDropped=e.framesDropped}return cr(c)}).filter(e=>!!e)}function pr(e,t,n=!1){if(!t||!t.rtps.length||!e.rtps.length)return e;let r,i;n&&(r=or(`ssrc`,e?.remoteRtps||[]),i=or(`ssrc`,t?.remoteRtps||[]));let a=or(`ssrc`,e.rtps),o=or(`ssrc`,t.rtps),s=(e.timestamp-t.timestamp)/1e3;return!a||!o||Object.keys(a).forEach(c=>{let l=a[c],u=o[c];if(!(!l||!u)){if(l.bytesReceived&&l.bytesReceived>u.bytesReceived&&(l.bandwidth=Math.round((l.bytesReceived-u.bytesReceived)/s),l.bandwidth+=Math.round((l.headerBytesReceived-u.headerBytesReceived)/s)),l.bytesSent&&l.bytesSent>u.bytesSent&&(l.bandwidth=Math.round((l.bytesSent-u.bytesSent)/s),l.bandwidth+=Math.round((l.headerBytesSent-u.headerBytesSent)/s)),l.packetsReceived)if(l.packetsReceived>u.packetsReceived||l.packetsLost>u.packetsLost){let e=l.packetsLost-u.packetsLost,t=l.packetsReceived-u.packetsReceived;l.packetLoss=parseFloat((100*e/(e+t)).toFixed(2))}else l.packetLoss=0;if(l.freezeCount>u.freezeCount&&(l.freezeCountDelta=l.freezeCount-u.freezeCount),l.totalFreezesDuration>u.totalFreezesDuration&&(l.totalFreezesDurationDelta=l.totalFreezesDuration-u.totalFreezesDuration),l.framesDropped&&u.framesDropped&&l.framesDropped>u.framesDropped&&(l.framesDroppedDelta=parseFloat(((l.framesDropped-u.framesDropped)/s).toFixed(0))),n&&l.type===`outbound-rtp`&&l.kind===k.video){let n=r?.[c],a=i?.[c],o=e=>e??0,s=Math.max(0,o(n?.packetsLost)-o(a?.packetsLost)),d=Math.max(1,l.packetsSent-u.packetsSent);e.transport.averageNetStat={currentRoundTripTime:(e.transport.currentRoundTripTime+t.transport.currentRoundTripTime)/2*1e3,lostPercent:Math.round(s/d*100)}}}}),e}async function mr(e,t,n={},r=!1){let i=await ur(e),a={timestamp:Date.now(),transport:dr(i),rtps:fr(i,n)};return r&&(a.remoteRtps=fr(i,n,!0)),t?pr(a,t,r):(await j.delay(nr),mr(e,a,n,r))}function hr(e){performance.clearMarks(e),performance.mark(e)}function gr(e){performance.clearMarks(e)}function _r(e){let t=performance.getEntriesByName(e)[0];if(t===void 0)return null;let n=Math.round(performance.now()-t.startTime);return performance.clearMarks(e),n}function vr(e){return`${H.SCREENSHARE_FIRST_FRAME}_${yr(e)}`}function yr(e){return typeof e==`string`?e:JSON.stringify(e)}var W={distinctById:sr,rtcStatsToArray:lr,extractTransport:dr,extractRtps:fr,delta:pr,collectStats:mr,setMark:hr,clearMark:gr,measureMark:_r,getMarkNameScreenshareFirstFrame:vr},br=function(e){return e.START=`start`,e.ACCEPT=`accept`,e.JOIN=`join`,e.RETRY=`retry`,e}(br||{}),G=function(e){return e.NOTIFICATION=`NOTIFICATION`,e.FAILED=`FAILED`,e.RECONNECT=`RECONNECT`,e}(G||{}),K=function(e){return e.TRANSMITTED_DATA=`transmitted-data`,e.ACCEPTED_CALL=`accepted-call`,e.HUNGUP=`hungup`,e.PARTICIPANT_ADDED=`participant-added`,e.PARTICIPANT_JOINED=`participant-joined`,e.CLOSED_CONVERSATION=`closed-conversation`,e.MEDIA_SETTINGS_CHANGED=`media-settings-changed`,e.PARTICIPANT_STATE_CHANGED=`participant-state-changed`,e.PARTICIPANTS_STATE_CHANGED=`participants-state-changed`,e.RATE_CALL_DATA=`rate-call-data`,e.FEATURE_SET_CHANGED=`feature-set-changed`,e.TOPOLOGY_CHANGED=`topology-changed`,e.PRODUCER_UPDATED=`producer-updated`,e.CONSUMER_ANSWERED=`consumer-answered`,e.MULTIPARTY_CHAT_CREATED=`multiparty-chat-created`,e.FORCE_MEDIA_SETTINGS_CHANGE=`force-media-settings-change`,e.SETTINGS_UPDATE=`settings-update`,e.VIDEO_QUALITY_UPDATE=`video-quality-update`,e.REGISTERED_PEER=`registered-peer`,e.SWITCH_MICRO=`switch-micro`,e.RECORD_STARTED=`record-started`,e.RECORD_STOPPED=`record-stopped`,e.REALLOC_CON=`realloc-con`,e.AUDIO_ACTIVITY=`audio-activity`,e.SPEAKER_CHANGED=`speaker-changed`,e.SESSION_STATE=`session-state`,e.STALLED_ACTIVITY=`stalled-activity`,e.CHAT_MESSAGE=`chat-message`,e.CUSTOM_DATA=`custom-data`,e.ROLES_CHANGED=`roles-changed`,e.MUTE_PARTICIPANT=`mute-participant`,e.PIN_PARTICIPANT=`pin-participant`,e.OPTIONS_CHANGED=`options-changed`,e.NETWORK_STATUS=`network-status`,e.PARTICIPANT_SOURCES_UPDATE=`participant-sources-update`,e.PROMOTE_PARTICIPANT=`promote-participant`,e.CHAT_ROOM_UPDATED=`chat-room-updated`,e.PROMOTION_APPROVED=`promotion-approved`,e.JOIN_LINK_CHANGED=`join-link-changed`,e.FEEDBACK=`feedback`,e.MOVIE_UPDATE_NOTIFICATION=`movie-update-notification`,e.MOVIE_SHARE_STARTED=`movie-share-started`,e.MOVIE_SHARE_STOPPED=`movie-share-stopped`,e.URL_SHARING_INFO_UPDATED=`url-sharing-info-updated`,e.ROOM_UPDATED=`room-updated`,e.ROOMS_UPDATED=`rooms-updated`,e.ROOM_PARTICIPANTS_UPDATED=`room-participants-updated`,e.FEATURES_PER_ROLE_CHANGED=`features-per-role-changed`,e.PARTICIPANT_ANIMOJI_CHANGED=`participant-animoji-changed`,e.ASR_STARTED=`asr-started`,e.ASR_STOPPED=`asr-stopped`,e.DECORATIVE_PARTICIPANT_ID_CHANGED=`decorative-participant-id-changed`,e.VIDEO_SUSPEND_SUGGEST=`video-suspend-suggest`,e.HOLD=`hold`,e}(K||{}),xr=function(e){return e.WEBSOCKET=`ws`,e.WEBTRANSPORT=`wt`,e}({}),Sr=function(e){return e.CONNECTED=`connected`,e.RECONNECTED=`reconnected`,e.FAILED_PINGS=`failed_pings`,e.FAILED_EXCEPTIONS=`failed_exception`,e.TIMEOUT=`timeout`,e.RESTART=`restart`,e}({}),Cr={connected:{wt:H.WEBTRANSPORT_CONNECTED,ws:H.WEBSOCKET_CONNECTED},reconnected:{wt:H.WEBTRANSPORT_RECONNECTED,ws:H.WEBSOCKET_RECONNECTED},failed_pings:{wt:H.WEBTRANSPORT_FAILED_PINGS,ws:H.WEBSOCKET_FAILED_PINGS},failed_exception:{wt:H.WEBTRANSPORT_FAILED_EXCEPTION,ws:H.WEBSOCKET_FAILED_EXCEPTION},timeout:{wt:H.WEBTRANSPORT_TIMEOUT,ws:H.WEBSOCKET_TIMEOUT},restart:{wt:H.WEBTRANSPORT_RESTART,ws:H.WEBSOCKET_RESTART}},q=function(e){return e.IDLE=`IDLE`,e.OPENED=`OPENED`,e.CONNECTING=`CONNECTING`,e.RECONNECTING=`RECONNECTING`,e.CONNECTED=`CONNECTED`,e.CLOSED=`CLOSED`,e.FAILED=`FAILED`,e}(q||{}),J=function(e){return e.DIRECT=`DIRECT`,e.SERVER=`SERVER`,e}(J||{}),wr=function(e){return e.producerNotification=`producerNotification`,e.producerCommand=`producerCommand`,e.consumerScreenShare=`consumerScreenShare`,e.producerScreenShare=`producerScreenShare`,e.asr=`asr`,e.animoji=`animoji`,e}(wr||{}),{isObject:Tr,isObjectsEquals:Er}=j;function Dr(e,t){return e===null||t===null?e===null&&t===null:e.maxDimension!==t.maxDimension||e.maxBitrateK!==t.maxBitrateK||e.maxFramerate!==t.maxFramerate||e.degradationPreference!==t.degradationPreference||e.scalabilityMode!==t.scalabilityMode||Tr(e.bitrates)&&Tr(t.bitrates)&&!Er(e.bitrates,t.bitrates,!0)?!1:e.bitrates===t.bitrates}var Or=function(e){return e.L1T1=`L1T1`,e.L1T2=`L1T2`,e.L1T3=`L1T3`,e}({});function kr(e,t){return!(!Dr(e.camera,t.camera)||!Dr(e.screenSharing,t.screenSharing)||!Dr(e.fastScreenSharing,t.fastScreenSharing))}function Ar(e,t){return{camera:Object.assign({},e.camera,t.camera),screenSharing:Object.assign({},e.screenSharing,t.screenSharing),fastScreenSharing:Object.assign({},e.fastScreenSharing,t.fastScreenSharing)}}function jr(){return{camera:null,screenSharing:null,fastScreenSharing:null}}var Mr=200;function Nr(e){for(let t of e.values())if(t.type===`outbound-rtp`&&(t.packetsSent??0)>0)return!0;return!1}var Pr=class{constructor(e,t,n=Mr){h(this,`_peerConnection`,void 0),h(this,`_onFirstMediaSent`,void 0),h(this,`_pollIntervalMs`,void 0),h(this,`_timer`,null),h(this,`_state`,`idle`),this._peerConnection=e,this._onFirstMediaSent=t,this._pollIntervalMs=n}start(){this._state===`idle`&&(this._state=`polling`,this._poll())}destroy(){this._state!==`stopped`&&(this._state=`stopped`,this._timer!==null&&(clearTimeout(this._timer),this._timer=null))}async _getStatsReports(){return(await Promise.all(this._peerConnection.getSenders().map(async e=>{try{return await e.getStats()}catch{return null}}))).filter(e=>e!==null)}async _poll(){if(this._state===`polling`){try{let e=await this._getStatsReports();if(this._state!==`polling`)return;if(e.some(Nr)){this._state=`stopped`,this._onFirstMediaSent();return}}catch{}this._scheduleNextPoll()}}_scheduleNextPoll(){this._state===`polling`&&(this._timer=setTimeout(()=>{this._timer=null,this._poll()},this._pollIntervalMs))}},Fr=class extends b{constructor(e,t,n=null){super(),h(this,`_signaling`,void 0),h(this,`_mediaSource`,void 0),h(this,`_state`,q.IDLE),h(this,`_pc`,null),h(this,`_onFirstMediaSent`,void 0),h(this,`_firstMediaSentProbe`,null),h(this,`_firstMediaSentProbeStopped`,!1),this._signaling=e,this._mediaSource=t,this._onFirstMediaSent=n}getState(){return this._state||q.IDLE}stopFirstMediaSentProbe(){this._firstMediaSentProbeStopped=!0,this._disposeFirstMediaSentProbe()}_startFirstMediaSentProbe(){this._disposeFirstMediaSentProbe(),!(!this._pc||!this._onFirstMediaSent||this._firstMediaSentProbeStopped)&&(this._firstMediaSentProbe=new Pr(this._pc,this._onFirstMediaSent),this._firstMediaSentProbe.start())}_disposeFirstMediaSentProbe(){this._firstMediaSentProbe?.destroy(),this._firstMediaSentProbe=null}},Ir=class{constructor(e,t=null){h(this,`weightUp`,void 0),h(this,`weightDown`,void 0),h(this,`value`,NaN),this.weightUp=e,this.weightDown=t??e}set(e){this.value=e}update(e){return this.value=Number.parseFloat(this.getNext(e).toFixed(3)),this.value}getNext(e){if(isNaN(this.value))return e;let t=e<this.value?this.weightDown:this.weightUp;return this.value*(1-t)+e*t}getValue(){return this.value}},Lr=.25,Rr=.35,zr=85,Br=.1,Vr=1.5,Hr=.1,Ur=1,Wr=.6,Gr=.3,Kr=class extends b{constructor(e,t=R){super(),h(this,`_signaling`,void 0),h(this,`_localNetworkStat`,void 0),h(this,`_remoteNetworkStat`,void 0),h(this,`_lastNetworkStat`,void 0),h(this,`_networkLimits`,{badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}}),h(this,`_lastStatSentTimestamp`,0),h(this,`_currentState`,`good`),h(this,`_debug`,void 0),this._debug=t,this._signaling=e,this._localNetworkStat={rtt:new Ir(Lr,Lr),loss:new Ir(Rr,Rr),bitrate:0},this._remoteNetworkStat={rtt:0,loss:0,bitrate:0},this._lastNetworkStat={rtt:0,loss:0,date:0}}_calcRttRating(e){let t=typeof e==`number`?e:e.getValue(),n=1;if(isNaN(t))return n;let r=Math.round((t-this._networkLimits.goodNet.rtt)/zr);for(let e=0;e<r;e++)n*=1-Br;return n}_calcLossRating(e){let t=typeof e==`number`?e:e.getValue(),n=1;if(isNaN(t))return n;let r=Math.round((t-this._networkLimits.goodNet.loss)/Vr);for(let e=0;e<r;e++)n*=1-Hr;return n}_calcBitrateRating(e,t){if(!e||!t)return 1;let n=1-(1-Math.min(e,t)/Math.max(e,t))*Ur;return Math.min(n,1)}_calcUDPRating({rtt:e,loss:t}){return this._calcRttRating(e)*this._calcLossRating(t)}_calcRating(e,t,n){return n?this._calcBitrateRating(e.bitrate,t.bitrate):this._calcUDPRating(e)*this._calcUDPRating(t)}_getNetworkState(e){return isNaN(e)||e>=Wr?`good`:e>=Gr?`medium`:`bad`}updateSettings(e){Object.assign(this._networkLimits.badNet,e?.badNet||{}),Object.assign(this._networkLimits.goodNet,e?.goodNet||{})}reportLocal(e){if(!this._signaling.ready)return;let t=e.outbound.transport.local?.protocol===`tcp`,n=Math.max(0,Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0),r=e.inbound.rtps.reduce((e,t)=>Math.max(e,t.packetLoss||0),0),i={rtt:this._localNetworkStat.rtt.update(n),loss:this._localNetworkStat.loss.update(r)};if(t){let t=e.outbound.rtps.reduce((e,t)=>e+(t.bandwidth??0)*8,0);i.bitrate=t,this._localNetworkStat.bitrate=t}let a=Date.now(),o=this._calcRating(this._localNetworkStat,this._remoteNetworkStat,t),s=Math.max(Math.round(o*10)/10,.1),c=this._getNetworkState(s);(t||c!==this._currentState||a-this._lastStatSentTimestamp>M.networkStatisticsInterval)&&(this._lastStatSentTimestamp=a,this._signaling.customData({sdk:Object.assign({type:`bad-net`},i)},null).catch(e=>{this._debug.warn(`Unable to send [bad-net]`,e)})),this._currentState=c,this._triggerEvent(Y.NETWORK_STATUS,s)}reportRemote(e){let{rtt:t,loss:n,bitrate:r}=e||{};this._remoteNetworkStat.rtt=t||0,this._remoteNetworkStat.loss=n||0,this._remoteNetworkStat.bitrate=r||0}},qr=30*1e3,Jr=class e extends Fr{constructor(e,t,n,r,i,a=R,o=null,s=null,c=null,l=null){super(n,r,l),h(this,`_participantId`,void 0),h(this,`_isMaster`,void 0),h(this,`_remoteSDP`,{}),h(this,`_remoteCandidates`,{}),h(this,`_lastRemoteSDP`,null),h(this,`_animojiDataChannel`,null),h(this,`_animojiReceiver`,null),h(this,`_animojiSender`,null),h(this,`_remoteAnimojiVersion`,1),h(this,`_isOpen`,!1),h(this,`_remotePeerId`,null),h(this,`_statInterval`,null),h(this,`_settingsInterval`,null),h(this,`_failedOnCreate`,null),h(this,`_remoteStream`,null),h(this,`_iceRestartTimeout`,null),h(this,`_reconnectionTimeout`,null),h(this,`_reconnectionPrevented`,!1),h(this,`_remoteHold`,!1),h(this,`_lastStat`,null),h(this,`_fingerprint`,null),h(this,`_neverConnected`,!0),h(this,`_serverSettings`,void 0),h(this,`_prevConsumerSettings`,{}),h(this,`_networkLimitsForVideo`,{bad:{loss:4,rtt:1e3},good:{loss:2,rtt:700}}),h(this,`_videoMaxDimensionsForNet`,{worst:320,bad:640,good:1280}),h(this,`_lastVideoMaxDimension`,this._videoMaxDimensionsForNet.good),h(this,`_lastBadConnection`,0),h(this,`_perfStatReporter`,void 0),h(this,`_directStatReporter`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_statAggregator`,void 0),h(this,`_codecStatsAggregator`,void 0),this._participantId=e,this._isMaster=t,this._serverSettings=i,this._debug=a,this._logger=o,this._statAggregator=s,this._codecStatsAggregator=c,this._perfStatReporter=new ga(this,n,this._statAggregator,!0,this._debug),this._directStatReporter=new Kr(n,this._debug),this.subscribe(this._signaling,G.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Yt.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Yt.SOURCE_CHANGED,this._applySettings.bind(this)),this.subscribe(this._directStatReporter,Y.NETWORK_STATUS,this._onNetworkStatus.bind(this));try{this._pc=this._createPeerConnection()}catch(e){this._debug.error(`Failed to create RTCPeerConnection:`,e),this._failedOnCreate=e;return}if(this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(e){this._logger?.log(C.ERROR,`addTrack-direct`),this._debug.error(`Unable to add media source tracks`,e,{participantId:this._participantId}),this._failedOnCreate=e;return}this._createOffer(!1).catch(e=>{this._state===q.IDLE?this._failedOnCreate=e:this.close(e)})}this._startSettingsInterval()}get participantId(){return this._participantId}updateStatisticsInterval(){this._stopStatInterval(),this._isDeadConnection()||this._startStatInterval()}_isDeadConnection(){return!this._pc||[q.IDLE,q.CLOSED,q.FAILED].includes(this.getState())}async open(e=null){if(this._isOpen){this._debug.warn(`DirectTransport: Already opened`,{participantId:this._participantId});return}if(this._failedOnCreate){this._finishClose(this._failedOnCreate);return}if(this._debug.debug(`DirectTransport: Open transport`,{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(e){this._logger?.log(C.ERROR,`addTrack-direct`),this._debug.error(`DirectTransport: Unable to add media source tracks`,e,{participantId:this._participantId}),this.close(e);return}this._startFirstMediaSentProbe(),this._setState(q.OPENED);let t=e;if(!e){let e=Object.keys(this._remoteSDP);t=e[e.length-1]}if(t&&this._remoteSDP[t])try{await this._setRemoteDescription(t,this._remoteSDP[t])}catch{this.close();return}this._remoteSDP={},this._remoteCandidates={}}updateSettings(e){kr(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}setRemoteHold(e){if(this._remoteHold!==e){if(this._remoteHold=e,e){this._stopReconnection(),this._stopStatInterval(),this._stopSettingsInterval(),this._isOpen&&(this._disposePeerConnection(),this._remoteSDP={},this._remoteCandidates={},this._lastRemoteSDP=null);return}this._isOpen&&this._recreatePeerConnection()}}_recreatePeerConnection(){this._debug.log(`Recreating peer connection after remote unhold`,{participantId:this._participantId});try{this._pc=this._createPeerConnection()}catch(e){this._debug.error(`Failed to recreate RTCPeerConnection:`,e),this.close(e);return}this._neverConnected=!0;try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(e){this._debug.error(`Unable to add media source tracks after unhold`,e,{participantId:this._participantId});return}this._startFirstMediaSentProbe(),this._startSettingsInterval(),this._isMaster&&this._createOffer(!1).catch(e=>{this._debug.error(`Unable to create offer after unhold`,e,{participantId:this._participantId})}),this._setState(q.CONNECTING)}_createPeerConnection(){let e=new RTCPeerConnection({iceServers:M.iceServers,iceTransportPolicy:M.forceRelayPolicy?`relay`:`all`});return e.onicecandidate=this._handleIceCandidate.bind(this),e.ontrack=this._onAddTrack.bind(this),e.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),e.onconnectionstatechange=this._onConnectionStateChange.bind(this),e.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},M.vmoji&&this._createDataChannel(e,wr.animoji,e=>{this._animojiDataChannel=e,this._animojiDataChannel.binaryType=`arraybuffer`,this._animojiReceiver?.setDataChannel(this._animojiDataChannel),this._animojiSender?.setDataChannel(this._animojiDataChannel)}),e}_disposePeerConnection(){if(this._disposeFirstMediaSentProbe(),this._lastStat=null,this._remoteStream){let e=this._remoteStream;e.getTracks().forEach(t=>{t.stop(),this._triggerEvent(Y.REMOTE_TRACK_REMOVED,e,t)}),this._remoteStream=null}this._animojiDataChannel&&(this._animojiDataChannel.onopen=null,this._animojiDataChannel.onmessage=null,this._animojiDataChannel.onerror=null,this._animojiDataChannel.close(),this._animojiDataChannel=null),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._pc=null)}setAnimojiTransport(e,t){if(M.vmoji&&(this._animojiReceiver=e,this._animojiSender=t,e.setParticipantId(this._participantId),this._animojiDataChannel)){e.setDataChannel(this._animojiDataChannel),t.setDataChannel(this._animojiDataChannel);return}}close(e){this._isOpen&&this._finishClose(e)}_finishClose(e){this._isOpen=!1,this._stopReconnection(),this._stopStatInterval(),this._stopSettingsInterval(),this._disposePeerConnection(),this._onNetworkStatus(1),this.unsubscribe(),e?(this._debug.error(`DirectTransport: Closed`,e,{participantId:this._participantId}),this._setState(q.FAILED)):(this._debug.debug(`DirectTransport: Closed`,{participantId:this._participantId}),this._setState(q.CLOSED)),this._triggerEvent(Y.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(this._debug.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(Y.STATE_CHANGED,e))}_onSignalingNotification(e){switch(e.notification){case K.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case K.SETTINGS_UPDATE:this._directStatReporter.updateSettings(e.settings);break;case K.CUSTOM_DATA:Object.hasOwn(e.data,`sdk`)&&this._directStatReporter.reportRemote(e.data?.sdk);break}}_handleTransmittedData(e){let t=e.data,n=j.getPeerIdString(e.peerId);j.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(n,t.candidate).catch(this.close.bind(this)):t.sdp&&(this._remoteAnimojiVersion=t.animojiVersion||1,this._setRemoteDescription(n,t.sdp).catch(this.close.bind(this))))}async _addIceCandidate(e,t){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){this._debug.debug(`Add remote ice candidate`,{participantId:this._participantId,candidate:t});try{await this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(e){throw this._logger?.log(C.ERROR,`addIceCandidate-direct`),this._debug.error(`Unable to add remote ice candidate`,e,{participantId:this._participantId,candidate:t}),e}}else this._debug.debug(`Cache remote ice candidate`,{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)}async _setRemoteCandidates(e){if(!this._remoteCandidates[e]){this._debug.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let n of t)try{await this._addIceCandidate(e,n)}catch{}}async _setRemoteDescription(t,n){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===t)&&this._pc){if(this._lastRemoteSDP?.sdp===n.sdp)return;this._lastRemoteSDP=n,n=e._patchRemoteDescription(n),this._debug.debug(`Add remote description`,{participantId:this._participantId,sdp:n}),this._calcFingerprint(n.sdp);try{await this._pc.setRemoteDescription(n),await this._setRemoteCandidates(t),this._processAnimojiProtocolVersion(this._remoteAnimojiVersion)}catch(e){throw this._logger?.log(C.ERROR,`setRemoteDescription-direct`),this._debug.error(`Unable to set remote description`,e,{participantId:this._participantId,sdp:n}),e}}else this._remoteSDP[t]=n}_processAnimojiProtocolVersion(e){let t=Math.min(e,M.vmojiOptions?.protocolVersion||1);this._animojiSender?.setProtocolVersion(t)}_onAddTrack(e){this._debug.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=e=>{this._triggerEvent(Y.REMOTE_TRACK_REMOVED,this._remoteStream,e.track)}),this._triggerEvent(Y.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}async _handleIceCandidate(e){this._signaling.ready&&(e.candidate?(this._debug.debug(`Local ice candidate`,{participantId:this._participantId,candidate:e.candidate}),await this._signaling.sendCandidate(this._participantId,e.candidate)):M.forwardEmptyIceCandidate&&(this._debug.debug(`ICE gathering complete, forwarding empty candidate`,{participantId:this._participantId}),await this._signaling.sendCandidate(this._participantId,{candidate:``})))}_onSignalingStateChange(){this._debug.debug(`DirectTransport: Signaling state changed to ${this._pc?.signalingState}`,{participantId:this._participantId});let e={animojiVersion:M.vmojiOptions.protocolVersion||1};switch(this._pc?.signalingState){case`have-local-offer`:let t=this._pc.localDescription;t?this._signaling.sendSdp(this._participantId,t,e).catch(this.close.bind(this)):this.close(Error());break;case`have-remote-offer`:this._createAnswer().then(t=>this._signaling.sendSdp(this._participantId,t,e)).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(this._debug.debug(`DirectTransport: Ice Connection state changed to ${this._pc?.iceConnectionState}`,{participantId:this._participantId}),this._pc?.iceConnectionState){case`checking`:{let e=this.getState();e===q.IDLE||e===q.OPENED?this._setState(q.CONNECTING):this._setState(q.RECONNECTING);break}case`connected`:case`completed`:this._pc?.connectionState!==`connected`&&(this._debug.warn(`DirectTransport: marking connected via iceConnectionState fallback`,{participantId:this._participantId,connectionState:this._pc?.connectionState,iceConnectionState:this._pc?.iceConnectionState}),this._logger?.log(C.ERROR,`iceConnectionState-fallback`),this._markConnected());break}}_markConnected(){this._neverConnected=!1,this._setState(q.CONNECTED),this._stopReconnection(),this._pc&&j.getPeerConnectionHostInfo(this._pc).then(e=>{e?.local&&(this._logger?.log(C.ICE_CONNECTION_TYPE,e.local.type),this._debug.debug(`Selected ICE candidates`,e))}),this._startStatInterval()}_onConnectionStateChange(){switch(this._debug.debug(`DirectTransport: Connection state changed to ${this._pc?.connectionState}`,{participantId:this._participantId}),this._logger?.log(C.ICE_CONNECTION_STATE,this._pc?.connectionState),this._pc?.connectionState){case`connected`:this._markConnected();break;case`failed`:case`disconnected`:this._remoteHold?this._debug.log(`Remote participant on hold, skipping reconnection`,{participantId:this._participantId}):this._reconnectionPrevented?this.close(Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(q.RECONNECTING),this._startReconnection());break;case`closed`:this._remoteHold||this.close(Error(`Ice connection closed`));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(this._debug.log(`Waiting for reconnection...`,{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},M.transportConnectionWaitTime))}_requestTopologySwitch(e=!1){(this._isMaster||e)&&this._signaling.ready&&(this._debug.log(`Switch topology DIRECT to SERVER`,{participantId:this._participantId}),this._signaling.switchTopology(J.SERVER).catch(e=>{e instanceof En||this._debug.warn(`Unable to switch topology DIRECT to SERVER`,e)}))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(this._logger?.log(C.ICE_RESTART),this._debug.log(`Ice restart`,{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):this._debug.debug(`Waiting for ice restart...`,{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,this._debug.error(`Ice restart failed`,{participantId:this._participantId}),this._logger?.log(C.ERROR,`iceRestart-direct`),this._requestTopologySwitch(M.switchTopologyOnReconnectFromAnySide)},M.iceRestartWaitTime)}async _createOffer(t){let n={iceRestart:t,offerToReceiveAudio:!0,offerToReceiveVideo:!0};this._debug.debug(`Create offer`,{participantId:this._participantId,options:n});let r;try{r=await this._pc?.createOffer(n),this._debug.debug(`Created offer`,{participantId:this._participantId,offer:r}),r=e._patchLocalDescription(r)}catch(e){throw this._debug.error(`Unable to create offer`,e,{participantId:this._participantId}),this._logger?.log(C.ERROR,`createOffer-direct`),e}try{return this._debug.debug(`Set local description`,{participantId:this._participantId,offer:r}),this._calcFingerprint(r.sdp),await this._pc?.setLocalDescription(r),r}catch(e){throw this._debug.error(`Unable to set local description`,e,{participantId:this._participantId}),this._logger?.log(C.ERROR,`setLocalDescription-direct`),e}}async _createAnswer(){this._debug.debug(`Create answer`,{participantId:this._participantId});let t;try{t=await this._pc?.createAnswer(),this._debug.debug(`Created answer`,{participantId:this._participantId,answer:t}),t=e._patchLocalDescription(t)}catch(e){throw this._debug.error(`Unable to create answer`,e,{participantId:this._participantId}),this._logger?.log(C.ERROR,`createAnswer-direct`),e}try{return this._debug.debug(`Set local description`,{participantId:this._participantId,answer:t}),this._calcFingerprint(t.sdp),await this._pc?.setLocalDescription(t),t}catch(e){throw this._debug.error(`Unable to set local description`,e,{participantId:this._participantId}),this._logger?.log(C.ERROR,`setLocalDescription-direct`),e}}static _patchLocalDescription(e){let t=!!T.baseChromeVersion();return e.sdp=j.patchLocalSDP(e.sdp,M.preferH264&&T.canPreferH264(),T.isBrokenH264Decoder(),M.preferVP9,t&&M.audioNack),e}static _patchRemoteDescription(e){return e.sdp=j.patchRemoteSDP(e.sdp,!1,!1,M.preferVP9,T.isBrokenVP9Encoder(),T.isBrokenVP9Decoder()),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&t.track.contentHint===e.contentHint&&t.replaceTrack(e).catch(e=>{this._debug.error(`DirectTransport: Unable to replace track`,e,{participantId:this._participantId}),this._logger?.log(C.ERROR,`replaceTrack-direct`)})}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(this._isDeadConnection()){this._stopStatInterval();return}W.collectStats(this._pc,this._lastStat,void 0,!0).then(t=>{this._lastStat=t,this._codecStatsAggregator?.reportUsage(t);let n={inbound:{topology:J.DIRECT,transport:t.transport,rtps:t.rtps.filter(e=>e.type===`inbound-rtp`?(e.userId=this._participantId,!0):!1)},outbound:{topology:J.DIRECT,transport:t.transport,rtps:t.rtps.filter(e=>e.type===`outbound-rtp`)},remoteInbound:{topology:J.DIRECT,transport:t.transport,rtps:t.remoteRtps??[]}};this._checkPPTNetwork(n),this._directStatReporter.reportLocal(n),this._triggerEvent(Y.REMOTE_DATA_STATS,n),this._statInterval=window.setTimeout(e,M.statisticsInterval)})};this._statInterval=window.setTimeout(e,M.statisticsInterval)}async _isSVCSupported(e,t){let n=this._mediaSource.getSendVideoTrack(),r=e.outbound.rtps.find(e=>e.kind===`video`);if(!r?.mimeType||!r?.bandwidth||!n)return!1;let i=n.getSettings();if(!i.width||!i.height||!i.frameRate)return!1;let a={type:`webrtc`,video:{contentType:r.mimeType,width:i.width,height:i.height,bitrate:r.bandwidth,framerate:i.frameRate,scalabilityMode:t}};try{return(await navigator.mediaCapabilities.encodingInfo(a)).supported||!1}catch(e){return this._debug.warn(`Failed to get encodingInfo`,a,e),!1}}async _checkPPTNetwork(e){if(!M.switchVideoAtBadNetwork||!e.inbound.transport.averageNetStat)return;let{averageNetStat:t}=e.inbound.transport,n=t.currentRoundTripTime<=this._networkLimitsForVideo.good.rtt&&t.lostPercent<=this._networkLimitsForVideo.good.loss,r=t.currentRoundTripTime>=this._networkLimitsForVideo.bad.rtt||t.lostPercent>=this._networkLimitsForVideo.bad.loss,i=t.currentRoundTripTime<this._networkLimitsForVideo.bad.rtt,a=this._videoMaxDimensionsForNet.good,o=Or.L1T1;if(r?(this._lastBadConnection=Date.now(),i?(a=this._videoMaxDimensionsForNet.bad,o=Or.L1T2):(a=this._videoMaxDimensionsForNet.worst,o=Or.L1T3)):n&&(a=this._videoMaxDimensionsForNet.good,o=Or.L1T1),!(a<this._lastVideoMaxDimension||Date.now()-this._lastBadConnection>qr)||this._lastVideoMaxDimension===a)return;let s=this._serverSettings.camera;if(!s||!await this._isSVCSupported(e,o))return;this._debug.debug(`Switch outbound video frame size and scalabilityMode`,{scalabilityMode:o,averageNetStat:t,nextVideoMaxDimension:a}),this._lastVideoMaxDimension=a;let c={...this._serverSettings,camera:{...s,scalabilityMode:o,maxDimension:this._lastVideoMaxDimension}};this.updateSettings(c)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_onNetworkStatus(e){let t={};t[this._participantId]=t[``]=e,this._triggerEvent(Y.NETWORK_STATUS,t)}_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=j.sdpFingerprint(e);if(t===null){this._debug.warn(`Fingerprint calculation is unsupported`);return}this._fingerprint===null?this._fingerprint=t:(L.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){let e=this._mediaSource.mediaSettings.isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&this._pc?.connectionState===`connected`&&(this._prevConsumerSettings=j.applySettings(this._pc,e,this._prevConsumerSettings,this._debug))}_createDataChannel(e,t,n){this._debug.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{negotiated:!0,id:1});r.onopen=()=>{let e=r.readyState;e===`open`?(this._debug.debug(`[${t}] data channel opened`),r.onerror=e=>{this._debug.error(`[${t}] data channel error`,e)},n(r)):this._debug.error(`[${t}] data channel open failed, state [${e}]`)}}},Yr=function(e){return e.AUDIO_MIX=`audio-mix`,e.PARTICIPANT_AGNOSTIC_TRACK_PREFIX=`pat`,e.TRANSPARENT_AUDIO_TRACK_PREFIX=`ta`,e}({}),Xr=16,Zr=class e{constructor(e,t,n,r=R){h(this,`_datachannel`,void 0),h(this,`_participantIdRegistry`,void 0),h(this,`_asrCallback`,void 0),h(this,`_textDecoder`,void 0),h(this,`_debug`,void 0),this._debug=r,this._debug.debug(`AsrReceiver started`),this._datachannel=e,this._participantIdRegistry=t,this._asrCallback=n,this._textDecoder=new TextDecoder,this._datachannel.onmessage=e=>this._onDataChannelMessage(e.data)}static parse(e){let t=new DataView(e),n=t.getUint8(0),r=t.getUint8(1);if(r!==0)throw Error(`Unsupported message type. Message type: ${r}`);let i=t.getUint16(2),a=t.getUint32(4),o=t.getUint32(8),s=t.getUint32(12);if(n!==1)throw Error(`Unexpected protocol version. Got ${n}, expected 1`);return{sequence:i,ssrc:a,timestamp:o,duration:s,data:e.slice(Xr)}}_onDataChannelMessage(t){let n=e.parse(t),r=this._participantIdRegistry?.getStreamDescription(n.ssrc)?.participantId;if(!r){this._debug.warn(`Participant id for ssrc ${n.ssrc} not found in registry`);return}let i={participantId:r,text:this._textDecoder.decode(n.data),timestamp:n.timestamp,duration:n.duration};this._asrCallback(i)}destroy(){this._datachannel.onmessage=null}},Qr,$r=class{constructor(){h(this,`_value`,1)}get value(){return this._value}set value(e){this._value=e}};Qr=$r,h($r,`_instance`,null),h($r,`getInstance`,()=>(Qr._instance||(Qr._instance=new Qr),Qr._instance));var ei=class{constructor(e=R){h(this,`streamDescriptionByCompactId`,new Map),h(this,`compactIdByStreamDescription`,new Map),h(this,`_debug`,void 0),this._debug=e}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}getCompactId(e){return this.compactIdByStreamDescription.get(e)}handleMessage(e){let t=new Uint8Array(e),n=t[0],r=t.subarray(1);switch(n){case 1:let e=(0,l.decode)(r);return Object.entries(e).forEach(([e,t])=>{let n=Fn(e);this.streamDescriptionByCompactId.set(t,n),this.compactIdByStreamDescription.set(e,t)}),null;case 2:case 4:let t=(0,l.decode)(r),i=[];for(let e of t){let t=this.getStreamDescription(e);t&&i.push(t.participantId)}return n===2?{type:`notification`,notification:K.AUDIO_ACTIVITY,activeParticipants:i}:{type:`notification`,notification:K.STALLED_ACTIVITY,stalledParticipants:i};case 3:let a=(0,l.decode)(r);return{type:`notification`,notification:K.SPEAKER_CHANGED,speaker:this.getStreamDescription(a)?.participantId};case 5:let o=(0,l.decode)(r);return{type:`notification`,notification:K.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:o[0],maxDimension:o[1]},mediaType:this._decodeMediaType(o[2])};case 6:let s=(0,l.decode)(r),c={};for(let[e,t]of Object.entries(s)){let n=this.getStreamDescription(Number(e))?.participantId;n&&(c[n]=t/100)}return{type:`notification`,notification:K.NETWORK_STATUS,statuses:c};case 7:return this._createParticipantSourcesUpdateNotification(r);case 8:{let e=(0,l.decode)(r).map(e=>{let[t,n,r,i,a,o,s]=e;return{participantId:this.getStreamDescription(t)?.participantId,gain:n,pause:r,offset:i,mute:a,liveStatus:o,startTimeMs:s}});return{type:`notification`,notification:K.MOVIE_UPDATE_NOTIFICATION,data:e}}case 9:let u=(0,l.decode)(r);return{type:`notification`,notification:K.VIDEO_SUSPEND_SUGGEST,bandwidth:u};default:return this._debug.debug(`unsupported message type: `+n),null}}_decodeMediaType(e){if(e===null)return null;switch(e){case 0:return V.CAMERA;case 1:return V.SCREEN;default:throw Error(`Unsupported media type: ${e}`)}}_createParticipantSourcesUpdateNotification(e){let t=(0,l.decode)(e),n=[];for(let[e,r]of Object.entries(t)){let t=r[0],i=r[1],a=r[2],o=!!r[3],s=r[4]===null?void 0:!!r[4],c;if(t!==null){if(c=this.getStreamDescription(t),!c){this._debug.error(`could not uncompress participant ID ${t}`);continue}}else c=null;if(a===null){this._debug.error(`unexpected null sequenceNumber`,e,r);continue}let l=Yr.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+`-`+e,u=i?i>>>0:null;n.push({participantStreamDescription:c,streamId:l,rtpTimestamp:u,sequenceNumber:a,fastScreenShare:o,suspend:s})}return{type:`notification`,notification:K.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:n}}},ti=function(e){return 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}({}),ni=class{constructor(e=R,t=null){h(this,`_worker`,null),h(this,`_debug`,void 0),h(this,`_logger`,void 0),this._debug=e,this._logger=t}async _createWorker(e,t,n=[],r={},i=[]){return new Promise((a,o)=>{let s=!1,c=!1,l=n.join(`,`),u=new Blob([e,`exports.default(${l});`],{type:`application/javascript; charset=utf-8`}),d=window.URL.createObjectURL(u),f=new Worker(d);window.URL.revokeObjectURL(d),this._worker=f;let p=e=>{c||(c=!0,o(e))},m=e=>{if(this._debug.warn(e),!s){p(e);return}t({type:ti.FRAME,error:e})};f.onerror=e=>{e.preventDefault?.(),m(this._formatWorkerError(e))},f.onmessageerror=e=>{e.preventDefault?.(),m(this._formatWorkerMessageError(e))},f.onmessage=e=>{switch(e.data.type){case ti.READY:s=!0,c||(c=!0,a());break;case ti.ERROR:s?m(e.data.error):p(e.data.error);break;case ti.FRAME:t(e.data);break;case ti.DEBUG:this._debug.debug(e.data.message);break;case ti.LOG_ERROR:this._logger?.log(C.ERROR,e.data.message);break}},this._sendToWorker(ti.INIT,r,i)})}_removeWorker(){this._worker?.terminate(),this._worker=null}_sendToWorker(e,t={},n=[]){this._worker?.postMessage(Object.assign({type:e},t),n)}_formatWorkerError(e){let t=e.message||e.error?.message||`Unknown worker error`,n=[[e.filename,e.lineno,e.colno].filter(Boolean).join(`:`),[e.error?.name,e.error?.stack].filter(Boolean).join(`: `)].filter(Boolean).join(` `);return`${this.constructor.name} Worker crashed: ${t}${n?` (${n})`:``}`}_formatWorkerMessageError(e){return`${this.constructor.name} Worker message error${e.origin?` from ${e.origin}`:``}`}static isBrowserSupported(){throw Error(`Not implemented`)}},ri=class extends ni{constructor(e=R,t=null){super(e,t)}async init(e,t,n){this._debug.debug(`LibVPxDecoder started`),await this._createWorker("var workerExports=(function(){var e=function(e){return 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}({});return(t,n)=>{let r=null,i=null,a=!0,o=!1;function s(){return t({locateFile:n}).then(e=>i=e)}function c(t,n,s,c){if(!i){self.postMessage({type:e.LOG_ERROR,message:`decoder-init-fail-libvpx`}),self.postMessage({type:e.FRAME,error:`Fatal initialization error`});return}if(a!==s&&(a=s,r&&(r=null,self.postMessage({type:e.DEBUG,message:`LibVPxDecoder codec changed to ${s?`VP9`:`VP8`} - reinitialize`}))),!r&&(self.postMessage({type:e.DEBUG,message:`LibVPxDecoder codec ${s?`VP9`:`VP8`}`}),r=new i.VpxDecoder,r.debug(c),!r.init(s?i.VpxType.VP9:i.VpxType.VP8))){r=null,self.postMessage({type:e.FRAME,error:`Decoder failed to create`});return}try{r.allocateBuffer(n.byteLength).set(new Uint8Array(n))}catch(t){self.postMessage({type:e.DEBUG,message:t}),r=null,self.postMessage({type:e.FRAME,error:String(t)});return}if(r.decode()&&r.nextImage())o=!1;else{self.postMessage({type:e.FRAME,error:`Decode failed`}),l();return}let u=r.getImageBuffer();if(!u){self.postMessage({type:e.FRAME,error:`No decoded data`});return}let d=r.getImageWidth(),f=r.getImageHeight();r.nextImage()&&(self.postMessage({type:e.DEBUG,message:`LibVPxDecoder dropped frame`}),self.postMessage({type:e.LOG_ERROR,message:`LibVPxDecoder-drop`}));let p=new Uint8ClampedArray(u.byteLength);p.set(u),self.postMessage({type:e.FRAME,data:p.buffer,width:d,height:f},[p.buffer])}function l(){o||(self.postMessage({type:e.FRAME,requestKeyFrame:!0}),o=!0)}s().then(()=>{self.onmessage=t=>{switch(t.data.type){case e.FRAME:c(t.data.timestamp,t.data.data,t.data.isVP9,t.data.debug);break}},self.postMessage({type:e.READY})}).catch(t=>{self.postMessage({type:e.ERROR,error:String(t)})})}})(),exports={default:workerExports};",r=>{r.error?(this._debug.warn(`LibVPxDecoder`,r.error),t(r.error)):r.requestKeyFrame?(this._debug.debug(`LibVPxDecoder requests key frame`),n()):e(new ImageData(new Uint8ClampedArray(r.data),r.width,r.height))},[u.default,u.default.getUrl])}decodeFrame(e,t,n,r){this._sendToWorker(ti.FRAME,{timestamp:e,data:t.buffer,isVP9:n,keyFrame:r,debug:R.enabled()},[t.buffer])}destroy(){this._removeWorker(),this._debug.debug(`LibVPxDecoder destroyed`)}static isBrowserSupported(){return`WebAssembly`in window&&`Worker`in window}},ii=class extends ni{constructor(e=R,t=null){super(e,t)}async init(e,t,n){this._debug.debug(`WebCodecsDecoder started`),await this._createWorker("var workerExports=(function(){var e=function(e){return e.VP9=`vp09.00.50.08`,e.VP8=`vp8`,e}({}),t=function(e){return 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}({});return n=>{let r=null,i=`no-preference`,a=!0,o=!1,s=!1,c=null,l=null;function u(e){return e instanceof Error?[e.name,e.message,e.stack].filter(Boolean).join(`: `):String(e)}function d(e,n){try{self.postMessage({type:t.FRAME,error:`WebCodecsDecoder ${e} failed: ${u(n)}`})}catch{}}function f(){self.postMessage({type:t.READY})}function p(e,n,r,i=!1){try{c={timestamp:e,data:n,isVP9:r,keyFrame:i};let a=h(r);if(o&&!i){self.postMessage({type:t.FRAME,error:`WebCodecsDecoder waiting for keyframe`}),m();return}else o&&i&&(o=!1,s=!1,self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder got keyframe. Start decoding`}));let l=new EncodedVideoChunk({type:i?`key`:`delta`,timestamp:e,data:n});a.decode(l)}catch(e){_(`because failed call decode: ${u(e)}`),d(`decode`,e);return}v(i)}self.onmessage=e=>{try{switch(e.data.type){case t.INIT:f();break;case t.FRAME:p(e.data.timestamp,e.data.data,e.data.isVP9,e.data.keyFrame);break}}catch(e){d(`message`,e)}};function m(){s||(self.postMessage({type:t.FRAME,requestKeyFrame:!0}),s=!0)}function h(e){if(a!==e&&(a=e,_(`because codec is changed to ${a?`VP9`:`VP8`}`)),!r){o=!0,self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec ${a?`VP9`:`VP8`}`}),r=new VideoDecoder({output:e=>{y(),g(e)},error:e=>{y(),_(`because error during decoding: ${u(e)}`),i===`prefer-software`?self.postMessage({type:t.FRAME,error:`WebCodecsDecoder failed, reinitialize: `+u(e)}):(i=`prefer-software`,c&&c.keyFrame&&p(c.timestamp,c.data,c.isVP9,c.keyFrame),self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec switch to prefer-software because decoding issue: ${u(e)}`}))}});try{r.configure(b(a,i))}catch(e){throw _(`because failed configure: ${u(e)}`),d(`configure`,e),e}}return r}function g(e){try{let r=n?[e]:[];self.postMessage({type:t.FRAME,data:e},r)}catch(n){try{self.postMessage({type:t.FRAME,data:e})}catch(e){d(`postMessage`,e),d(`postMessage transfer`,n)}}finally{try{e.close()}catch{}}}function _(e){if(r){try{r&&r.state!==`closed`&&r.close()}catch{}r=null,self.postMessage({type:t.FRAME,error:`WebCodecsDecoder reset ${e}`})}}function v(e=!1){l=setTimeout(()=>{_(`because of decode timeout`)},3e3)}function y(){l&&clearTimeout(l),l=null}function b(t,n){return{codec:t?e.VP9:e.VP8,hardwareAcceleration:n}}}})(),exports={default:workerExports};",r=>{r.error?(this._debug.warn(`WebCodecsDecoder`,r.error),t(r.error)):r.requestKeyFrame?(this._debug.debug(`WebCodecsDecoder requests key frame`),n()):(e(r.data),r.data.close())},[!0])}decodeFrame(e,t,n,r=!1){this._sendToWorker(ti.FRAME,{timestamp:e,data:t.buffer,isVP9:n,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),this._debug.debug(`WebCodecsDecoder destroyed`)}static isBrowserSupported(){return`VideoDecoder`in window&&`Worker`in window&&`VideoFrame`in window&&!T.isBrokenVP9Decoder()&&T.browserName()!==`Firefox`}},ai=class{constructor(e=null,t=0){h(this,`_counter`,0),h(this,`_interval`,0),h(this,`_lastCalculationTime`,Date.now()),h(this,`_onCalculated`,null),this._onCalculated=e,t&&(this._interval=window.setInterval(()=>this.calculate(),t))}increment(e=1){this._counter+=e}calculate(){let e=Date.now(),t=e-this._lastCalculationTime,n=Math.round(this._counter*1e3/t);return this._counter=0,this._lastCalculationTime=e,this._onCalculated?.(n),n}destroy(){window.clearInterval(this._interval),this._interval=0}},oi=class{constructor(e,t){h(this,`_participantId`,void 0),h(this,`_statAggregator`,void 0),h(this,`_firstFrameReceived`,!1),this._participantId=e,this._statAggregator=t}measure(e,t){if(this._firstFrameReceived)return;this._firstFrameReceived=!0;let n=W.getMarkNameScreenshareFirstFrame(this._participantId),r=W.measureMark(n);r!==null&&this._statAggregator?.logEventualStat({name:H.SCREENSHARE_FIRST_FRAME,value:r,width:e,height:t})}},si=65536,ci=`MARK_SCREENSHARE_FREEZE_DURATION`,li=class e{constructor(e,t,n,r,i,a=R){h(this,`_participantId`,void 0),h(this,`_onStream`,void 0),h(this,`_onStat`,void 0),h(this,`_onKeyFrameRequested`,void 0),h(this,`_statScreenShareFirstFrame`,void 0),h(this,`_debug`,void 0),h(this,`_chunks`,[]),this._participantId=e,this._onStream=t,this._onStat=n,this._onKeyFrameRequested=i,this._statScreenShareFirstFrame=new oi(e,r),this._debug=a}appendChunk(t){let n=this._chunks.length;if(t.start)this._measureFreezeDuration(!1),this._measureFreezeDuration(!0),n&&(this._debug.warn(`[FrameBuilder] Cleanup buffer`,Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!n||(this._chunks[n-1].sequence+1)%si!==t.sequence){this._debug.warn(`[FrameBuilder] Got incorrect chunk`);return}if(this._chunks.push(t),t.end){let n=this._processFrameData(),{width:r,height:i}=e.getFrameSize(n);this._processFrame({timestamp:t.timestamp,frameData:n,isVP9:t.isVP9,keyframe:t.keyframe,width:r,height:i}),this._statScreenShareFirstFrame.measure(r,i)}}destroy(){W.clearMark(ci),W.clearMark(W.getMarkNameScreenshareFirstFrame(this._participantId)),this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((e,t)=>e+t.data.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(new Uint8Array(t.data),r),r+=t.data.byteLength;return n}static getFrameSize(e){let t={width:0,height:0},n=new d.BitStream(e.buffer);n.bigEndian=!0,n.index+=2;let r=n.readBits(1),i=n.readBits(1)<<1|r;return i===3&&n.index++,n.readBits(1)===1||n.readBits(1)!==0?t:(n.index++,n.index++,n.index+=24,i>=2&&n.index++,n.readBits(3)===7?(i===1||i===3)&&n.index++:(n.index++,(i===1||i===3)&&(n.index+=3)),t.width=n.readBits(16)+1,t.height=n.readBits(16)+1,t)}static isBrowserSupported(){throw Error("Method `isBrowserSupported` is not implemented")}_measureFreezeDuration(e){if(e){W.setMark(ci);return}let t=W.measureMark(ci);t!==null&&t>1e3&&this._onStat({freeze_duration:t})}},ui=class{constructor(e){h(this,`_onStream`,void 0),this._onStream=e}async drawFrame(e){throw Error("Method `drawFrame` is not supported by this implementation")}async drawImage(e){throw Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw Error("Method `isBrowserSupported` is not implemented")}},di=class extends ui{constructor(e,t=R){super(e),h(this,`_useImageBitmap`,void 0),h(this,`_canvas`,null),h(this,`_canvasContext`,null),h(this,`_stream`,null),h(this,`_track`,null),h(this,`_debug`,void 0),this._debug=t,this._debug.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{}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}async _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,this._useImageBitmap){let t;if(e instanceof ImageBitmap)t=e;else{let{width:n,height:r,data:i}=e,a=n*r*4;if(i.byteLength!==a){this._debug.warn(`Bad frame buffer`,{w:n,h:r,got:i.byteLength,expected:a});return}t=await createImageBitmap(e,0,0,e.width,e.height)}if(!this._canvasContext){this._debug.warn(`Canvas context is null`),t.close();return}this._canvasContext.transferFromImageBitmap(t),t.close()}else{let n=this._canvasContext;n.clearRect(0,0,t.width,t.height),n.putImageData(e,0,0)}this._requestCanvasFrame()}async drawFrame(e){let t=`createImageBitmap`in e?await e.createImageBitmap():await createImageBitmap(e);await this._drawImage(t)}async drawImage(e){await this._drawImage(e)}destroy(){this._removeStream(),this._debug.debug(`CanvasRenderer destroyed`)}static isBrowserSupported(){return(`CanvasCaptureMediaStream`in window||`CanvasCaptureMediaStreamTrack`in window)&&!(T.browserName()===`Safari`&&Number(T.browserVersion())===15)}},fi=class extends ui{constructor(e,t=R){super(e),h(this,`_generator`,void 0),h(this,`_writer`,void 0),h(this,`_stream`,void 0),h(this,`_debug`,void 0),this._debug=t,this._debug.debug(`TrackGeneratorRenderer started`),this._generator=new MediaStreamTrackGenerator({kind:k.video}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}async drawFrame(e){await this._writer.write(e)}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),this._debug.debug(`TrackGeneratorRenderer destroyed`)}static isBrowserSupported(){return`VideoFrame`in window&&`MediaStreamTrackGenerator`in window&&ii.isBrowserSupported()}},pi=class extends li{constructor(e,t,n,r,i,a=R,o=null){super(e,t,n,r,i,a),h(this,`_renderer`,void 0),h(this,`_decoder`,void 0),h(this,`_decoderReady`,!1),h(this,`_decoderBusy`,!1),h(this,`_decoderQueue`,[]),h(this,`_webCodecsRetryAttempted`,!1),h(this,`_fpsMeter`,void 0),h(this,`_logger`,void 0),this._logger=o,this._debug.debug(`StreamBuilder started for participant [${e}]`),this._initFpsMeter(),this._initRenderer(),this._initDecoder()}_processFrame(e){e.keyframe&&(this._decoderQueue=[]),this._decoderQueue.push(e),this._decodeQueue()}_initFpsMeter(){this._fpsMeter=new ai(e=>this._debug.log(`[StreamBuilder][${this._participantId}] fps: ${e}`),2e4)}_initRenderer(e=!1){e||!fi.isBrowserSupported()?this._renderer=new di(this._onStream,this._debug):this._renderer=new fi(this._onStream,this._debug)}_initDecoder(e=!1){e||!ii.isBrowserSupported()?this._decoder=new ri(this._debug,this._logger):this._decoder=new ii(this._debug,this._logger),this._decoder.init(async e=>{this._decoderBusy=!1,`VideoFrame`in window&&e instanceof VideoFrame?await this._renderer.drawFrame(e):await this._renderer.drawImage(e),this._fpsMeter.increment(),this._decodeQueue()},e=>{if(this._decoderBusy=!1,this._decoder instanceof ii&&typeof e==`string`&&e.includes(`EncodingError`)){this._decoderQueue=[],!this._webCodecsRetryAttempted&&e.includes(`reset because error during decoding`)?(this._webCodecsRetryAttempted=!0,this._debug.warn(`StreamBuilder retry WebCodecs with software decoder`),this._onKeyFrameRequested?.()):this._switchToLibVPXDecoder();return}this._decodeQueue()},this._onKeyFrameRequested).then(()=>{this._decoderReady=!0,this._decodeQueue()}).catch(e=>{this._debug.warn(`StreamBuilder decoder init failed`,e),this._decoder instanceof ii&&this._switchToLibVPXDecoder()})}_switchToLibVPXDecoder(){this._debug.warn(`StreamBuilder switch to LibVPX decoder`),this._decoderQueue=[],this._fpsMeter&&this._fpsMeter.destroy(),this._decoder&&(this._decoderReady=!1,this._decoderBusy=!1,this._decoder.destroy()),this._renderer&&this._renderer.destroy(),this._initFpsMeter(),this._initRenderer(!0),this._initDecoder(!0),this._onKeyFrameRequested?.()}_decodeQueue(){if(!this._decoderReady||this._decoderBusy)return;let e=this._decoderQueue.shift();e&&(this._decoderBusy=!0,this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe))}destroy(){super.destroy(),this._fpsMeter.destroy(),this._decoder.destroy(),this._renderer.destroy(),this._debug.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return di.isBrowserSupported()||fi.isBrowserSupported()}},mi=1,hi=1,gi=2,_i=0,vi=1,yi=2,bi=4,xi=8;function Si(e,t,n,r,i,a,o){let s=0;t&&(s|=vi),n&&(s|=yi),r&&(s|=bi),o||(s|=xi);let c=new ArrayBuffer(11),l=new DataView(c);if(l.setUint8(0,mi),l.setUint16(1,i),l.setUint32(3,e),l.setUint8(7,+!!a),l.setUint16(8,_i),l.setUint8(10,s),!o)return c;let u=new Uint8Array(c.byteLength+o.byteLength);return u.set(new Uint8Array(c),0),u.set(new Uint8Array(o),c.byteLength),u.buffer}function Ci(e){let t=new DataView(e),n=t.getUint8(0),r=t.getUint16(1),i=t.getUint32(3),a=t.getUint8(7)===1,o=t.getUint16(8),s=t.getUint8(10),c=!!(s&vi),l=!!(s&yi),u=!!(s&bi),d=!!(s&xi);if(n!==mi)throw Error(`Unexpected protocol version. Got ${n}, expected ${mi}`);return{timestamp:i,start:c,end:l,keyframe:u,sequence:r,isVP9:a,ssrc:o,eos:d,data:e.slice(11)}}function wi(e){if(!e||!e.byteLength||e.byteLength!==4)return!1;let t=new DataView(e);return!(t.getUint8(0)!==mi||t.getUint8(1)!==hi||t.getUint16(2)!==_i)}function Ti(e){if(!e||!e.byteLength||e.byteLength!==10)return null;let t=new DataView(e);return t.getUint8(0)!==mi||t.getUint8(1)!==gi||t.getUint16(2)!==_i?null:{seq:t.getUint16(4),ts2:t.getUint32(6)}}function Ei(e){let t=new ArrayBuffer(4),n=new DataView(t);return n.setUint8(0,mi),n.setUint8(1,hi),n.setUint16(2,e),t}var Di=2**15-1,Oi=1,ki=5,Ai=5,ji=class e{constructor(e,t=R){h(this,`_mediaSource`,void 0),h(this,`_codec`,void 0),h(this,`_sourceBuffer`,null),h(this,`_queue`,[]),h(this,`_clearBufferTill`,0),h(this,`_debug`,void 0),this._mediaSource=new MediaSource,this._codec=e,this._debug=t;let n=()=>{this._mediaSource.removeEventListener(`sourceopen`,n),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener(`sourceopen`,n,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let e=this._sourceBuffer.buffered.start(0);e<this._clearBufferTill&&(this._sourceBuffer.remove(e,this._clearBufferTill),this._debug.debug(`[WebmBuilder] SourceBuffer cleanup from ${e} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let t=this._queue;this._queue=[];let n=e._buildQueue(t);this._sourceBuffer.appendBuffer(n)}static _buildQueue(e){if(!e.length)return new Uint8Array;if(e.length===1)return f.build(e[0]);let t=e.reduce((e,t)=>e+t.countSize(),0),n=new Uint8Array(t),r=0;for(let t of e){let e=f.build(t);n.set(e,r),r+=e.byteLength}return n}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode=`sequence`,this._sourceBuffer.addEventListener(`updateend`,()=>this._handleQueue())}changeType(e){return this._codec=e,this._sourceBuffer?.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){this._mediaSource?.readyState===`open`&&this._sourceBuffer?.abort();let e=this._sourceBuffer?.buffered,t=e?.length;if(!t)return;let n=e.start(0),r=Math.max(0,e.end(t-1)-ki);r-n>Ai&&(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(){return this._sourceBuffer?.buffered}},Mi=class e extends li{constructor(e,t,n,r,i=R){super(e,t,n,r,void 0,i),h(this,`_mediaBuffer`,null),h(this,`_video`,null),h(this,`_stream`,null),h(this,`_earliestTimestamp`,0),h(this,`_clusterStartTime`,0),h(this,`_lastFrameTimestamp`,0),this._debug.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return f.element(f.ID.EBML,[f.element(f.ID.EBMLVersion,f.number(1)),f.element(f.ID.EBMLReadVersion,f.number(1)),f.element(f.ID.EBMLMaxIDLength,f.number(4)),f.element(f.ID.EBMLMaxSizeLength,f.number(8)),f.element(f.ID.DocType,f.string(`webm`)),f.element(f.ID.DocTypeVersion,f.number(2)),f.element(f.ID.DocTypeReadVersion,f.number(2))])}static _genSegmentHeader(e,t,n){let r=f.element(f.ID.Info,[f.element(f.ID.TimecodeScale,f.number(1e6)),f.element(f.ID.MuxingApp,f.string(`vk-webm-builder`)),f.element(f.ID.WritingApp,f.string(`vk-webm-builder`))]),i=[f.element(f.ID.PixelWidth,f.number(e)),f.element(f.ID.PixelHeight,f.number(t))],a=f.element(f.ID.Tracks,f.element(f.ID.TrackEntry,[f.element(f.ID.TrackNumber,f.number(Oi)),f.element(f.ID.TrackUID,f.number(Oi)),f.element(f.ID.TrackType,f.number(1)),f.element(f.ID.FlagLacing,f.number(0)),f.element(f.ID.DefaultDuration,f.number(1e9)),f.element(f.ID.CodecID,f.string(`V_${n.toUpperCase()}`)),f.element(f.ID.Video,i)]));return f.unknownSizeElement(f.ID.Segment,[r,a])}static _genClusterHeader(e){return f.unknownSizeElement(f.ID.Cluster,[f.element(f.ID.Timecode,f.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new ji(e,this._debug),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){this._debug.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let e=this._video.seekable;e.length&&(this._video.currentTime=e.end(e.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>this._debug.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video?.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(t){let n=t.isVP9?`vp9`:`vp8`;this._mediaBuffer?this._mediaBuffer.codec!==n&&this._mediaBuffer.changeType(n):this._createVideo(n);let r=t.timestamp;if(r<=this._lastFrameTimestamp&&(r=this._lastFrameTimestamp+10,this._debug.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=r,this._earliestTimestamp)r-=this._earliestTimestamp;else{if(!t.keyframe)return;this._earliestTimestamp=r,r=0}if(t.keyframe){this._clusterStartTime=r,this._mediaBuffer?.cleanup(),this._debug.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let i=e._genWebmHeader();this._mediaBuffer?.append(i);let a=e._genSegmentHeader(t.width,t.height,n);this._mediaBuffer?.append(a)}let i=Math.round(r-this._clusterStartTime);if(i>Di&&(this._clusterStartTime=r,i=0),i===0){this._debug.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let t=e._genClusterHeader(this._clusterStartTime);this._mediaBuffer?.append(t)}let a=f.element(f.ID.SimpleBlock,[f.vintEncodedNumber(Oi),f.bytes(e._intToU16BE(i)),f.number(!!t.keyframe<<7),f.bytes(t.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),this._debug.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){return`captureStream`in window.HTMLVideoElement?.prototype&&window.MediaSource?.isTypeSupported(`video/webm; codecs="vp8"`)&&window.MediaSource?.isTypeSupported(`video/webm; codecs="vp9"`)}},Ni=class{constructor(e,t,n,r,i,a=null,o=R,s=null){h(this,`_datachannel`,void 0),h(this,`_participantIdRegistry`,null),h(this,`_streamBuilders`,{}),h(this,`_onStream`,()=>{}),h(this,`_onEos`,()=>{}),h(this,`_onStat`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_statAggregator`,void 0),this._debug=o,this._logger=s,this._statAggregator=a,this._debug.debug(`ScreenCaptureReceiver started`),this._datachannel=e,this._participantIdRegistry=t,this._onStream=n,this._onEos=r,this._onStat=i,this._datachannel.onmessage=e=>this._onDataChannelMessage(e.data)}_onDataChannelMessage(e){let t=Ci(e),n=this._participantIdRegistry?.getStreamDescription(t.ssrc)?.participantId;if(!n){this._debug.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(n),this._onEos(n);return}let r=this._streamBuilders[n];if(!r){let e=e=>this._onStream(n,e);r=M.screenShareWebmBuilder&&Mi.isBrowserSupported()?new Mi(n,e,this._onStat,this._statAggregator,this._debug):new pi(n,e,this._onStat,this._statAggregator,()=>{this._requestKeyFrame(t.ssrc)},this._debug,this._logger),this._streamBuilders[n]=r}r.appendChunk(t)}_requestKeyFrame(e){if(!(!this._datachannel||this._datachannel.readyState!==`open`))try{let t=Ei(e);this._datachannel.send(t),this._debug.debug(`ScreenCaptureReceiver request for keyframe for ssrc ${e}`)}catch(e){this._debug.warn(`Failed to send keyframe request`,e)}}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,this._debug.debug(`ScreenCaptureReceiver destroyed`)}},Pi=class{constructor(e,t,n){h(this,`_prev`,void 0),h(this,`_next`,void 0),h(this,`_data`,void 0),this._next=n,n&&(n.prev=this),this._prev=t,t&&(t.next=this),this._data=e}get prev(){return this._prev}set prev(e){this._prev=e}get next(){return this._next}set next(e){this._next=e}get data(){return this._data}},Fi=class{constructor(){h(this,`_head`,null),h(this,`_tail`,null),h(this,`_length`,0)}get length(){return this._length}push(...e){for(let t of e)this._tail=new Pi(t,this._tail,null),this._head||(this._head=this._tail),this._length++}merge(e){this._tail&&(this._tail.next=e._head),this._head||(this._head=e._head),this._tail=e._tail,this._length+=e._length,e.clear()}shift(){if(!this._length||!this._head)return null;let e=this._head;return this._head=e.next,this._head&&(e.next=null,this._head.prev=null),this._length--,this.length===1?this._tail=this._head:this.length||(this._head=this._tail=null),e.data}bisect(){if(this.length){let e=this.length>1?Math.floor(this.length/2):1;for(let t=0;t<e;t++)this.shift()}}head(){return this._head?.data||null}tail(){return this._tail?.data||null}clear(){this._head=null,this._tail=null,this._length=0}toString(){let e=[],t=this._head;for(;t!==null;)e.push(t.data),t=t.next;return e.length?JSON.stringify(e,(e,t)=>t instanceof Error?String(t):t):``}},Ii=1e3,Li=class extends ni{constructor(e,t,n,r,i=R,a=null){super(i,a),h(this,`_sourceTrack`,void 0),h(this,`_onFrame`,void 0),h(this,`_useCongestionControl`,void 0),h(this,`_maxBitrate`,void 0),h(this,`_useImageCapture`,void 0),h(this,`_video`,null),h(this,`_imageCapture`,null),h(this,`_canvas`,null),h(this,`_canvasCtx`,null),h(this,`_frameReadTimeout`,0),h(this,`_lastFrame`,null),this._sourceTrack=e,this._onFrame=t,this._useCongestionControl=n,this._maxBitrate=r,this._useImageCapture=`ImageCapture`in window&&ImageCapture.prototype.grabFrame!==void 0&&`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{}this._canvasCtx=null,this._canvas=null,this._video=null}async _createStream(e){if(!this._canvas)throw Error(`Canvas not found`);if(!this._video&&!this._useImageCapture)throw Error(`Video element not found`);return new Promise((t,n)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=e=>t(),r.onerror=()=>n(Error(`Video element error`));let i=r.play(),a=()=>n(Error(`Autoplay is disabled`));i?i.catch(a):a()}})}_removeStream(){window.clearTimeout(this._frameReadTimeout),this._lastFrame?.close(),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video)throw 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._canvasCtx.getImageData(0,0,e,t)}async _getFrameBitmap(){if(!this._imageCapture)throw Error(`Destroyed`);return this._imageCapture.grabFrame()}_drawFrameData(e){if(!this._canvas||!this._canvasCtx)throw Error(`Destroyed`);let t=e.width,n=e.height;return this._canvas.width=t,this._canvas.height=n,this._canvasCtx.clearRect(0,0,t,n),this._canvasCtx.drawImage(e,0,0,t,n),this._canvasCtx?.getImageData(0,0,t,n)}async init(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;this._debug.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?`VP9`:`VP8`}`),await this._createStream(this._sourceTrack),await this._createWorker("var workerExports=(function(){var e=function(e){return 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}({});return(t,n,r,i)=>{let a;function o(o,s){return t({locateFile:n}).then(t=>{if(a=new t.VpxEncoder,a.debug(s),!a.init(o?t.VpxType.VP9:t.VpxType.VP8))throw self.postMessage({type:e.LOG_ERROR,message:`encoder-init-fail-libvpx`}),Error(`LibVPxEncoder failed to create`);if(r){let e=Math.round(i/1e3);a.setTargetBitrate(e)}else a.setMaxQuantizer(10),a.setTargetBitrate(1024)})}function s(t,n,r,i){let o=a.allocateImage(t,n);if(!o){self.postMessage({type:e.FRAME,error:`No buffer data`});return}o.set(new Uint8Array(r));let s=Math.round(performance.now());if(!a.encode(s,150,i)){self.postMessage({type:e.FRAME,error:`Encode failed`});return}let c=a.readFrame();if(!c){self.postMessage({type:e.FRAME,error:`No encoded data`});return}a.readFrame()&&(self.postMessage({type:e.DEBUG,message:`LibVPxEncoder dropped frame`}),self.postMessage({type:e.LOG_ERROR,message:`LibVPxEncoder-drop`}));let l=new Uint8Array(c.byteLength);l.set(c),self.postMessage({type:e.FRAME,frameType:i?`key`:`delta`,timestamp:s,duration:150,width:t,height:n,data:l.buffer},[l.buffer])}function c(e,t){let n=Math.round(e/1e3);a.setTargetBitrate(n)}self.onmessage=t=>{switch(t.data.type){case e.INIT:o(t.data.isVP9,t.data.debug).then(()=>self.postMessage({type:e.READY})).catch(t=>self.postMessage({type:e.ERROR,error:String(t)}));break;case e.FRAME:s(t.data.width,t.data.height,t.data.imageData,t.data.keyFrame);break;case e.SET_BITRATE:c(t.data.bitrate,t.data.useCbr);break}}}})(),exports={default:workerExports};",e=>{e.error?this._onFrame(null,e.error):this._onFrame({type:e.frameType,timestamp:e.timestamp,duration:e.duration,data:e.data,byteLength:e.data?.byteLength,width:e.width,height:e.height})},[u.default,u.default.getUrl,this._useCongestionControl,this._maxBitrate],{isVP9:this.isVP9(),debug:R.enabled()})}_encode(e,t){let n=e.data.buffer;this._sendToWorker(ti.FRAME,{width:e.width,height:e.height,imageData:n,keyFrame:t},[n])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){window.clearTimeout(this._frameReadTimeout),this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},Ii),this._getFrameBitmap().then(t=>{window.clearTimeout(this._frameReadTimeout),this._lastFrame?.close(),this._lastFrame=t;let n=this._drawFrameData(t);this._encode(n,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}setBitrate(e,t,n){this._sendToWorker(ti.SET_BITRATE,{bitrate:e,useCbr:t})}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),this._debug.debug(`LibVPxEncoder destroyed`)}},Ri=class extends ni{constructor(e,t,n,r,i,a,o=R,s=null){super(o,s),h(this,`_sourceTrack`,void 0),h(this,`_trackProcessor`,void 0),h(this,`_onFrame`,void 0),h(this,`_useCongestionControl`,void 0),h(this,`_maxBitrate`,void 0),h(this,`_useCbr`,void 0),h(this,`_frameRate`,void 0),this._sourceTrack=e,this._onFrame=t,this._useCongestionControl=n,this._maxBitrate=r,this._useCbr=i,this._frameRate=a,this._trackProcessor=new MediaStreamTrackProcessor({track:e})}async init(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,n=this._trackProcessor.readable;this._debug.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?`VP9`:`VP8`}`),await this._createWorker("var workerExports=(function(){var e=function(e){return e.VP9=`vp09.00.50.08`,e.VP8=`vp8`,e}({}),t=function(e){return 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}({});return()=>{let n,r,i,a,o,s,c=null,l=0,u=!1,d=0,f,p,m=!1,h=!1,g=null;function _(e){return e instanceof Error?[e.name,e.message,e.stack].filter(Boolean).join(`: `):String(e)}function v(e,n){try{self.postMessage({type:t.FRAME,error:`WebCodecsEncoder ${e} failed: ${_(n)}`})}catch{}}function y(e,n){try{self.postMessage({type:t.ERROR,error:`WebCodecsEncoder ${e} failed: ${_(n)}`})}catch{}}function b(e){try{n=e.readable,r=n.getReader(),i=e.width,a=e.height,o=e.isVP9,s=e.framerate,f=e.useCongestionControl,p=e.maxBitrate,f&&(d=p,m=e.useCbr),T(),C(),self.postMessage({type:t.READY})}catch(e){y(`init`,e)}}function x(e){e&&!h&&(h=!0),self.clearTimeout(l),l=self.setTimeout(()=>{c&&S(c,h)},1e3),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(l)}).then(({done:e,value:t})=>{if(c?.close(),c=null,!(e||!t)){if(!g){r.releaseLock(),n.cancel();return}c=t,S(t,h)}}).catch(e=>{v(`read`,e)}))}function S(e,t){try{let n=e.codedWidth!==i||e.codedHeight!==a;n&&(i=e.codedWidth,a=e.codedHeight,t=!0),!g||g.state===`closed`?(T(),C()):n&&C(),g?.encode(e,{keyFrame:t}),t&&(h=!1)}catch(e){g&&g.state===`closed`&&(g=null),v(`encode`,e)}}function C(){if(!g)throw Error(`encoder is not initialized`);let t={framerate:s,codec:o?e.VP9:e.VP8,width:i,height:a,latencyMode:`realtime`,bitrateMode:m?`constant`:`variable`};d>0&&(t.bitrate=d),g.configure(t)}function w(e,t,n){try{d=e,m=t,s=n,(!g||g.state===`closed`)&&T(),C()}catch(e){v(`setBitrate`,e)}}function T(){g=new VideoEncoder({output:e=>{try{let n;e.data?n=e.data:(n=new ArrayBuffer(e.byteLength),e.copyTo(n)),self.postMessage({type:t.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,width:i,height:a,data:n},[n])}catch(e){v(`output`,e)}},error:e=>{g&&g.state===`closed`&&(g=null),v(`codec`,e)}})}self.onmessage=e=>{try{switch(e.data.type){case t.INIT:b(e.data);break;case t.FRAME:x(e.data.keyFrame);break;case t.SET_BITRATE:w(e.data.bitrate,e.data.useCbr,e.data.fps);break}}catch(e){v(`message`,e)}}}})(),exports={default:workerExports};",e=>{e.error?this._onFrame(null,e.error):this._onFrame({type:e.frameType,timestamp:e.timestamp,duration:e.duration,data:e.data,byteLength:e.data?.byteLength,width:e.width,height:e.height})},[],{readable:n,width:e,height:t,isVP9:this.isVP9(),framerate:this._frameRate,useCongestionControl:this._useCongestionControl,maxBitrate:this._maxBitrate,useCbr:this._useCbr},[n])}requestFrame(e=!1){this._sendToWorker(ti.FRAME,{keyFrame:e})}setBitrate(e,t,n){this._sendToWorker(ti.SET_BITRATE,{bitrate:e,useCbr:t,fps:n})}isVP9(){return!0}destroy(){this._removeWorker(),this._debug.debug(`WebCodecsEncoder destroyed`)}static isBrowserSupported(){return`VideoEncoder`in window&&`Worker`in window&&`EncodedVideoChunk`in window&&`MediaStreamTrackProcessor`in window}},zi=2100,Bi=600,Vi=1.2,Hi=.8,Ui=2e3,Wi=8e3,Gi=8e3,Ki=16e3,qi=4,Ji=2e3,Yi=function(e){return e[e.NONE=0]=`NONE`,e[e.UP=1]=`UP`,e[e.DOWN=2]=`DOWN`,e}(Yi||{}),Xi=class{constructor(e,t,n,r,i,a,o,s=R){h(this,`_onCongestion`,void 0),h(this,`_ccEnabled`,void 0),h(this,`_fastSharing`,void 0),h(this,`_trendDelayThreshold`,void 0),h(this,`_highDelayThreshold`,void 0),h(this,`_targetFps`,void 0),h(this,`_minBitrate`,void 0),h(this,`_maxBitrate`,void 0),h(this,`_targetBitrate`,void 0),h(this,`_lastDown`,void 0),h(this,`_lastUp`,void 0),h(this,`_lastProbing`,void 0),h(this,`_lastCheckDelay`,void 0),h(this,`_upPenalty`,0),h(this,`_probing`,void 0),h(this,`_delayAvgShort`,-1),h(this,`_delayAvgLong`,-1),h(this,`_minDelay`,Number.MAX_VALUE),h(this,`_maxDelay`,0),h(this,`_largeDelayDuration`,0),h(this,`_lastFpsCalcMs`,void 0),h(this,`_frames`,0),h(this,`_fps`,0),h(this,`_debug`,void 0),this._onCongestion=e,this._ccEnabled=r,this._debug=s,this._minBitrate=t,this._maxBitrate=n,this._fastSharing=i,this._targetFps=o,a>0?this._highDelayThreshold=a:this._highDelayThreshold=zi,i&&(this._highDelayThreshold=Bi),this._trendDelayThreshold=Math.round(this._highDelayThreshold/3),this._targetBitrate=this._maxBitrate,this._probing=!1;let c=Date.now();this._lastDown=0,this._lastUp=c,this._lastProbing=c,this._lastCheckDelay=0,this._lastFpsCalcMs=0}checkDelay(e,t,n){let r=Date.now();if(this._calcFps(r),this._calcDelay(t,r),this._delayAvgShort<=0||this._delayAvgLong<=0||!this._ccEnabled)return;let i=0,a=this._delayAvgShort-this._delayAvgLong,o=Math.round(Math.abs(a)*100/this._delayAvgLong),s=a>40&&o>30&&this._delayAvgShort>this._trendDelayThreshold,c=this._delayAvgShort>this._highDelayThreshold;s||c?i=2:Math.abs(a)<40&&o<10&&!c&&(i=1);let l=Math.round(this._targetBitrate/1e3),u=n;e%20==0&&this._debug.debug(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Yi[i]} tr=${l} br=${n}`);let d=r-this._lastDown;if(i===2&&d>Ui){this._probing&&(this._upPenalty=Math.min(++this._upPenalty,qi),this._probing=!1);let n=Hi*u*1e3;if(n>=this._targetBitrate&&(n=this._targetBitrate*Hi),n=Math.max(n,this._minBitrate),n<this._targetBitrate){let r=Math.round(n/1e3),s=Math.round(this._upPenalty*Gi/1e3);this._debug.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Yi[i]}`),this._debug.log(`#${e}: cc: DOWN delay=${t} bitrate=${u} target=${l} -> newBitrate=${r} penalty=${s}s`),this._setBitrate(n,!0),this._targetBitrate=n}this._lastDown=r}let f=r-this._lastUp,p=Wi+this._upPenalty*Gi;if(i===1&&f>p&&d>p){let n=Math.min(this._targetBitrate*Vi,this._maxBitrate);if(n>this._targetBitrate){let s=Math.round(n/1e3),c=Math.round(this._targetBitrate/1e3),l=Math.round(this._upPenalty*Gi/1e3);this._debug.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Yi[i]}`),this._debug.log(`#${e}: cc: UP bitrate=${u} target=${c} -> newBitrate=${s} penalty=${l}s`),this._setBitrate(n,!1),this._targetBitrate=n,this._probing=!0,this._lastProbing=r,this._lastUp=r}}let m=r-this._lastProbing;this._probing&&m>Ki&&(this._probing=!1);let ee=r-this._lastDown;this._upPenalty>0&&ee>3*p&&(this._debug.log(`#${e}: cc: UP reset penalty: oldPenalty=${this._upPenalty}`),this._upPenalty=0)}_setBitrate(e,t){this._fastSharing&&(t=!0);let n=this._targetFps;this._fps>0&&(n=this._fps),this._onCongestion(e,t,n)}_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>Ji){let e=t-this._lastCheckDelay;this._largeDelayDuration+=e}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}_calcFps(e){this._frames++;let t=e-this._lastFpsCalcMs;if(t>5e3){this._lastFpsCalcMs=e;let n=this._fps,r=this._frames*1e3/t;this._fps===0?this._fps=Math.round(r):this._fps=Math.round((this._fps*3+r)/4),this._frames=0,this._fps!==n&&this._debug.log(`cc: fps=${this._fps}`)}}},Zi=class{constructor(e){h(this,`_maxSize`,void 0),h(this,`_size`,0),h(this,`_buffer`,void 0),h(this,`_head`,0),h(this,`_tail`,0),this._maxSize=e,this._buffer=Array(e)}add(e,t,n,r,i){this._tail===this._head&&this._size>0&&(this._head=++this._head%this._maxSize);let a=this._tail;return this._buffer[this._tail]={seq:e,ts:t,size:n,sent:Date.now(),start:r,end:i,ts2:-1,recv:-1},this._tail=++this._tail%this._maxSize,this._size++,a}update(e,t){let n=this.get(e);return n===null?null:(n.ts2=t,n.recv=Date.now(),n)}get(e){let t=this._head;for(let n=0;n<this._maxSize;n++){let n=this._buffer[t];if(e===n?.seq)return n;if(t=++t%this._maxSize,t===this._tail)break}return null}getServerBitrateK(e){let t=0,n=0,r=-1,i=-1,a=this._tail;for(let t=0;t<this._maxSize;t++){a>0?--a:a=this._maxSize-1;let t=this._buffer[a];if(!t||(i===-1&&(i=t.ts2,n=0),i>=0&&(n+=t.size),r=t.ts2,i-r>=e)||a===this._head)break}if(r>=0&&i>=0){let e=i-r;t=Math.round(e>0?n*8/e:0)}return t}getCurrentDelay(){let e=this._tail;for(let t=0;t<this._maxSize;t++){e>0?--e:e=this._maxSize-1;let t=this._buffer[e];if(!t)break;if(t.recv>=0&&t.sent>=0)return t.recv-t.sent;if(e===this._head)break}return 0}getMaxBandwidth(){let e=0,t=0,n=-1,r=-1,i=this._tail;for(let a=0;a<this._maxSize;a++){i>0?--i:i=this._maxSize-1;let a=this._buffer[i];if(a){if(r===-1&&a.end&&!a.start&&(r=a.ts2,t=0),n===-1&&r>=0&&a.start&&!a.end&&(n=a.ts2),n>=0&&r>=0){let i=r-n;e=i>0?t*8/i:0;break}if(r>=0&&(t+=a.size),i===this._head)break}}return Math.round(e)}clear(){this._buffer.fill(void 0),this._size=0,this._head=0,this._tail=0}},Qi=65536,$i=50,ea=400,ta=1e6,na=3e5,ra=3e4,ia=2e3,aa=5,oa=0,sa=class{constructor(e,t,n,r,i=R,a=null){h(this,`_encoder`,void 0),h(this,`_datachannel`,void 0),h(this,`_signaling`,void 0),h(this,`_fastSharing`,void 0),h(this,`_destroyed`,!1),h(this,`_needKeyframe`,!0),h(this,`DATA_SIZE`,void 0),h(this,`_congestionControl`,void 0),h(this,`_frameNum`,0),h(this,`_width`,void 0),h(this,`_height`,void 0),h(this,`_feedback`,new Zi(1024)),h(this,`_lastSentFrameSeq`,0),h(this,`_lastDeliveredFrameSeq`,0),h(this,`_lastFrameDelay`,0),h(this,`_lastFramerateReduced`,Date.now()),h(this,`_lastSharingStat`,Date.now()),h(this,`_congestionControlEnabled`,void 0),h(this,`_queue`,new Fi),h(this,`_fpsMeter`,void 0),h(this,`_maxFrameDelay`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),this._debug=i,this._logger=a,this._debug.debug(`ScreenCaptureSender started`),this.DATA_SIZE=M.consumerScreenDataChannelPacketSize-11,this._datachannel=t,this._signaling=n,this._fastSharing=r,this._congestionControlEnabled=M.screenShareCongestionControl||this._fastSharing,this._width=e.getSettings().width,this._height=e.getSettings().height,this._maxFrameDelay=this._fastSharing?M.screenShareCongestionControlThreshold:M.screenShareCongestionControlThreshold*2;let o=M.getScreenFrameRate(this._fastSharing),{minBitrate:s,maxBitrate:c}=this._calcMinMaxBitrate(this._width,this._height),l=this._onCongestionCallback.bind(this);this._debug.log(`ScreenCaptureSender: CongestionControl: enabled=${this._congestionControlEnabled} minBitrate=${Math.round(s/1e3)}k maxBitrate=${Math.round(c/1e3)}k delayThreshold=${M.screenShareCongestionControlThreshold}`),this._congestionControl=new Xi(l,s,c,this._congestionControlEnabled,this._fastSharing,M.screenShareCongestionControlThreshold,o,this._debug);let u=(e,t)=>{if(this._destroyed)return;if(!e){this._debug.warn(`requestFrame failed, keyFrame: `+this._needKeyframe,t),this._needKeyframe=!0,this._handleQueue();return}(e.width!==this._width||e.height!==this._height)&&(this._width=e.width,this._height=e.height,this._onResize(this._width,this._height));let n=this._sliceFrame(e);this._queue.merge(n),this._handleQueue(),this._sendSharingStat()};if(Ri.isBrowserSupported()){let t=this._fastSharing;this._encoder=new Ri(e,u,this._congestionControlEnabled,c,t,o,this._debug,this._logger)}else this._encoder=new Li(e,u,this._congestionControlEnabled,c,this._debug,this._logger);this._datachannel.onmessage=e=>{wi(e.data)&&(this._debug.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0);let t=Ti(e.data);t!==null&&this._checkCcFeedback(t)},this._encoder.init().then(()=>this._handleQueue()).catch(e=>this._debug.warn(`ScreenCaptureSender init failed`,e)),this._fpsMeter=new ai(e=>this._debug.log(`[ScreenCaptureSender] fps: ${e}`),5e3)}_handleQueue(){if(this._destroyed)return;let e=this._queue.shift();if(!e){if((this._lastSentFrameSeq-this._lastDeliveredFrameSeq+Qi)%Qi>aa&&this._lastFrameDelay>this._maxFrameDelay){let e=Date.now();e-this._lastFramerateReduced>ia&&(this._lastFramerateReduced=e,this._debug.debug(`[ScreenCaptureSender] reduce framerate: delay=${this._lastFrameDelay} maxDelay=${this._maxFrameDelay}`))}else this._requestFrame();return}if(!this._sendFrameChunk(e)){this._needKeyframe=this._needKeyframe||!this._cleanupQueue(),j.setImmediate(()=>this._handleQueue());return}if(e.isLast){this._frameNum++,this._fpsMeter.increment(),e.isKey&&this._debug.debug(`#${this._frameNum}: sharing: send keyframe size=${Math.round(e.frameSize/1e3)}k`);let t=this._feedback.getCurrentDelay(),n=this._feedback.getServerBitrateK(2e3);t>0&&this._congestionControl.checkDelay(this._frameNum,t,n)}else j.setImmediate(()=>this._handleQueue())}_cleanupQueue(){let e=this._queue.head();for(;e;){if(e.isFirst&&e.isKey)return!0;this._queue.shift(),e=this._queue.head()}return!1}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_sliceFrame(e){let t=e.type===`key`,n=e.data.byteLength,r=new Fi;for(let i=0;i<n;i+=this.DATA_SIZE){let a=e.data.slice(i,i+this.DATA_SIZE),o=i===0,s=n<=i+a.byteLength,c=this._wrapHeader(e.timestamp,o,s,t,a);r.push({data:c.data,sequence:c.sequence,frameSize:n,isFirst:o,isLast:s,isKey:t,timestamp:e.timestamp})}return r}_wrapHeader(e,t,n,r,i){let a=Si(e,t,n,r,oa,this._encoder.isVP9(),i),o={sequence:oa,data:a};return oa=(oa+1)%Qi,o}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null).data}_sendFrameChunk(e){if(!this._datachannel||this._datachannel.readyState!==`open`)return!1;try{return this._datachannel.send(e.data),this._feedback.add(e.sequence,e.timestamp,e.data.byteLength,e.isFirst,e.isLast),e.isLast&&(this._lastSentFrameSeq=e.sequence),!0}catch(e){return this._debug.warn(`Error sending chunk to DataChannel`,e),!1}}destroy(){this._queue.clear(),this._fpsMeter.destroy(),this._datachannel.onmessage=null,this._feedback.clear(),this._datachannel.readyState===`open`&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),this._debug.debug(`ScreenCaptureSender destroyed`)}static isBrowserSupported(){return Ri.isBrowserSupported()||Li.isBrowserSupported()}_onCongestionCallback(e,t,n){this._encoder.setBitrate(e,t,n)}_onResize(e,t){let{minBitrate:n,maxBitrate:r}=this._calcMinMaxBitrate(e,t),i=Math.round(n/1e3),a=Math.round(r/1e3);this._debug.log(`cc: resize to ${e}x${t}, minBitrate=${i} maxBitrate=${a}`),this._congestionControl.reconfigure(n,r)}_calcMinMaxBitrate(e,t){(e===void 0||e<640)&&(e=640),(t===void 0||t<360)&&(t=360);let n=e*t/256;return{minBitrate:Math.max(na,Math.min(ta,Math.round(n*$i))),maxBitrate:Math.round(n*ea)}}_checkCcFeedback(e){let t=this._feedback.update(e.seq,e.ts2);if(t===null)this._debug.debug(`cc: update failed, seq=${e.seq}`);else if(t.end){this._lastDeliveredFrameSeq=t.seq;let e=t.recv-t.sent;e>0&&(this._lastFrameDelay=e),this._handleQueue()}}_sendSharingStat(){let e=Date.now();if(e-this._lastSharingStat>ra){let t=this._congestionControl.getStat();t!==null&&(this._debug.debug(`cc: send stats: ${JSON.stringify(t)}`),this._signaling.reportSharingStat(t).catch(e=>{!(e instanceof En)&&!(e instanceof Dn)&&this._debug.warn(`Unable to send sharing stats`,e)})),this._lastSharingStat=e}}},ca=class{constructor(e,t,n,r=R,i=null){h(this,`_pc`,null),h(this,`_transceiver`,null),h(this,`_currentSimulcastInfo`,null),h(this,`_signaling`,void 0),h(this,`_mediaSource`,void 0),h(this,`_getCameraSettings`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),this._signaling=e,this._mediaSource=t,this._getCameraSettings=n,this._debug=r,this._logger=i}async configureFromRemoteOffer(e){if(this.reset(),!M.simulcast)return;let t=this._findTransceiver(e);if(!t){this._debug.debug(`SimulcastSender: Multi-encoding video transceiver not found`);return}let n=this._mediaSource.getStream(),r=n?.getVideoTracks()[0];if(!n||!r){this._debug.debug(`SimulcastSender: Camera stream or track not found`);return}this._pc=e,this._transceiver=t,t.direction=`sendonly`,await t.sender.replaceTrack(r),t.sender.setStreams(n),await this._applyCurrentMediaState(),this._debug.log(`SimulcastSender: Prepared mid=${t.mid} encodings=${JSON.stringify(t.sender.getParameters().encodings)}`)}finalizeAnswer(e){if(!this._pc||!this._transceiver?.mid)return e;this._pc.getTransceivers().forEach(e=>{e.mid===null&&e.stop()});let t=dn(e),n=this._findMediaSection(t,this._transceiver.mid);if(n){for(let e=n.start;e<n.end;e++)if(t[e].startsWith(`a=simulcast:send `)){t[e]=t[e].replaceAll(`~`,``);break}let e=this._mediaSource.getStream()?.getVideoTracks()[0];e&&this._getConfig(Qt.WIDTH,Qt.HEIGHT,e.getSettings().frameRate).simulcastInfo.streams.forEach(e=>{let r=`a=rid:${e.rid} send`;for(let i=n.start;i<n.end;i++)if(t[i]===r||t[i].startsWith(r+` `)){t[i]=`${r} max-width=${e.width};max-height=${e.height};max-fps=${e.fps};max-br=${e.bitrate}`;break}})}return fn(t)}async sync({force:e=!1}={}){if(!this._transceiver||!this._currentSimulcastInfo||!this._mediaSource.mediaSettings.isVideoEnabled)return;let t=this._mediaSource.getStream()?.getVideoTracks()[0];if(!t)return;let n=this._getTrackConfig(t);if(!e&&nn(this._currentSimulcastInfo,n.simulcastInfo))return;let r=await this._applyConfig(n,!0);r&&(this._debug.log(`SimulcastSender: Sync ${n.width}x${n.height} encodings=${JSON.stringify(r.encodings)}`),await this._changeSimulcast({mediaSource:Xt.CAMERA,simulcastInfo:n.simulcastInfo}))}replaceTrack(e){let t=this._transceiver,n=t?.sender.track;if(!t||e.kind!==k.video||!n||n.contentHint!==e.contentHint)return!1;let r=this._mediaSource.mediaSettings.isVideoEnabled;return t.sender.replaceTrack(e).then(()=>{if(!r)return;let{width:t,height:n}=e.getSettings();t&&n&&this._syncReplacedTrack(e).catch(e=>{this._debug.error(`SimulcastSender: Failed to sync replaced track`,e)})}).catch(e=>{this._debug.error(`SimulcastSender: Unable to replace track`,e),this._logger?.log(C.ERROR,`replaceTrack-single`)}),!0}reset(){this._pc=null,this._transceiver=null,this._currentSimulcastInfo=null}_findTransceiver(e){for(let t of e.getTransceivers())if((t.sender.track?.kind??t.receiver.track?.kind)===k.video&&t.sender.getParameters().encodings.length>1)return t;return null}_findMediaSection(e,t){let n=-1;for(let r=0;r<e.length;r++)if(e[r].startsWith(`m=`)&&(n=r),e[r]===`a=mid:${t}`){if(n<0||!e[n].startsWith(`m=video`))return null;let t=e.findIndex((e,t)=>t>r&&e.startsWith(`m=`));return{start:n,end:t<0?e.length:t}}return null}_getConfig(e,t,n=30){let r=this._getCameraSettings(),i=r?.maxFramerate?Math.min(n||30,r.maxFramerate):n||30,a=r?.bitrates?.generic?.length?r.bitrates.generic:void 0;return{width:e,height:t,simulcastInfo:an(e,t,a,i),maxDimension:r?.maxDimension,maxBitrate:!a&&r?.maxBitrateK?r.maxBitrateK*1024:void 0}}_getTrackConfig(e){let t=e.getSettings();return this._getConfig(t.width??Qt.WIDTH,t.height??Qt.HEIGHT,t.frameRate)}async _applyConfig(e,t=!1){let n=this._transceiver;if(!n)return null;let r=n.sender.getParameters();if(r.encodings.length<=1)return null;sn(r.encodings,e.simulcastInfo,e.maxDimension,e.maxBitrate);try{await n.sender.setParameters(r)}catch(e){if(this._debug.error(`SimulcastSender: Failed to set sender parameters`,r,e),!t)throw e}return this._currentSimulcastInfo=e.simulcastInfo,r}async _applyCurrentMediaState(){let e=this._mediaSource.getStream()?.getVideoTracks()[0];if(!e)return;let t=this._mediaSource.mediaSettings.isVideoEnabled?this._getTrackConfig(e):this._getConfig(M.videoMinWidth,M.videoMinHeight,e.getSettings().frameRate),n=await this._applyConfig(t);n&&this._debug.log(`SimulcastSender: Current media state ${t.width}x${t.height} encodings=${JSON.stringify(n.encodings)}`)}async _syncReplacedTrack(e){let t=this._getTrackConfig(e);this._currentSimulcastInfo=t.simulcastInfo,await this._changeSimulcast({mediaSource:Xt.CAMERA,simulcastInfo:t.simulcastInfo})}async _changeSimulcast(e){try{await this._signaling.changeSimulcast(e)}catch(e){if(!(e instanceof Dn))throw e}}},la=90,ua=4294967295,da=class e extends Fr{constructor(e,t,n,r=R,i=null,a=null,o=null,s=null){super(e,t,s),h(this,`_producerNotification`,null),h(this,`_producerCommand`,null),h(this,`_producerScreen`,null),h(this,`_consumerScreen`,null),h(this,`_asr`,null),h(this,`_animojiDataChannel`,null),h(this,`_animojiReceiver`,null),h(this,`_animojiSender`,null),h(this,`_isOpen`,!1),h(this,`_observer`,!1),h(this,`_reconnectionPrevented`,!1),h(this,`_statInterval`,null),h(this,`_settingsInterval`,null),h(this,`_monitorRtpShareInterval`,null),h(this,`_statBytes`,{}),h(this,`_ssrcMap`,{}),h(this,`_ssrcMapUpdated`,!1),h(this,`_perfStatReporter`,void 0),h(this,`_producerOfferIsProcessing`,!1),h(this,`_producerNextOffer`,null),h(this,`_producerNextSessionId`,null),h(this,`_lastStat`,null),h(this,`_serverSettings`,void 0),h(this,`_prevConsumerSettings`,{}),h(this,`_prevConsumerFastSharingSettings`,{}),h(this,`_asrTrack`,null),h(this,`_captureSender`,null),h(this,`_captureReceiver`,null),h(this,`_participantIdRegistry`,null),h(this,`_disabledSenders`,new Set),h(this,`_rtpReceiversByStreamId`,{}),h(this,`_producerSessionId`,``),h(this,`_newAudioShareTrack`,null),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_statAggregator`,void 0),h(this,`_codecStatsAggregator`,void 0),h(this,`_simulcast`,void 0),this._debug=r,this._logger=i,this._statAggregator=a,this._codecStatsAggregator=o,this._serverSettings=n,this._simulcast=new ca(e,t,()=>this._serverSettings.camera,r,i),this.subscribe(this._signaling,G.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Yt.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Yt.SOURCE_CHANGED,this._onSourcesChanged.bind(this)),this.subscribe(this._mediaSource,Yt.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._createPerfStatsReporter(),this._debug.debug(`ServerTransport: Created`)}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==q.IDLE&&e!==q.CLOSED&&e!==q.FAILED&&this._startStatInterval()}open(e=!1){if(this._isOpen){this._debug.log(`ServerTransport: Already opened connections`);return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen&&(this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(this._debug.error(`ServerTransport: Closed`,e),this._setState(q.FAILED)):(this._debug.debug(`ServerTransport: Closed`),this._setState(q.CLOSED)))}removeParticipant(e){this._captureReceiver?.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){kr(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}setAnimojiTransport(e,t){if(M.vmoji&&(this._animojiReceiver=e,this._animojiSender=t,this._participantIdRegistry&&e.setParticipantIdRegistry(this._participantIdRegistry),this._animojiDataChannel)){e.setDataChannel(this._animojiDataChannel),t.setDataChannel(this._animojiDataChannel);return}}async onCameraResolutionChanged(){await this._simulcast.sync()}_createPerfStatsReporter(){this._perfStatReporter?.destroy(),this._perfStatReporter=new ga(this,this._signaling,this._statAggregator,!1,this._debug)}_closeConnection(){this._signaling.resetProducerConnection(),this._ssrcMap={},this._ssrcMapUpdated=!0,this._disposeFirstMediaSentProbe(),this._stopStatInterval(),this._stopSettingsInterval(),this._stopMonitorRtpShareInterval(),this._removeAsrTrack(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._simulcast.reset(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>e.track?.stop()),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,e._closeDataChannel(this._producerNotification),e._closeDataChannel(this._producerCommand),e._closeDataChannel(this._producerScreen),e._closeDataChannel(this._consumerScreen),e._closeDataChannel(this._asr),e._closeDataChannel(this._animojiDataChannel),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(Y.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,n){this._debug.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let e=r.readyState;e===`open`?(this._debug.debug(`[${t}] data channel opened`),n(r)):this._debug.error(`[${t}] data channel open failed, state [${e}]`)},r.onerror=e=>{let n=e.error;this._debug.error(`[${t}] data channel error`,n?.errorDetail,n?.message)}}_openConnection(e=!1){this._debug.debug(`ServerTransport: Open single connection`);try{this._pc=new RTCPeerConnection}catch(e){this._debug.error(`Failed to create RTCPeerConnection:`,e),this.close(e);return}this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=j.debounce(e=>{this._pc&&this._onConnectionStateChange(this._pc,e)},500),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this,this._pc),this._participantIdRegistry=new ei(this._debug),this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._createDataChannel(this._pc,wr.producerNotification,e=>{this._producerNotification=e,this._producerNotification.binaryType=`arraybuffer`,this._signaling.setProducerNotificationDataChannel(e)}),this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,wr.producerCommand,e=>{this._producerCommand=e,this._signaling.setProducerCommandDataChannel(e)}),this._createDataChannel(this._pc,wr.producerScreenShare,e=>{this._producerScreen=e,this._producerScreen.binaryType=`arraybuffer`,this._createCaptureReceiver()}),M.asrDataChannel&&this._createDataChannel(this._pc,wr.asr,e=>{this._asr=e,this._asr.binaryType=`arraybuffer`,this._removeAsrTrack(),this._asrTrack=new Zr(e,this._participantIdRegistry,e=>{this._onAsrTranscription(e)},this._debug)}),M.vmoji&&this._createDataChannel(this._pc,wr.animoji,e=>{this._animojiDataChannel=e,this._animojiDataChannel.binaryType=`arraybuffer`,this._animojiReceiver?.setDataChannel(e),this._animojiReceiver?.setParticipantIdRegistry(this._participantIdRegistry),this._animojiSender?.setDataChannel(e),this._animojiSender?.setProtocolVersion(M.vmojiOptions.protocolVersion||1)}),this._newAudioShareTrack=this._mediaSource.getAudioShareTrack();try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1),this._prevConsumerSettings={},this._prevConsumerFastSharingSettings={},this._applyConsumerSettings()}catch(e){this._debug.error(`ServerTransport: Unable to add media source tracks`,e),this._logger?.log(C.ERROR,`addTrack-single`),this.close(e);return}this._startFirstMediaSentProbe(),this._createDataChannel(this._pc,wr.consumerScreenShare,e=>{this._consumerScreen=e,this._consumerScreen.binaryType=`arraybuffer`;let t=this._mediaSource.getScreenTrack();t&&(!M.consumerFastScreenShare||!this._mediaSource.mediaSettings.isFastScreenSharingEnabled)&&this._createCaptureSender(t)}),e||this._allocateConsumer(),this._setState(q.OPENED),this._startStatInterval(),this._startSettingsInterval(),this._startMonitorRtpShareInterval()}_removeAsrTrack(){this._asrTrack?.destroy(),this._asrTrack=null}_reconnect(){this.getState()!==q.OPENED&&(this._setState(q.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(Y.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(Y.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(Y.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(Y.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&(this._ssrcMap={},this._ssrcMapUpdated=!0,dn(e.sdp).forEach(e=>{let t=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Yr.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+)|(?:${Yr.TRANSPARENT_AUDIO_TRACK_PREFIX}-[0-9]+))`,n=new RegExp(t).exec(e);n&&(this._ssrcMap[n[1]]=n[3])}))}_createCaptureSender(e){let t=this._mediaSource.mediaSettings;!e||!this._consumerScreen||!t.isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new sa(e,this._consumerScreen,this._signaling,t.isFastScreenSharingEnabled,this._debug,this._logger))}_removeCaptureSender(){this._captureSender?.destroy(),this._captureSender=null}_createCaptureReceiver(){this._producerScreen&&(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new Ni(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(Y.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(Y.REMOTE_STREAM_SECOND,e,null)},e=>{this._triggerEvent(Y.SCREEN_SHARING_STAT,e)},this._statAggregator,this._debug,this._logger))}_removeCaptureReceiver(){this._captureReceiver?.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(n=>{if(!n.track||n.track.kind!==k.video||n.track.contentHint===`motion`)return;let r=!this._disabledSenders.has(n),i=e.maxDimension!==0;if(r&&!i){this._debug.log(`Disabling video upload`),this._disabledSenders.add(n),n.replaceTrack(T.getBlackMediaTrack()).catch(e=>{this._debug.error(`Could not disable video upload`,e)});return}let a=this._mediaSource.getSendVideoTrack();if(!r&&i&&a){this._debug.log(`Enabling video upload`),this._disabledSenders.delete(n);let e=n.track;e.enabled=a.enabled,n.replaceTrack(a).then(()=>e.stop()).catch(e=>{this._debug.error(`Could not enable video upload`,e)})}j.applyVideoTrackSettings(e,n,a??n.track,this._prevConsumerSettings,t,this._debug)}),this._prevConsumerSettings=t}if(this._mediaSource.mediaSettings.isFastScreenSharingEnabled&&M.consumerFastScreenShare){let e=this._serverSettings.fastScreenSharing;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(n=>{!n.track||n.track.kind!==k.video||n.track.contentHint!==`motion`||j.applyVideoTrackSettings(e,n,n.track,this._prevConsumerFastSharingSettings,t,this._debug)}),this._prevConsumerFastSharingSettings=t}}}_onScreenSharingStatus(e){e.track?(!M.consumerFastScreenShare||!this._mediaSource.mediaSettings.isFastScreenSharingEnabled)&&this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(Y.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(e=>{this._reportStats(e),this._detectStaleTracks(e),this._codecStatsAggregator?.reportUsage(e)}).catch(()=>{}),this._statInterval=window.setTimeout(e,M.statisticsInterval)};this._statInterval=window.setTimeout(e,M.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)}async _collectStat(){if(!this._pc)return Promise.reject();this._ssrcMapUpdated&&(this._lastStat=null,this._ssrcMapUpdated=!1,this._createPerfStatsReporter());let e=await W.collectStats(this._pc,this._lastStat,this._ssrcMap,!0);return this._lastStat=e,e}_reportStats(e){this._triggerEvent(Y.REMOTE_DATA_STATS,{inbound:{topology:J.SERVER,transport:e.transport,rtps:e.rtps.filter(e=>e.type===`inbound-rtp`)},outbound:{topology:J.SERVER,transport:e.transport,rtps:e.rtps.filter(e=>e.type===`outbound-rtp`)},remoteInbound:{topology:J.SERVER,transport:e.transport,rtps:e.remoteRtps??[]}})}_detectStaleTracks(e){let t=e.rtps.find(e=>e.type===`inbound-rtp`&&e.kind===`audio`&&this._ssrcMap[e.ssrc]===`mix`);if(!t)return;let n=Yr.AUDIO_MIX,r=this._statBytes[n],i=!1;if(r){let e=t.bytesReceived-r.bytesReceived;e>=0&&e<=5&&(i=!0),r.stalled!==i&&this._triggerEvent(Y.AUDIO_MIX_STALL,i)}this._statBytes[n]={bytesReceived:t.bytesReceived,stalled:i}}_allocateConsumer(){if(!this._signaling.ready)return;let e=Sa.get();!M.videoTracksCount&&!this._observer&&this._debug.warn(`Setting videoTracksCount to 0 is deprecated`),this._signaling.allocateConsumer(null,e).catch(e=>{e instanceof En||this._debug.warn(`ServerTransport: Unable to allocate consumer`,e)})}async _processOffer(e,t){if(!this._pc)throw Error(`Interrupt allocation`);try{await this._pc.setRemoteDescription(e)}catch(e){throw this._debug.error(`[single] unable to set remote offer`,e),this._logger?.log(C.ERROR,`setRemoteDescription-single`),e}await this._simulcast.configureFromRemoteOffer(this._pc);let n;try{if(await this._handleTracks(),this._debug.debug(`[single] create local answer`),!this._pc)throw Error(`Interrupt allocation`);n=await this._pc.createAnswer()}catch(e){throw this._debug.error(`[single] unable to create answer`,e),this._logger?.log(C.ERROR,`createAnswer-single`),e}try{if(!this._pc)throw Error(`Interrupt allocation`);n.sdp=j.patchLocalSDP(n.sdp,!1,T.isBrokenH264Decoder(),!1),this._debug.debug(`[single] set local answer`,{answer:n}),await this._pc.setLocalDescription(n)}catch(e){throw this._debug.error(`[single] unable to set local answer`,e),this._logger?.log(C.ERROR,`setLocalDescription-single`),e}n.sdp=this._simulcast.finalizeAnswer(n.sdp);try{this._debug.debug(`[single] transmit local answer`,{answer:n}),this._updateSSRCMap(e),await this._signaling.acceptProducer(n,Object.keys(this._ssrcMap),t),this._debug.debug(`[single] remote offer has been processed`)}catch(e){this._debug.warn(`[single] unable to send local answer`,e),this._logger?.log(C.ERROR,`acceptProducer`)}await this._simulcast.sync({force:!0})}async _acceptProducer(e,t){if(this._producerOfferIsProcessing){this._producerNextOffer=e,this._producerNextSessionId=t,this._debug.debug(`[single] wait until other remote offer is processed`);return}this._producerOfferIsProcessing=!0;let n={type:`offer`,sdp:j.patchRemoteSDP(e,!1,!1,!1,T.isBrokenVP9Encoder(),T.isBrokenVP9Decoder())};if(this._debug.debug(`[single] set remote offer`,{offer:n}),!this._pc)throw Error(`Interrupt allocation`);try{if(await this._processOffer(n,t),this._producerOfferIsProcessing=!1,this._producerNextOffer&&this._producerNextSessionId){this._debug.debug(`[single] there is other unprocessed remote offer, process it`);let e=this._producerNextOffer,t=this._producerNextSessionId;this._producerNextOffer=null,this._producerNextSessionId=null,await this._acceptProducer(e,t)}}catch(e){this.close(e)}}async _replaceScreenShareTrack(){let e=this._pc?.getTransceivers().find(e=>e.mid?.endsWith(`s`)&&e?.receiver?.track.kind===k.video);if(!e||!e.sender){this._debug.warn(`Cannot find screenshare transceiver`);return}try{e.direction=`sendonly`,await e.sender.replaceTrack(this._mediaSource.getScreenShareTrack())}catch(e){this._debug.error(`ServerTransport: Unable to replace track`,e)}}async _handleTracks(){this._observer||(await this._handleAudioShareTrack(),await this._handleScreenShareTrack())}async _handleAudioShareTrack(){if(!this._newAudioShareTrack)return;let e=this._pc?.getTransceivers().find(e=>e.mid?.endsWith(`s`)&&e?.receiver?.track.kind===k.audio);if(!e||!e.sender){this._debug.warn(`Cannot find audioshare transceiver`);return}e.sender.track!==null&&this._debug.warn(`Unexpected track assigned to audioshare`);try{e.direction=`sendonly`,await e.sender.replaceTrack(this._newAudioShareTrack),this._newAudioShareTrack=null}catch(e){this._debug.error(`ServerTransport: Unable to replace track`,e),this._logger?.log(C.ERROR,`replaceTrack-single`)}}async _handleScreenShareTrack(){this._mediaSource.getScreenShareTrack()&&await this._replaceScreenShareTrack()}async _onSignalingNotification(e){if(this._isOpen)switch(e.notification){case K.PRODUCER_UPDATED:await this._onProducerUpdated(e);break;case K.REALLOC_CON:this._reconnect();break;case K.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case K.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case K.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case K.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}}_onAsrTranscription(e){this._triggerEvent(Y.ASR_TRANSCRIPTION,e)}async _onProducerUpdated(e){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),M.breakVideoPayloadTypes&&(this._debug.log(`test mode enabled, video switched off`),this._signaling.requestTestMode(`breakVideoPayloadTypes`,null).catch(e=>{e instanceof En||this._debug.warn(`Unable to enable signaling test mode`,e)})),this._producerSessionId=e.sessionId,await this._acceptProducer(e.description,e.sessionId)}_onAddTrack(e,t){this._debug.debug(`[single] remote track (added)`,{track:t.track});let n=t.streams[0];n?(n.onremovetrack||(n.onremovetrack=e=>{this._triggerEvent(Y.REMOTE_TRACK_REMOVED,n.id,n,e.track)}),n.getTracks().find(e=>e.id===t.track.id)||(this._debug.warn(`[single] remote track missing from stream, re-adding`,{streamId:n.id,trackId:t.track.id}),this._logger?.log(C.ERROR,`ontrack-empty-stream`),n.addTrack(t.track)),this._rtpReceiversByStreamId[n.id]=t.receiver,this._triggerEvent(Y.REMOTE_TRACK_ADDED,n.id,n,t.track)):this._debug.error(`[single] unable to get media stream from track event`)}_onSignalingStateChange(e,t){this._debug.debug(`[single] signaling state changed`,{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(this._debug.debug(`[single] connection state changed`,{state:e.connectionState},t),this._logger?.log(C.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case`failed`:this._reconnectionPrevented?this.close(Error(`Ice connection failed`)):this._reconnect();break;case`connecting`:let t=this.getState();t===q.IDLE||t===q.OPENED?this._setState(q.CONNECTING):e.iceConnectionState===`checking`&&this._setState(q.RECONNECTING);break;case`disconnected`:this._reconnectionPrevented?this.close(Error(`Ice connection disconnected`)):this._setState(q.RECONNECTING);break;case`connected`:this._setState(q.CONNECTED),j.getPeerConnectionHostInfo(e).then(e=>{e?.local&&(this._logger?.log(C.ICE_CONNECTION_TYPE,e.local.type),this._debug.debug(`Selected ICE candidates`,e))});break}}_onReplacedTrack(e,t){if(this._pc){this._debug.debug(`_onReplacedTrack: newTrack=${e}, sendTrack=${t}`),t&&(e=t);let n=(e,t)=>{e.replaceTrack(t).catch(e=>{this._debug.error(`ServerTransport: Unable to replace track`,e),this._logger?.log(C.ERROR,`replaceTrack-single`)})};if(this._debug.log(`_onReplacedTrack: newTrack=${e.getSettings().width}x${e.getSettings().height}`),!this._simulcast.replaceTrack(e)){let t=this._pc?.getSenders().find(t=>t.track&&t.track.kind===e.kind&&!this._disabledSenders.has(t)&&t.track.contentHint===e.contentHint);t?.track?n(t,e):e.kind===k.audio&&e.contentHint===`music`&&(this._newAudioShareTrack=e)}}this._applyConsumerSettings()}async _onSourcesChanged({kind:e}){e===k.screen&&M.consumerFastScreenShare&&this._mediaSource.mediaSettings.isFastScreenSharingEnabled&&await this._replaceScreenShareTrack(),this._applyConsumerSettings()}getStreamWaitingTimeMs(e,t){if(!this._pc)return this._logger?.log(C.PAT_WAITING_TIME_ERROR,`noConnection`),this._debug.error(`Cannot get stream waiting time, peer connection is not initialized`),0;if(!RTCRtpReceiver.prototype.getSynchronizationSources)return this._logger?.log(C.PAT_WAITING_TIME_ERROR,`oldBrowser`),this._debug.error(`Cannot get stream waiting time, RTCRtpReceiver.getSynchronizationSources is not supported`),0;let n=this._rtpReceiversByStreamId[e];if(!n)return this._logger?.log(C.PAT_WAITING_TIME_ERROR,`noReceiver`),this._debug.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=n.getSynchronizationSources();if(!r||!r.length)return this._debug.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let i=r[0].rtpTimestamp;if(!Number.isInteger(i))return this._logger?.log(C.PAT_WAITING_TIME_ERROR,`timestampNotInteger`),this._debug.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${i}`),0;let a=t-i&ua,o=Math.ceil(a/la);return Math.min(100,Math.max(0,o))}async _monitorRtpShare(){let e=$r.getInstance().value;if(!this._mediaSource.mediaSettings.isFastScreenSharingEnabled||!M.consumerFastScreenShare||e<.6)return;let t=this._pc?.getSenders().find(e=>e.track?.kind===k.video&&e.track?.contentHint===`motion`);t&&(await t.getStats()).forEach(e=>{if(e.type===`outbound-rtp`&&this._serverSettings.fastScreenSharing&&e.frameWidth<this._serverSettings.fastScreenSharing.maxDimension&&e.frameWidth<window.screen.width){let n=t.getParameters();n.degradationPreference=`maintain-resolution`,t.setParameters(n),this._debug.log(`
|
|
10
10
|
degradationPreference updated for fast share RTP Sender
|
|
11
11
|
Actual senderStats: ${JSON.stringify(e)}
|
|
12
12
|
serverSettings: ${JSON.stringify(this._serverSettings.fastScreenSharing)}
|
|
13
|
-
`)}})}_startMonitorRtpShareInterval(){let e=5e3;if(this._monitorRtpShareInterval)return;let t=()=>{if(!this._pc){this._stopMonitorRtpShareInterval();return}this._monitorRtpShare(),this._monitorRtpShareInterval=window.setTimeout(t,e)};this._monitorRtpShareInterval=window.setTimeout(t,e)}_stopMonitorRtpShareInterval(){this._monitorRtpShareInterval&&(window.clearTimeout(this._monitorRtpShareInterval),this._monitorRtpShareInterval=null)}},Y=function(e){return e.REMOTE_TRACK_ADDED=`REMOTE_TRACK_ADDED`,e.REMOTE_TRACK_REMOVED=`REMOTE_TRACK_REMOVED`,e.REMOTE_STREAM_SECOND=`REMOTE_STREAM_SECOND`,e.AUDIO_MIX_STALL=`AUDIO_MIX_STALL`,e.REMOTE_DATA_STATS=`REMOTE_DATA_STATS`,e.STATE_CHANGED=`STATE_CHANGED`,e.LOCAL_STATE_CHANGED=`LOCAL_STATE_CHANGED`,e.SIGNALLED_ACTIVE_PARTICIPANTS=`SIGNALLED_ACTIVE_PARTICIPANTS`,e.SIGNALLED_SPEAKER_CHANGED=`SIGNALLED_SPEAKER_CHANGED`,e.SIGNALLED_STALLED_PARTICIPANTS=`SIGNALLED_STALLED_PARTICIPANTS`,e.TOPOLOGY_CHANGED=`TOPOLOGY_CHANGED`,e.NETWORK_STATUS=`NETWORK_STATUS`,e.PEER_CONNECTION_CLOSED=`PEER_CONNECTION_CLOSED`,e.ASR_TRANSCRIPTION=`ASR_TRANSCRIPTION`,e.ANIMOJI_STREAM=`ANIMOJI_STREAM`,e.ANIMOJI_ERROR=`ANIMOJI_ERROR`,e.SCREEN_SHARING_STAT=`SCREEN_SHARING_STAT`,e}({}),ma=class extends b{constructor(e,t,n,r,i=z,a=null,o=null,s=null,c=null){super(),h(this,`_signaling`,void 0),h(this,`_mediaSource`,void 0),h(this,`_topology`,void 0),h(this,`_allocated`,[]),h(this,`_opened`,[]),h(this,`_directTransport`,null),h(this,`_serverTransport`,null),h(this,`_serverSettings`,void 0),h(this,`_dtListeners`,[]),h(this,`_stListeners`,[]),h(this,`_states`,{}),h(this,`_localState`,q.IDLE),h(this,`_animojiReceiver`,null),h(this,`_animojiSender`,null),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_statAggregator`,void 0),h(this,`_codecStatsAggregator`,void 0),h(this,`_onFirstMediaSent`,void 0),h(this,`_firstMediaSentProbeStopped`,!1),h(this,`_vadController`,null),h(this,`_updateVadTrack`,()=>{this._vadController?.setSendTrack(this._mediaSource.getSendAudioTrack())}),this._signaling=t,this._mediaSource=n,this._topology=e,this._serverSettings=r,this._debug=i,this._logger=a,this._statAggregator=o,this._codecStatsAggregator=s,this._onFirstMediaSent=c,this.subscribe(this._signaling,Sr.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Jt.ANIMOJI_STATUS,this._onAnimojiStatus.bind(this)),this.subscribe(this._mediaSource,Jt.SOURCE_CHANGED,this._onSourceChanged.bind(this)),this.subscribe(this._mediaSource,Jt.SOURCE_READY,this._updateVadTrack),this._createVad(),this._createAnimojiTransport(),e===J.SERVER&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._debug.log(`Update transport settings`,e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._debug.log(`Trying allocate participant [${e}]`),this._allocated.indexOf(e)!==-1){this._debug.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology===J.DIRECT&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology===J.SERVER&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,n=!1,r=!1){this._debug.log(`Trying open participant`,{participantIds:e});let i=r;for(let t of e){if(this._opened.indexOf(t)!==-1){this._debug.warn(`The participant [${t}] has already had opened transport`);continue}if(this._allocated.indexOf(t)===-1){this._debug.warn(`The participant [${t}] has no allocated transport`);continue}this._opened.push(t),i=!0}i&&(this._topology===J.DIRECT&&this._directTransport&&this._directTransport.open(t),this._topology===J.SERVER&&this._serverTransport&&(this._serverTransport.open(n),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),this._debug.debug(`The transport has been opened`,e))}close(e){let t=this._allocated.indexOf(e),n=this._opened.indexOf(e);t<0&&this._debug.warn(`The participant [${e}] transport has already deallocated`),this._topology===J.DIRECT&&this._directTransport&&n>=0&&this._releaseDirectTransport(),this._topology===J.SERVER&&(this._serverTransport?.removeParticipant(e),this._setStates([e],q.CLOSED)),n>=0&&this._opened.splice(n,1),t>=0&&this._allocated.splice(t,1),delete this._states[e]}destroy(){this.stopFirstMediaSentProbe(),this.unsubscribe();for(let e of this._dtListeners)e.dispose();for(let e of this._stListeners)e.dispose();this._removeAnimojiTransport(),N.audioEffects?.destroy(),this._vadController?.destroy(),this._vadController=null,this._directTransport?.close(),this._directTransport=null,this._serverTransport?.close(),this._serverTransport=null,this._allocated=[],this._opened=[]}stopFirstMediaSentProbe(){this._firstMediaSentProbeStopped||(this._firstMediaSentProbeStopped=!0,this._directTransport?.stopFirstMediaSentProbe(),this._serverTransport?.stopFirstMediaSentProbe())}holdClose(){this.unsubscribe();for(let e of this._dtListeners)e.dispose();for(let e of this._stListeners)e.dispose();this._vadController?.destroy(),this._vadController=null,this._directTransport?.close(),this._directTransport=null,this._serverTransport?.close(),this._serverTransport=null,this._allocated=[],this._opened=[]}setRemoteHold(e){this._directTransport?.setRemoteHold(e)}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}getState(){return this._topology===J.SERVER?this._serverTransport?.getState():this._directTransport?.getState()}getStates(){return this._states}setAnimojiSvg(e,t){N.vmoji&&t.isMe&&N.vmoji.AnimojiPreviewGenerator?.setSvgData(t),(!(t.svg instanceof ArrayBuffer)||t.svg.byteLength!==0)&&this._animojiReceiver?.setParticipantSvg(e,t)}setAnimojiFill(e){this._animojiSender?.setFill(e)}async onCameraResolutionChanged(){this._topology===J.SERVER&&this._serverTransport&&await this._serverTransport.onCameraResolutionChanged()}_setStates(e,t){let n=e.filter(e=>this._states[e]===t?!1:(this._states[e]=t,!0));n.length&&this._triggerEvent(`STATE_CHANGED`,n,t)}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent(`LOCAL_STATE_CHANGED`,e))}_onSignalingNotification(e){if(e.notification===K.TOPOLOGY_CHANGED)return this._onTopologyChanged(e)}_handleFirstMediaSent(){this._firstMediaSentProbeStopped||(this.stopFirstMediaSentProbe(),this._onFirstMediaSent?.())}_getFirstMediaSentCallback(){return!this._onFirstMediaSent||this._firstMediaSentProbeStopped?null:this._handleFirstMediaSent.bind(this)}_onTopologyChanged(e){if(e.topology!==this._topology){if(this._debug.log(`Topology changed ${this._topology} -> ${e.topology}`),this._logger?.log(C.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology===J.SERVER&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&(this._directTransport?.preventRestart(),this._serverTransport.open()))),this._topology===J.DIRECT){let t=e.offerTo||[],n=e.offerToTypes||[],r=e.offerToDeviceIdxs||[],i=t.length&&n.length?M.composeParticipantId(t[0],n[0],r[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){this._debug.error(`Topology changed to DIRECT, but the list of allocated participants is empty`);return}this._allocated.length>1&&this._debug.warn(`Topology changed to DIRECT, but the allocated participants count more then one`);let a=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let e=i===a;this._directTransport=this._createDirectTransport(a,e)}this._opened.indexOf(a)>=0&&this._directTransport.open()}this._triggerEvent(`TOPOLOGY_CHANGED`,this._topology)}}_createDirectTransport(e,t=!1){let n=new Xr(e,t,this._signaling,this._mediaSource,this._serverSettings,this._debug,this._logger,this._statAggregator,this._codecStatsAggregator,this._getFirstMediaSentCallback());return this._dtListeners.length>0&&this._debug.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(n.addEventListener(`REMOTE_TRACK_ADDED`,this._onRemoteTrackAdded.bind(this,e)),n.addEventListener(`REMOTE_TRACK_REMOVED`,this._onRemoteTrackRemoved.bind(this,e)),n.addEventListener(`REMOTE_DATA_STATS`,this._onRemoteDataStats.bind(this)),n.addEventListener(`STATE_CHANGED`,this._onDirectTransportChanged.bind(this)),n.addEventListener(`NETWORK_STATUS`,this._onTransportNetworkStatus.bind(this)),n.addEventListener(`PEER_CONNECTION_CLOSED`,this._onPeerConnectionClosed.bind(this,J.DIRECT))),this._animojiReceiver&&this._animojiSender&&n.setAnimojiTransport(this._animojiReceiver,this._animojiSender),n}_createServerTransport(){let e=new pa(this._signaling,this._mediaSource,this._serverSettings,this._debug,this._logger,this._statAggregator,this._codecStatsAggregator,this._getFirstMediaSentCallback());return this._stListeners.length>0&&this._debug.warn(`The list of server transport listeners is not empty`),this._stListeners=[],this._stListeners.push(e.addEventListener(`REMOTE_TRACK_ADDED`,this._onRemoteTrackAdded.bind(this)),e.addEventListener(`REMOTE_TRACK_REMOVED`,this._onRemoteTrackRemoved.bind(this)),e.addEventListener(`AUDIO_MIX_STALL`,this._onServerAudioMixStall.bind(this)),e.addEventListener(`REMOTE_DATA_STATS`,this._onRemoteDataStats.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,J.SERVER)),e.addEventListener(`ASR_TRANSCRIPTION`,this._onAsrTranscription.bind(this))),this._animojiReceiver&&this._animojiSender&&e.setAnimojiTransport(this._animojiReceiver,this._animojiSender),e}_releaseDirectTransport(){this._directTransport?.close(),this._directTransport=null;for(let e of this._dtListeners)e.dispose();this._dtListeners=[]}_releaseServerTransport(){this._serverTransport?.close(),this._serverTransport=null;for(let e of this._stListeners)e.dispose();this._stListeners=[]}_onDirectTransportChanged(e){let t=this._directTransport?.participantId;if(e===q.CONNECTED&&this._topology===J.DIRECT&&this._releaseServerTransport(),(e===q.CLOSED||e===q.FAILED)&&(this._releaseDirectTransport(),this._topology===J.DIRECT)){let e=this._opened.indexOf(t);e>=0&&this._opened.splice(e,1);let n=this._allocated.indexOf(t);n>=0&&this._allocated.splice(n,1)}this._topology===J.DIRECT&&t&&(this._setStates([t],e),this._setLocalState(e))}_onServerTransportChanged(e){let t=this._opened.slice();e===q.CONNECTED&&this._topology===J.SERVER&&this._releaseDirectTransport(),(e===q.CLOSED||e===q.FAILED)&&(this._releaseServerTransport(),this._topology===J.SERVER&&(this._allocated=[],this._opened=[])),this._topology===J.SERVER&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology===J.SERVER&&this._triggerEvent(`SIGNALLED_ACTIVE_PARTICIPANTS`,e)}_onTransportStalledParticipants(e){this._topology===J.SERVER&&this._triggerEvent(`SIGNALLED_STALLED_PARTICIPANTS`,e)}_onTransportSpeakerChanged(e){this._topology===J.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)}_onServerAudioMixStall(e){this._topology===J.SERVER&&this._triggerEvent(`AUDIO_MIX_STALL`,e)}_onRemoteDataStats(e){this._triggerEvent(`REMOTE_DATA_STATS`,e)}_onRemoteTrackAdded(e,t,n){this._triggerEvent(`REMOTE_TRACK_ADDED`,e,t,n)}_onRemoteTrackRemoved(e,t,n){this._triggerEvent(`REMOTE_TRACK_REMOVED`,e,t,n)}_onAsrTranscription(e){this._triggerEvent(`ASR_TRANSCRIPTION`,e)}_onSourceChanged(e){let t=this._mediaSource.getStream();t&&this._animojiSender?.setStream(t),(!e||e.kind===A.audio)&&this._updateVadTrack()}_onAnimojiStream(e,t){this._triggerEvent(`ANIMOJI_STREAM`,e,t)}_onAnimojiStatus(e){e?this._animojiSender?.resume():this._animojiSender?.pause(),this._mediaSource.onAnimojiSender(e)}_createVad(){N.vad&&(this._vadController=new N.vad.VadController(this._mediaSource.getSendAudioTrack(),N.vadOptions),this._vadController.setLogger((e,...t)=>z.send(e,...t),`VAD`),this._vadController.init().catch(e=>{z.warn(`[Transport] VAD init failed, continuing without VAD`,e),this._vadController?.destroy(),this._vadController=null}))}_createAnimojiTransport(){if(!N.vmoji)return;this._animojiReceiver=new N.vmoji.AnimojiReceiver((e,t)=>this._onAnimojiStream(e,t),e=>this._onAnimojiStream(e,null),e=>{this._triggerEvent(`ANIMOJI_ERROR`,e)},N.vmojiOptions.renderingOptions);let e=this._mediaSource.getStream();this._animojiSender=new N.vmoji.AnimojiSender(e,this._signaling.getPeerId(),N.vmojiOptions.protocolVersion,{requested:this._mediaSource.isAnimojiRequested,useAI:N.vmojiOptions.renderingOptions.useAI}),this._animojiSender.onLocalData=e=>this._animojiReceiver?.receive(e)}_removeAnimojiTransport(){this._animojiSender?.destroy(),this._animojiSender=null,this._animojiReceiver?.destroy(),this._animojiReceiver=null}getStreamWaitingTimeMs(e,t){return this._topology===J.SERVER?this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(this._logger?.log(C.PAT_WAITING_TIME_ERROR,`noTransport`),this._debug.error(`Cannot get stream waiting time, server transport is not initialized`),0):(this._logger?.log(C.PAT_WAITING_TIME_ERROR,`wrongTopology`),this._debug.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0)}},ha=`videochat-epi`,ga=5e3,_a=500,va=class extends b{constructor(e,t,n=null,r=!1,i=z){super(),h(this,`_previousPerfStatReportTimestamp`,0),h(this,`_previousNetworkStatReportTimestamp`,Date.now()),h(this,`_previousCallStatReportTimestamp`,Date.now()),h(this,`_previousCallStatReport`,null),h(this,`_previousRemoteInboundRtps`,new Map),h(this,`_screenShareStats`,[]),h(this,`_signaling`,void 0),h(this,`_directTopology`,void 0),h(this,`_debug`,void 0),h(this,`_statAggregator`,void 0),h(this,`_handleScreenSharingStat`,e=>{this._screenShareStats.push(e)}),h(this,`_handleTransportStateChanged`,e=>{(this._directTopology&&e===q.CONNECTED||!this._directTopology&&e===q.OPENED)&&(this._previousNetworkStatReportTimestamp=Date.now(),this._previousCallStatReportTimestamp=Date.now(),this._previousRemoteInboundRtps.clear())}),this._signaling=t,this._directTopology=r,this._debug=i,this._statAggregator=n,this.subscribe(e,Y.REMOTE_DATA_STATS,this._handleStats.bind(this)),this.subscribe(e,Y.SCREEN_SHARING_STAT,this._handleScreenSharingStat.bind(this)),this.subscribe(e,Y.STATE_CHANGED,this._handleTransportStateChanged.bind(this))}destroy(){this._previousRemoteInboundRtps.clear(),this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(ha)||``,10);return isNaN(e)?0:e}catch{return 0}}async _handleStats(e){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&N.perfStatReportEnabled&&this._previousPerfStatReportTimestamp+ga<=t&&(await this.reportPerfStats(e),this._previousPerfStatReportTimestamp=t);let n=e.outbound.transport.local?.protocol===`tcp`;!this._directTopology&&n&&this._previousNetworkStatReportTimestamp+_a<=t&&(await this.reportNetworkStats(e),this._previousNetworkStatReportTimestamp=t),N.callStatReportEnabled&&this._previousCallStatReportTimestamp+N.statisticsInterval<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)}async reportPerfStats(e){let t=e.inbound.rtps.reduce((e,t)=>(t.kind===`video`&&(e.framesDecoded+=t.framesDecoded||0,e.framesReceived+=t.framesReceived||0),e),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let e=await this._signaling.reportPerfStat(t);localStorage.setItem(ha,e.estimatedPerformanceIndex)}catch{}}async reportNetworkStats(e){let t={timestamp:e.outbound.transport.timestamp,sendBitrate:e.outbound.rtps.reduce((e,t)=>e+(t.bandwidth??0)*8,0)};if(t.timestamp)try{await this._signaling.reportNetworkStat(t)}catch{}}_reportCallStats(e){let t={call_topology:this._directTopology?`D`:`S`,stat_time_delta:0,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,freeze_count:0,total_freezes_duration:0,rtt:Math.round(e.inbound.transport.currentRoundTripTime*1e3),ss_freeze_count:0,ss_total_freezes_duration:0,local_address:ba(e.inbound.transport.local),local_connection_type:e.inbound.transport.local?.type,network_type:e.inbound.transport.local?.networkType,transport:e.inbound.transport.local?.protocol,remote_address:ba(e.inbound.transport.remote),remote_connection_type:e.inbound.transport.remote?.type};this._previousCallStatReport||(this._previousCallStatReport=Object.assign({},t));let n=!1,r=!1;for(e.inbound.rtps.reduce((e,t)=>(t.kind===`video`?(n=!0,t.framesReceived&&(e.jitter_video=e.jitter_video*e.inbound_video_count/(e.inbound_video_count+1)+t.jitter*1e3/(e.inbound_video_count+1),e.interframe_delay_variance=e.interframe_delay_variance*e.inbound_video_count/(e.inbound_video_count+1)+(t.interframeDelayVariance||0)*1e6/(e.inbound_video_count+1),e.inbound_video_count++),e.frames_dropped+=t.framesDropped||0,e.nack_sent+=t.nackCount,e.pli_sent+=t.pliCount,e.fir_sent+=t.firCount,e.freeze_count+=t.freezeCountDelta||0,e.total_freezes_duration+=t.totalFreezesDurationDelta||0):(r=!0,t.totalSamplesReceived&&(e.jitter_audio=e.jitter_audio*e.inbound_audio_count/(e.inbound_audio_count+1)+t.jitter*1e3/(e.inbound_audio_count+1),e.total_audio_energy=e.total_audio_energy*e.inbound_audio_count/(e.inbound_audio_count+1)+(t.totalAudioEnergy||0)/(e.inbound_audio_count+1),e.inbound_audio_count++),e.total_audio_samples_received+=t.totalSamplesReceived||0,e.inserted_audio_samples_for_deceleration+=t.insertedSamplesForDeceleration||0,e.removed_audio_samples_for_acceleration+=t.removedSamplesForAcceleration||0,e.concealed_audio_samples+=t.concealedSamples||0,e.silent_concealed_audio_samples+=t.silentConcealedSamples||0,e.audio_concealment_events+=t.concealmentEvents||0),e),t),e.outbound.rtps.reduce((e,t)=>(t.kind===`video`&&(e.nack_received+=t.nackCount,e.pli_received+=t.pliCount,e.fir_received+=t.firCount),e),t);this._screenShareStats.length;){let e=this._screenShareStats.pop();e?.freeze_duration&&(t.ss_freeze_count+=1,t.ss_total_freezes_duration+=e.freeze_duration)}let i={call_topology:t.call_topology,stat_time_delta:Math.max(0,Date.now()-this._previousCallStatReportTimestamp),nack_sent:Math.max(0,t.nack_sent-this._previousCallStatReport.nack_sent),nack_received:Math.max(0,t.nack_received-this._previousCallStatReport.nack_received),pli_sent:Math.max(0,t.pli_sent-this._previousCallStatReport.pli_sent),pli_received:Math.max(0,t.pli_received-this._previousCallStatReport.pli_received),fir_sent:Math.max(0,t.fir_sent-this._previousCallStatReport.fir_sent),fir_received:Math.max(0,t.fir_received-this._previousCallStatReport.fir_received),frames_dropped:Math.max(0,t.frames_dropped-this._previousCallStatReport.frames_dropped),rtt:Math.max(0,t.rtt)};if(N.simulcast&&(i.is_simulcast=!0),navigator.hardwareConcurrency&&(i.cpu_hardware_concurrency=navigator.hardwareConcurrency),n&&!xa(t.jitter_video)&&(i.jitter_video=Math.round(t.jitter_video)),r&&!xa(t.jitter_audio)&&(i.jitter_audio=Math.round(t.jitter_audio)),n&&!xa(t.interframe_delay_variance)&&(i.interframe_delay_variance=t.interframe_delay_variance),t.freeze_count&&t.total_freezes_duration&&(i.freeze_count=t.freeze_count,i.total_freezes_duration=Math.round(t.total_freezes_duration*1e3)),t.ss_freeze_count&&t.ss_total_freezes_duration&&(i.ss_freeze_count=t.ss_freeze_count,i.ss_total_freezes_duration=t.ss_total_freezes_duration),r&&!xa(t.total_audio_samples_received)){let e=Math.max(0,t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received),n=Math.max(0,t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration),r=Math.max(0,t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration),a=Math.max(0,t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples),o=Math.max(0,t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples),s=Math.max(0,t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events);i.inserted_audio_samples_for_deceleration=Sa(n/e*1e3),i.removed_audio_samples_for_acceleration=Sa(r/e*1e3),i.concealed_audio_samples=Sa(a/e*1e3),i.concealed_silent_audio_samples=Sa(o/e*1e3),i.concealment_audio_avg_size=Sa(a/s),i.total_audio_energy=t.total_audio_energy}ya(t,`local_address`,`local_connection_type`,`network_type`,`transport`)&&(i.local_address=t.local_address,i.local_connection_type=t.local_connection_type,i.network_type=t.network_type,i.transport=t.transport),ya(t,`remote_address`,`remote_connection_type`)&&(i.remote_address=t.remote_address,i.remote_connection_type=t.remote_connection_type);let a=this._calculatePacketLoss(e.remoteInbound.rtps);a.video!==void 0&&(i.video_loss=a.video),a.audio!==void 0&&(i.audio_loss=a.audio),this._statAggregator?.logCallStat(i),N.enableLogPerfStatReport&&this._debug.log(`Sent call stats`,i),this._previousCallStatReport=t}_calculatePacketLoss(e){let t=new Map,n={audio:{lost:0,received:0},video:{lost:0,received:0}};for(let r of e){if(r.kind!==`audio`&&r.kind!==`video`)continue;let e=`${r.kind}:${r.ssrc}`,i={packetsLost:r.packetsLost,packetsReceived:r.packetsReceived},a=this._previousRemoteInboundRtps.get(e);t.set(e,i),a&&(n[r.kind].lost+=Math.max(0,i.packetsLost-a.packetsLost),n[r.kind].received+=Math.max(0,i.packetsReceived-a.packetsReceived))}this._previousRemoteInboundRtps=t;let r={};for(let e of[`audio`,`video`]){let{lost:t,received:i}=n[e];t+i>0&&(r[e]=t/(t+i)*100)}return r}};function ya(e,...t){for(let n of t)if(!Object.hasOwn(e,n)||e[n]===void 0)return!1;return!0}function ba(e,t=!1){if(e?.address)return e.address+(t?`:${e.port}`:``)}function xa(e){return e===void 0}function Sa(e){return Number.isNaN(e)?0:e}var Ca;(function(e){function t(){return{estimatedPerformanceIndex:va.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:8,producerCommandDataChannelVersion:3,consumerScreenDataChannelVersion:1,producerScreenDataChannelVersion:1,asrDataChannelVersion:+!!N.asrDataChannel,animojiDataChannelVersion:N.vmoji?N.vmojiOptions.protocolVersion:1,animojiBackendRender:!N.vmojiOptions.renderingOptions.useFullClientRendering,onDemandTracks:!0,unifiedPlan:!0,singleSession:!0,videoTracksCount:N.videoTracksCount,red:!0,audioShare:N.audioShare,fastScreenShare:N.fastScreenShare,videoSuspend:N.videoSuspend,simulcast:N.simulcast,simulcastNativeOrder:!0,consumerFastScreenShare:N.consumerFastScreenShare,consumerFastScreenShareQualityOnDemand:N.consumerFastScreenShareQualityOnDemand,transparentAudio:N.transparentAudio}}e.get=t})(Ca||(Ca={}));var wa=Ca,Ta={producerScreenTrack:()=>!0,videoTracksCount:()=>N.videoTracksCount>0,waitingHall:()=>!0,filteredMessages:()=>!0,consumerScreenTrack:()=>!0,muteNotificationForAdmins:()=>!0,movieShare:()=>N.movieShare,useParticipantListChunk:()=>N.useParticipantListChunk,useRooms:()=>N.useRooms,vmoji:()=>!!N.vmoji,useCallsToContacts:()=>N.useCallsToContacts,useChatRooms:()=>N.useChatRooms,audienceModeHandUpTimestamps:()=>!1,animojiBackendRender:()=>!N.vmojiOptions.renderingOptions.useFullClientRendering,sessionStateUpdates:()=>N.enableSessionStateUpdates,addParticipant:()=>N.addParticipant,p2pRelay:()=>!1,waitForAdmin:()=>N.waitForAdminInGroupCalls,hold:()=>N.hold},Ea=class{static getFlags(){let e=Object.values(Ta),t=0;for(let n=0;n<e.length;n++)e[n]()&&(t|=1<<n);return t.toString(16).toUpperCase()}static parseCapabilities(e){let t=parseInt(e||`0`,16);return Object.keys(Ta).reduce((e,n,r)=>(e[n]=!!(t&1<<r),e),{})}},Da=63n,Oa=16383n,ka=1073741823,Aa=4611686018427387903n,ja=class{encode(e){let t=typeof e==`number`?BigInt(e):e;if(t<=Da)return new Uint8Array([Number(t)]);if(t<=Oa)return new Uint8Array([64|Number(t>>8n),Number(t&255n)]);if(t<=BigInt(ka))return new Uint8Array([128|Number(t>>24n),Number(t>>16n&255n),Number(t>>8n&255n),Number(t&255n)]);if(t<=Aa)return new Uint8Array([192|Number(t>>56n),Number(t>>48n&255n),Number(t>>40n&255n),Number(t>>32n&255n),Number(t>>24n&255n),Number(t>>16n&255n),Number(t>>8n&255n),Number(t&255n)]);throw RangeError(`Number is too large to encode using varint`)}},Ma=class{decode(e){let t=this.getNumBytesForLengthInteger(e);if(t<0)throw Error(`Invalid length prefix`);if(e.length<t)return null;let n=BigInt(0);switch(t){case 1:n=BigInt(e[0]&63);break;case 2:n=BigInt(e[0]&63)<<8n|BigInt(e[1]);break;case 4:n=BigInt(e[0]&63)<<24n|BigInt(e[1])<<16n|BigInt(e[2])<<8n|BigInt(e[3]);break;case 8:n=BigInt(e[0]&63)<<56n|BigInt(e[1])<<48n|BigInt(e[2])<<40n|BigInt(e[3])<<32n|BigInt(e[4])<<24n|BigInt(e[5])<<16n|BigInt(e[6])<<8n|BigInt(e[7]);break}return n}getNumBytesForLengthInteger(e){let t=e[0]&192;return t===0?1:t===64?2:t===128?4:t===192?8:-1}},Na=class{constructor(e){h(this,`encoder`,void 0),h(this,`compression`,void 0),h(this,`lengthEncoder`,void 0),this.encoder=new TextEncoder,this.lengthEncoder=new ja,this.compression=e??null}encode(e){let t=this.encoder.encode(e);t=this.compress(t);let n=this.lengthEncoder.encode(t.length),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),r}compress(e){if(!this.compression)return e;switch(this.compression){case`gzip`:return p.gzipSync(e);case`deflate`:return p.zlibSync(e);case`deflate-raw`:return p.deflateSync(e);default:return e}}},Pa=class{constructor(e){h(this,`decoder`,void 0),h(this,`compression`,void 0),h(this,`lengthDecoder`,void 0),h(this,`buffer`,void 0),h(this,`expectedLength`,void 0),h(this,`offset`,void 0),h(this,`lengthPrefixLength`,void 0),this.decoder=new TextDecoder,this.lengthDecoder=new Ma,this.compression=e??null,this.buffer=new Uint8Array,this.expectedLength=null,this.offset=0}decode(e){let t=[];for(this.buffer=new Uint8Array([...this.buffer,...e]);this.buffer.length>0;){if(this.expectedLength===null){if(this.expectedLength=this.readLength(this.buffer),this.expectedLength===null)return t;this.offset=this.lengthPrefixLength}if(this.buffer.length-this.offset<this.expectedLength)return t;let e=this.buffer.subarray(this.offset,this.offset+this.expectedLength);e=this.decompress(e),t.push(this.decoder.decode(e)),this.buffer=this.buffer.subarray(this.offset+this.expectedLength),this.expectedLength=null,this.offset=0}return t}readLength(e){if(e.length===0)return 0;if(this.lengthPrefixLength=this.lengthDecoder.getNumBytesForLengthInteger(e),this.lengthPrefixLength<0)throw Error(`Invalid length prefix`);let t=this.lengthDecoder.decode(e.subarray(0,this.lengthPrefixLength));return t===null?null:Number(t)}decompress(e){if(!this.compression)return e;switch(this.compression){case`gzip`:return p.gunzipSync(e);case`deflate`:return p.unzlibSync(e);case`deflate-raw`:return p.inflateSync(e);default:return e}}},Fa=class{static isBrowserSupported(){return!(!(`WebTransport`in window&&typeof WebTransport==`function`)||E.browserName()===`Safari`)}constructor(e,t={},n=z){h(this,`onopen`,null),h(this,`onmessage`,null),h(this,`onerror`,null),h(this,`onclose`,null),h(this,`readyState`,WebSocket.CONNECTING),h(this,`webTransport`,null),h(this,`writer`,null),h(this,`url`,void 0),h(this,`options`,void 0),h(this,`compression`,void 0),h(this,`encoder`,void 0),h(this,`decoder`,void 0),h(this,`_debug`,void 0),this._debug=n,this.url=e,this.options=t,this.compression=this.getCompressionTypeFromUrl(e),this.encoder=new Na(this.compression),this.decoder=new Pa(this.compression),this.connect()}async send(e){if(this.readyState!==WebSocket.OPEN){this._debug.warn(`[WebTransport] Attempt to send data before webtransport is open`);return}let t=this.writer;if(!t){this._debug.warn(`[WebTransport] Attempt to send data before stream is ready`);return}try{await t.ready;let n=this.encoder.encode(e);await t.write(n)}catch(e){this.handleStreamError(`send`,e)}}close(e=1e3,t=``){this.readyState===WebSocket.CLOSING||this.readyState===WebSocket.CLOSED||(this.readyState=WebSocket.CLOSING,this.requestNativeClose(e,t))}getCompressionTypeFromUrl(e){try{let t=new URL(e).searchParams.get(`compression`);switch(t){case`gzip`:case`deflate`:case`deflate-raw`:return t;default:return null}}catch(e){return this._debug.log(`[WebTransport] Exception while parsing compression`,e),null}}async connect(){try{let e=new WebTransport(this.url,{...this.options});if(this.webTransport=e,this.observeClosed(e),await e.ready,this.readyState!==WebSocket.CONNECTING)return;this._debug.debug(`[WebTransport] WebTransport connected to `+this.url);let t=await e.createBidirectionalStream();if(this.readyState!==WebSocket.CONNECTING)return;this.writer=t.writable.getWriter(),this.readyState=WebSocket.OPEN,this.emitEvent(`open`,this.onopen,new Event(`open`)),this.readyState===WebSocket.OPEN&&this.readLoop(t.readable)}catch(e){if(!this.webTransport){queueMicrotask(()=>this.fail(`connect`,e));return}this.fail(`connect`,e)}}observeClosed(e){e.closed.then(({closeCode:e,reason:t})=>{this.finishClose(e,t)},e=>{let t=this.readyState===WebSocket.CONNECTING?`connect`:`session`;this.fail(t,e),this.finishClose(1006,``)}).catch(e=>{this._debug.error(`[WebTransport] Failed to process native close`,e)})}async readLoop(e){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e){this.close(1e3,`Stream Closed`);return}if(n)for(let e of this.decoder.decode(n))this.emitEvent(`message`,this.onmessage,new MessageEvent(`message`,{data:e}))}}catch(e){this.handleStreamError(`read`,e)}finally{t.releaseLock()}}fail(e,t){this.readyState===WebSocket.CLOSING||this.readyState===WebSocket.CLOSED||(this.readyState=WebSocket.CLOSING,this._debug.error(`[WebTransport] ${e} failed`,t),this.emitEvent(`error`,this.onerror,this.createErrorEvent(t,e)),this.requestNativeClose(1006,`${e} failed`))}handleStreamError(e,t){let n=typeof t==`object`&&t&&`source`in t?t.source:void 0;if(n===`session`)return;let r=n===void 0&&t instanceof Error&&t.name===`WebTransportError`&&t.message.startsWith(`Session closed`);this.fail(r?`session`:e,t)}requestNativeClose(e,t){if(!this.webTransport){this.finishClose(1006,`Connection Failed`);return}try{this.webTransport.close({closeCode:e,reason:t})}catch(e){this._debug.warn(`[WebTransport] Native close failed synchronously`,e),this.finishClose(1006,`Close Failed`)}}finishClose(e,t){this.readyState!==WebSocket.CLOSED&&(this.writer=null,this.readyState=WebSocket.CLOSED,this.emitEvent(`close`,this.onclose,new CloseEvent(`close`,{code:e,reason:t})))}emitEvent(e,t,n){try{t?.call(this,n)}catch(t){this._debug.error(`[WebTransport] ${e} handler failed`,t)}}createErrorEvent(e,t){let n=new Event(`error`),r=e instanceof Error?e:null;return n.error=e,n.errorInfo={phase:t,name:r?.name,message:r?.message||String(e),stack:r?.stack,readyState:this.readyState,compression:this.compression},n}},Ia=function(e){return e.EMPTY_ENDPOINT=`EMPTY_ENDPOINT`,e.NETWORK_ERROR=`NETWORK_ERROR`,e.ABORTED=`ABORTED`,e}({}),La=class{constructor(e=z,t){h(this,`handlers`,void 0),h(this,`socket`,null),h(this,`endpoint`,``),h(this,`wtEndpoint`,null),h(this,`peerId`,null),h(this,`lastStamp`,0),h(this,`connectionType`,void 0),h(this,`reconnectCount`,0),h(this,`reconnectTimer`,0),h(this,`doctorTimer`,0),h(this,`forceWebSocket`,!1),h(this,`abortSignal`,void 0),h(this,`manualClose`,!1),h(this,`currentType`,Cr.WEBSOCKET),h(this,`_debug`,void 0),this.handlers=t,this._debug=e}get readyState(){return this.socket?.readyState??null}get type(){return this.currentType}setEndpoint(e){this.endpoint=e}setWebTransportEndpoint(e){this.wtEndpoint=e||null}setPeerId(e){this.peerId=e}setLastStamp(e){this.lastStamp=e}setAbortSignal(e){this.abortSignal=e}resetReconnectCount(){this.reconnectCount=0}connect(e){this.socket&&this.socket.readyState<WebSocket.CLOSING||(e!==xr.RETRY&&(this.forceWebSocket=!1,this.reconnectCount=0),this.manualClose=!1,this.connectionType=e,this._connect())}close(e){this.manualClose=!0,this._disconnect(e),window.clearTimeout(this.reconnectTimer),this.reconnectTimer=0,this.lastStamp=0}async send(e){await this.socket?.send(e)}_connect(){if(this._canUseWebTransport()){this._connectWebTransport();return}this._connectWebSocket()}_connectWebTransport(){if(!this.wtEndpoint){this._connectWebSocket();return}let e=this._buildUrl(this.wtEndpoint,!0);this.currentType=Cr.WEBTRANSPORT,this.socket=new Fa(e,{congestionControl:`low-latency`},this._debug),this._setSocketHandlers()}_connectWebSocket(){if(!this.endpoint){this.handlers.onFailed({failure:`EMPTY_ENDPOINT`,message:`Unable to connect to the signaling: endpoint is not set`,source:Cr.WEBSOCKET,remote:!0});return}let e=this._buildUrl(this.endpoint,!1);this.currentType=Cr.WEBSOCKET,this.socket=new WebSocket(e),this._setSocketHandlers()}_setSocketHandlers(){this.socket&&(this.handlers.onConnecting({connectionType:this.connectionType,source:this.currentType}),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())}_buildUrl(e,t){let n=new URL(e),r=n.searchParams;return r.set(`platform`,N.platform),r.set(`appVersion`,N.appVersion),r.set(`version`,String(N.protocolVersion)),r.set(`device`,N.device),r.set(`capabilities`,Ea.getFlags()),r.set(`clientType`,N.clientType),this.connectionType&&r.set(`tgt`,this.connectionType),this.connectionType===xr.RETRY&&this.lastStamp&&r.set(`recoverTs`,String(this.lastStamp)),N.useParticipantListChunk&&(r.set(`partIdx`,String(N.participantListChunkInitIndex)),N.participantListChunkInitCount!==null&&r.set(`partCount`,String(N.participantListChunkInitCount))),t&&(r.set(`compression`,`deflate-raw`),r.set(`ua`,navigator.userAgent)),this.peerId!==null&&r.set(`peerId`,String(this.peerId)),n.toString()}_canUseWebTransport(){return!this.forceWebSocket&&Fa.isBrowserSupported()&&this.wtEndpoint!==null&&N.webtransport}_onOpen(){this._startDoctor(),this.handlers.onOpen()}_onMessage(e){this._startDoctor(),this.handlers.onMessage(e)}_onError(e){this.handlers.onError(e)}_onClose(e){if(this._stopDoctor(),this.handlers.onClose(e),!this.manualClose){if(this.abortSignal?.aborted){this.handlers.onFailed({failure:`ABORTED`,message:`Signaling connection aborted`,source:this.currentType});return}this.forceWebSocket=!0,this._scheduleReconnect(this.currentType===Cr.WEBTRANSPORT?0:void 0)}}_disconnect(e){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(e)),this.socket=null,this._stopDoctor()}_scheduleReconnect(e=this._getReconnectDelay()){if(this.reconnectCount>=N.signalingReconnectMaxCount){this.handlers.onFailed({failure:`NETWORK_ERROR`,message:`Unable to connect to the signaling: reconnect attempts exhausted`,source:this.currentType});return}this.reconnectCount++,this.handlers.onReconnectScheduled({count:this.reconnectCount,delay:e}),this.reconnectTimer=window.setTimeout(()=>{this.connectionType=xr.RETRY,this._connect()},e)}_getReconnectDelay(){return Math.min(N.signalingReconnectMaxDelay,N.signalingReconnectDelay*2**this.reconnectCount)}_startDoctor(){this._stopDoctor(),!(this.reconnectCount>=N.signalingReconnectMaxCount)&&(this.doctorTimer=window.setTimeout(()=>{this.handlers.onConnectionDead(),this.forceWebSocket=!0,this._disconnect(4e3),this._scheduleReconnect(0)},N.waitMessageDelay))}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Ra=`open`,za=10,Ba={CONVERSATION_ENDED:`conversation-ended`,OBSOLETE_CLIENT:`gen.obsoleteClient`,INVALID_TOKEN:`invalid-token`,PARTICIPANT_NOT_FOUND:`participant-not-found`,ILLEGAL_PARTICIPANT_STATE:`illegal-participant-state`,SERVICE_UNAVAILABLE:`service-unavailable`},Va={[Ba.CONVERSATION_ENDED]:`conversation-ended`,[Ba.OBSOLETE_CLIENT]:`obsolete-client`,[Ba.INVALID_TOKEN]:`invalid-token`,[Ba.PARTICIPANT_NOT_FOUND]:`participant-not-found`,[Ba.ILLEGAL_PARTICIPANT_STATE]:`illegal-participant-state`,[Ba.SERVICE_UNAVAILABLE]:`service-unavailable`};function Ha(e,t){return e.errorMessage??e.message??e.error??t}var Ua=new Set([O.CALLER_IS_BLOCKED,O.ENDED,O.NOT_FOUND,O.PARTICIPANT_LIMIT_REACHED,O.SERVICE_UNAVAILABLE]),Wa=class e extends kn{static get WAIT_CONNECTION_DELAY(){return N.waitConnectionDelay}static get WAIT_RESPONSE_DELAY(){return N.waitResponseDelay}get ready(){return!this.disposed&&this.transport.readyState!==null}constructor(e=z,t=null,n=null,r=null,i=null){super(),h(this,`transport`,void 0),h(this,`sequence`,1),h(this,`lastStamp`,0),h(this,`websocketCommandsQueue`,[]),h(this,`datachannelCommandsQueue`,[]),h(this,`incomingCache`,[]),h(this,`responseHandlers`,{}),h(this,`disposed`,!1),h(this,`connectionType`,void 0),h(this,`conversationResolve`,null),h(this,`conversationReject`,null),h(this,`connected`,!1),h(this,`listenersReady`,!1),h(this,`peerId`,null),h(this,`connectionMessageWaitTimer`,0),h(this,`participantIdRegistry`,null),h(this,`producerNotificationDataChannel`,null),h(this,`producerCommandDataChannel`,null),h(this,`producerCommandDataChannelEnabled`,!1),h(this,`producerCommandSerializationService`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_statAggregator`,void 0),h(this,`_statPings`,void 0),h(this,`_statSignalingCommands`,void 0),this._debug=e,this._logger=t,this._statAggregator=n,this._statPings=r,this._statSignalingCommands=i,this.producerCommandSerializationService=new nr(e),this.transport=new La(e,{onConnecting:this._onTransportConnecting.bind(this),onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onError:this._onError.bind(this),onClose:this._onClose.bind(this),onFailed:this._onTransportFailed.bind(this),onReconnectScheduled:this._onTransportReconnectScheduled.bind(this),onConnectionDead:this._onTransportConnectionDead.bind(this)})}setAbortSignal(e){super.setAbortSignal(e),this.transport.setAbortSignal(e)}setEndpoint(e){this.transport.setEndpoint(e)}setWebTransportEndpoint(e){this.transport.setWebTransportEndpoint(e)}setParticipantIdRegistry(e){this.participantIdRegistry=e,this.producerCommandSerializationService.setParticipantIdRegistry(e)}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{if(this.producerNotificationDataChannel!==e)return;let n=this.participantIdRegistry?.handleMessage(t.data);n&&this._handleMessage(n)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=t=>{this.producerCommandSerializationService.deserializeCommandResponse(t.data).then(t=>{this.producerCommandDataChannel===e&&t&&this._handleMessage(t)}).catch(e=>{this._debug.warn(`[signaling] cannot parse message at producerCommandDataChannel`,e)})},this._handleCommandsQueue(this.datachannelCommandsQueue)}useCommandDataChannel(e){this.producerCommandDataChannelEnabled=e}resetProducerConnection(e=new On){this.producerCommandDataChannelEnabled=!1,this.producerNotificationDataChannel&&(this.producerNotificationDataChannel.onmessage=null,this.producerNotificationDataChannel=null),this.producerCommandDataChannel&&(this.producerCommandDataChannel.onmessage=null,this.producerCommandDataChannel=null);let t=[...this.datachannelCommandsQueue];this.datachannelCommandsQueue=[];for(let e of Object.values(this.responseHandlers))e.route===`producer`&&(t.push(e),delete this.responseHandlers[e.sequence]);t.forEach(t=>{window.clearTimeout(t.responseTimer),t.reject(e instanceof On?new On(t.name):e,!0)})}async connect(e){return new Promise((t,n)=>{if(this.transport.readyState!==null&&this.transport.readyState<WebSocket.CLOSING){this._logger?.log(C.SOCKET_ACTION,`already_opened`),n(Error(`Socket already opened`));return}this.conversationResolve=e=>{t(e),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=e=>{n(e),this.conversationResolve=null,this.conversationReject=null},this.connectionType=e,this.transport.connect(e)})}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return this._send(V.HANGUP,{reason:e},!1)}async sendCandidate(e,t){return this._send(V.TRANSMIT_DATA,{participantId:e,data:{candidate:t}},!1)}async requestTestMode(e,t){return this._send(V.REQUEST_TEST_MODE,{consumer:e,producer:t})}async sendSdp(e,t,n){let r=Object.assign({sdp:t},n);return this._send(V.TRANSMIT_DATA,{participantId:e,data:r},!0,za)}async acceptCall(e){return this._send(V.ACCEPT_CALL,{mediaSettings:e})}async changeMediaSettings(e){return this._send(V.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},!0,za)}async changeParticipantState(e,t){let n={participantState:{state:e}};return t&&(n.participantId=t),this._sendRaw(V.CHANGE_PARTICIPANT_STATE,n)}async hold(e){let t=wa.get();return this._send(V.HOLD,{hold:e,capabilities:e?void 0:t})}async putHandsDown(){return this._send(V.PUT_HANDS_DOWN)}async addParticipant(e,t){return this._send(V.ADD_PARTICIPANT,{externalIds:e,...t})}async addParticipantLegacy(e,t){return this._send(V.ADD_PARTICIPANT,{participantIds:e,...t})}async removeParticipant(e,t=!1){return this._send(V.REMOVE_PARTICIPANT,{participantId:e,ban:t})}async allocateConsumer(e,t){let n={capabilities:t};return e&&(n.description=e.sdp),this._send(V.ALLOCATE_CONSUMER,n)}async acceptProducer(e,t,n){let r={description:e.sdp,sessionId:n};return t.length&&(r.ssrcs=t),this._send(V.ACCEPT_PRODUCER,r)}async changePriorities(e){return this._send(V.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})}async updateDisplayLayout(e){return this._send(V.UPDATE_DISPLAY_LAYOUT,e)}async addMovie(e){return this._send(V.ADD_MOVIE,e)}async updateMovie(e){return this._send(V.UPDATE_MOVIE,e)}async removeMovie(e){return this._send(V.REMOVE_MOVIE,e)}startUrlSharing(e){return this._send(V.START_URL_SHARING,{sharedUrl:e})}stopUrlSharing(){return this._send(V.STOP_URL_SHARING)}async updateRooms(e,t){return this._send(V.UPDATE_ROOMS,{rooms:e,assignRandomly:t})}async activateRooms(e,t){return this._send(V.ACTIVATE_ROOMS,{roomIds:e,deactivate:t})}async switchRoom(e,t){return this._sendRaw(V.SWITCH_ROOM,{toRoomId:e,participantId:t})}async getRooms(e){return this._sendRaw(V.GET_ROOMS,{withParticipants:e})}async removeRooms(e){return this._send(V.REMOVE_ROOMS,{roomIds:e})}async startStream(e){return this._send(V.RECORD_START,e)}async stopStream(e={roomId:null}){return this._send(V.RECORD_STOP,e)}async publishStream(e={roomId:null}){return this._send(V.RECORD_PUBLISH,e)}async getRecordStatus(){return this._send(V.RECORD_GET_STATUS)}async switchTopology(e,t=!1){return this._send(V.SWITCH_TOPOLOGY,{topology:e,force:t})}async requestRealloc(){return this._send(V.REQUEST_REALLOC)}async reportPerfStat(e){return this._send(V.REPORT_PERF_STAT,e)}async reportSharingStat(e){return this._send(V.REPORT_SHARING_STAT,e,!1)}async reportNetworkStat(e){return this._send(V.REPORT_NETWORK_STAT,e,!1)}async chatMessage(e,t=null){return this._send(V.CHAT_MESSAGE,{message:e,participantId:t})}async chatHistory(e){return this._send(V.CHAT_HISTORY,{count:e})}async customData(e,t){return this._send(V.CUSTOM_DATA,{data:e,participantId:t})}async grantRoles(e,t,n){let r={participantId:e,roles:t};return n&&(r.revoke=!0),this._sendRaw(V.GRANT_ROLES,r)}async muteParticipant(e,t,n,r=null){return this._sendRaw(V.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:n,roomId:r})}async enableFeatureForRoles(e,t){return this._sendRaw(V.ENABLE_FEATURE_FOR_ROLES,{feature:e,roles:t})}async pinParticipant(e,t,n){let r={participantId:e,roomId:n};return t&&(r.unpin=!0),this._sendRaw(V.PIN_PARTICIPANT,r)}async updateMediaModifiers(e){return this._send(V.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})}async enableVideoSuspend(e){return this._send(V.ENABLE_VIDEO_SUSPEND,{enabled:e},!1)}async enableVideoSuspendSuggest(e){return this._send(V.ENABLE_VIDEO_SUSPEND_SUGGEST,{enabled:e},!1)}async changeSimulcast(e){return this._send(V.CHANGE_SIMULCAST,e,!1)}async changeOptions(e){return this._send(V.CHANGE_OPTIONS,{options:e})}async getWaitingHall(e=null,t,n=!1){let r={};return e&&(r.fromId=e),t&&(r.count=t),n&&(r.backward=n),this._send(V.GET_WAITING_HALL,r)}async promoteParticipant(e,t=!1){let n={};return e&&(n.participantId=e),t&&(n.demote=t),this._sendRaw(V.PROMOTE_PARTICIPANT,n)}async requestPromotion(e=!1){let t={};return e&&(t.unrequest=e),this._send(V.REQUEST_PROMOTION,t)}async acceptPromotion(e=!1){let t={};return e&&(t.reject=e),this._send(V.ACCEPT_PROMOTION,t)}async feedback(e){return this._sendRaw(V.FEEDBACK,{key:e})}async getHandQueue(){return this._send(V.GET_HAND_QUEUE)}dispose(e=new Dn){this._terminate(e)}readyToSend(e=!0){this.listenersReady=e,this._handleCachedMessages()}async getParticipantListChunk(e){return this._send(V.GET_PARTICIPANT_LIST_CHUNK,e)}async getParticipants(e){return this._send(V.GET_PARTICIPANTS,{externalIds:e})}getPeerId(){return this.peerId}async startAsr(e){return this._send(V.ASR_START,e)}async stopAsr(e){return this._send(V.ASR_STOP,e)}async requestAsr(e){return this._send(V.REQUEST_ASR,{request:e},!1)}async _send(e,t={},n=!0,r=0){if(t.participantId){let e=M.decomposeParticipantId(t.participantId),n=M.decomposeId(e.compositeUserId);t=Object.assign({},t,{participantId:n.id,participantType:n.type}),e.deviceIdx&&(t.deviceIdx=e.deviceIdx)}return this._sendRaw(e,t,n,r)}async _sendRaw(e,t={},n=!0,r=0){let i=t=>{if(this.disposed)throw new Dn(e);switch(t.route){case`producer`:this.datachannelCommandsQueue.push(t),this.producerCommandDataChannel?.readyState===Ra&&this._handleCommandsQueue(this.datachannelCommandsQueue);break;case`websocket`:if(this.transport.readyState===null){this._logger?.log(C.SOCKET_ACTION,`not_opened`),this._debug.warn(`[signaling] socket is not opened`),t.reject(Error(`Socket not opened [${e}]`),!0);return}this.transport.readyState>WebSocket.OPEN&&(this._logger?.log(C.SOCKET_ACTION,`invalid_state`),this._debug.warn(`[signaling] socket is not opened, state ${this.transport.readyState}`)),this.websocketCommandsQueue.push(t),this.transport.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((a,o)=>{let s=(t,n=!1)=>{!r||n?o(t):(this._debug.debug(`[signaling] resending a signaling message`,e,u.sequence),r--,i(u))},c=this.sequence++,l=`${e}_${c}`;G.setMark(l);let u={sequence:c,name:e,route:this._isDataChannelCommand(e)?`producer`:`websocket`,statMarkName:l,params:t,responseTimer:0,needResponse:n,resolve:a,reject:s};i(u)})}_isDataChannelCommand(e){return this.producerCommandDataChannelEnabled?e===V.UPDATE_DISPLAY_LAYOUT||e===V.REPORT_PERF_STAT||e===V.REPORT_SHARING_STAT||e===V.REQUEST_ASR||e===V.ENABLE_VIDEO_SUSPEND||e===V.ENABLE_VIDEO_SUSPEND_SUGGEST||e===V.REPORT_NETWORK_STAT||e===V.CHANGE_SIMULCAST:!1}_onOpen(){this._debug.debug(`[signaling] socket opened`),this._logger?.log(C.SOCKET_ACTION,`opened`),this._waitConnectionMessage(),this._logTransportStat(this.connectionType===xr.RETRY?wr.RECONNECTED:wr.CONNECTED)}_onMessage(e){if(e.data===`ping`){this._statPings?.mark(this._getSocketType()),this._markTransportStat(wr.FAILED_PINGS),R.onSignalingMessage(e.data),this.transport.readyState===WebSocket.OPEN&&this.transport.send(`pong`).catch(e=>this._debug.warn(`[signaling] unable to send pong`,e));return}try{let t=JSON.parse(e.data);R.onSignalingMessage(t),this._handleMessage(t)}catch(t){this._logger?.log(C.SOCKET_ACTION,`parse_error`),this._debug.error(`[signaling] unable to parse message`,t,e.data)}}_handleMessage(e){switch(e.type){case`notification`:this._attachNotificationCallError(e),e.notification===`connection`?(this._debug.debug(`[signaling] signaling connected`,e),this.connected=!0,this.transport.resetReconnectCount(),this.transport.setEndpoint(e.endpoint),e.peerId&&this.peerId!==e.peerId.id&&(this.peerId=e.peerId.id,this.transport.setPeerId(e.peerId.id)),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._logTransportStat(wr.RESTART),this._triggerEvent(Sr.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Sr.NOTIFICATION,{type:`notification`,notification:K.TOPOLOGY_CHANGED,topology:e.conversation.topology}),this._resolvePendingRecordCommands(e)),this.lastStamp&&this._handleCachedMessages(),e.recoverMessages?.forEach(e=>{e.notification===K.ACCEPTED_CALL&&e.peerId.id===this.peerId&&e.peerId.type===`WEB_TRANSPORT`||this._handleMessage(e)}),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(Sr.NOTIFICATION,e);break;case`response`:this._handleCommandResponse(!0,e);break;case`error`:this._handleErrorMessage(e);break;default:this._logger?.log(C.SOCKET_ACTION,`unknown_message`),this._debug.warn(`[signaling] unhandled message`,e)}e.stamp&&(this.lastStamp=e.stamp,this.transport.setLastStamp(e.stamp))}_handleErrorMessage(e){this._logger?.log(C.SOCKET_ACTION,`error-${e.error}`);let t=this._getSocketType(),n=e.error?this._createSignalingCallError(e.error,e.errorCode,t):void 0,r=Ha(e,`Unknown signaling error`);switch(this._debug.debug(`[signaling] error message [${e.sequence}]`,e),e.sequence&&this.responseHandlers[e.sequence]&&this._handleCommandResponse(!1,e),e.error){case Ba.SERVICE_UNAVAILABLE:let i=new k(O.SERVICE_UNAVAILABLE,{callError:n,message:r,remote:!0});this.conversationReject?this.conversationReject(i):this._triggerEvent(Sr.NOTIFICATION,{notification:K.CLOSED_CONVERSATION,callError:n,reason:O.SERVICE_UNAVAILABLE});break;case Ba.CONVERSATION_ENDED:this.conversationReject?this.conversationReject(new k(e.reason||x.SIGNALING_FAILED,{callError:n,message:r,remote:!0})):this._triggerEvent(Sr.NOTIFICATION,{notification:K.CLOSED_CONVERSATION,callError:n,reason:e.reason});break;case Ba.ILLEGAL_PARTICIPANT_STATE:case Ba.PARTICIPANT_NOT_FOUND:this._throwError(new k(x.SIGNALING_FAILED,{callError:n,message:r,remote:!0}));break;case Ba.OBSOLETE_CLIENT:this.conversationReject?.(new k(e.reason||O.OBSOLETE_CLIENT,{callError:n,message:r,remote:!0}));break;case Ba.INVALID_TOKEN:default:if(e.sequence||t===Cr.WEBTRANSPORT)break;if(this.connected)this._throwError(new k(e.reason||x.SIGNALING_FAILED,{callError:n??{scope:`unknown`,description:`signaling-unrecognized-error`},message:r,remote:!0}));else if(!e.sequence){let t=new k(e.reason||x.SIGNALING_FAILED,{callError:n??{scope:`unknown`,description:`signaling-unrecognized-error`},message:r,remote:!0});this.conversationReject?.(t),this.dispose(t)}}}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(Sr.FAILED,e)}_onError(e){this._logger?.log(C.SOCKET_ACTION,`error`),this._debug.error(`[signaling] signaling error`,e),this._logTransportStat(wr.FAILED_EXCEPTIONS,{string_value:this._serializeErrorEvent(e)})}_serializeErrorEvent(e){let t=e,n=t.error instanceof Error?t.error:null;return JSON.stringify({eventType:e.type,socketType:this._getSocketType(),readyState:this.transport.readyState,errorName:n?.name||t.errorInfo?.name,errorMessage:n?.message||t.errorInfo?.message||t.message,errorStack:n?.stack||t.errorInfo?.stack,errorInfo:t.errorInfo})}_onClose(e){this._logger?.log(C.SOCKET_ACTION,`closed`),this._debug.debug(`[signaling] connection closed`,{code:e.code,reason:e.reason}),this.connected=!1}_terminate(e){if(this.disposed)return!1;this.disposed=!0,this.transport.close(),this._stopWaitConnectionMessage();let t=[...this.websocketCommandsQueue,...this.datachannelCommandsQueue,...Object.values(this.responseHandlers)],n=this.conversationReject;return this.websocketCommandsQueue=[],this.datachannelCommandsQueue=[],this.responseHandlers={},this.incomingCache=[],this.conversationResolve=null,this.conversationReject=null,this.connected=!1,this.listenersReady=!1,this.lastStamp=0,this.producerCommandDataChannelEnabled=!1,this.producerNotificationDataChannel&&(this.producerNotificationDataChannel.onmessage=null,this.producerNotificationDataChannel=null),this.producerCommandDataChannel&&(this.producerCommandDataChannel.onmessage=null,this.producerCommandDataChannel=null),super.setAbortSignal(void 0),this.transport.setAbortSignal(void 0),t.forEach(t=>{window.clearTimeout(t.responseTimer),t.reject(e instanceof Dn?new Dn(t.name):e,!0)}),n?.(e),!0}_fail(e){this._terminate(e)&&this._throwError(e)}_isRecordCommand(e){return e===V.RECORD_START||e===V.RECORD_STOP}_resolvePendingRecordCommands(e){if(!N.waitForRecordResponse)return;let t=Object.values(this.responseHandlers).filter(e=>this._isRecordCommand(e.name));if(t.length===0)return;let n=new Map;n.set(null,!!e.conversation?.recordInfo);for(let t of e.rooms?.rooms??[])t.id!==void 0&&n.set(t.id,!!t.recordInfo);for(let e of t){let t=e.params.roomId??null,r=n.get(t)??!1,i=e.name===V.RECORD_START;window.clearTimeout(e.responseTimer),delete this.responseHandlers[e.sequence],this._debug.debug(`[signaling] resolve pending record command [${e.sequence}] via reconnect state`),i===r?e.resolve({type:`response`,sequence:e.sequence,response:e.name}):e.reject(Error(`Recording state mismatch`),!0)}}_handleCommandResponse(t,n){if(!Object.hasOwn(this.responseHandlers,n.sequence)){if(n.participants)for(let e of n.participants)this._triggerEvent(Sr.NOTIFICATION,{...n,notification:K.PARTICIPANT_ADDED,type:`notification`,participant:e});return}let r=this.responseHandlers[n.sequence];window.clearTimeout(r.responseTimer);let i=G.measureMark(r.statMarkName);i!==null&&this._statSignalingCommands?.mark(r.name,i,this._getSocketType()),this._debug.debug(`[signaling] command response [${n.sequence}]`,n),t?(delete this.responseHandlers[n.sequence],r.resolve(n)):n.type===`error`?(delete this.responseHandlers[n.sequence],this._logger?.log(C.SOCKET_ACTION,`response-error`),r.reject(Error(Ha(n,`Response error [${r.name}]`)),!0)):this.transport.readyState===WebSocket.OPEN?(delete this.responseHandlers[n.sequence],this._logger?.log(C.SOCKET_ACTION,`response-timeout`),r.reject(Error(Ha(n,`Response timeout [${r.name}]`)))):r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(t,n),e.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){for(;e.length>0;){let t=e.shift();if(this._debug.debug(`[signaling] command send [${t.sequence}]`,`'${t.name}'`,t.params),t.route===`producer`){if(this.producerCommandDataChannel?.readyState!==Ra){t.reject(Error(`Invalid data channel state: ${this.producerCommandDataChannel?.readyState}`));return}t.needResponse?this._startResponseTimer(t):this._resolveCommandWithoutResponse(t);let e=this._serializeBinary(t);e!==null&&this.producerCommandDataChannel.send(e)}else{if(this.transport.readyState!==WebSocket.OPEN){t.reject(Error(`Invalid state or socket already closed`));continue}t.needResponse&&this._startResponseTimer(t),this.transport.send(this._serializeJson(t)).then(()=>{t.needResponse||this._resolveCommandWithoutResponse(t)},e=>{window.clearTimeout(t.responseTimer),delete this.responseHandlers[t.sequence],t.reject(e,!0)})}}}_startResponseTimer(t){t.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{response:t.name,sequence:t.sequence,type:`timeout`}),e.WAIT_RESPONSE_DELAY),this.responseHandlers[t.sequence]=t}_resolveCommandWithoutResponse(e){e.resolve({type:`response`,sequence:e.sequence,response:e.name})}_serializeBinary(e){switch(e.name){case V.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case V.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params);case V.REPORT_SHARING_STAT:return this.producerCommandSerializationService.serializeSharingStatReport(e.sequence,e.params);case V.REQUEST_ASR:return this.producerCommandSerializationService.serializeRequestAsr(e.sequence,e.params);case V.REPORT_NETWORK_STAT:return this.producerCommandSerializationService.serializeNetworkStatReport(e.sequence,e.params);case V.ENABLE_VIDEO_SUSPEND:return this.producerCommandSerializationService.serializeEnableVideoSuspend(e.sequence,e.params);case V.ENABLE_VIDEO_SUSPEND_SUGGEST:return this.producerCommandSerializationService.serializeEnableVideoSuspendSuggest(e.sequence,e.params);case V.CHANGE_SIMULCAST:return this.producerCommandSerializationService.serializeChangeSimulcast(e.sequence,e.params)}return this._debug.warn(`[signaling] cannot get binary data for data channel command: `+e.name),null}_serializeJson(e){let t;t=e.name===V.UPDATE_DISPLAY_LAYOUT?this._convertDisplayLayout(e.params):e.params;let n=Object.assign({command:e.name,sequence:e.sequence},t);return JSON.stringify(n)}_convertDisplayLayout(e){let t=e,n={};for(let e in t)Object.hasOwn(t,e)&&(n[e]=Mn(t[e]));return{layouts:n}}_waitConnectionMessage(){let t=this._getSocketType();this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new k(x.SIGNALING_FAILED,{callError:{scope:`network`,source:t,code:`timeout`,description:`connection-timeout`},message:`Unable to connect to the signaling: connection timeout`,remote:!0}))},e.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_onTransportConnecting(e){let t=e.connectionType===xr.RETRY?wr.RECONNECTED:wr.CONNECTED;this._markTransportStat(t,e.source)}_onTransportFailed(e){switch(e.failure){case Ia.EMPTY_ENDPOINT:this.conversationReject?.(new k(x.SIGNALING_FAILED,{callError:{scope:`internal`,code:`configuration`,description:`signaling-endpoint-missing`},message:e.message,remote:e.remote}));break;case Ia.NETWORK_ERROR:this._fail(new k(O.NETWORK_ERROR,{callError:{scope:`network`,source:e.source,code:`reconnect-exhausted`,description:`connection-failed`}}));break;case Ia.ABORTED:this._debug.debug(`[signaling] aborted reconnect`),this._fail(new k(O.CANCELED));break}}_onTransportReconnectScheduled(e){this.connectionType=xr.RETRY,this._debug.log(`[signaling] reconnect signaling after ${e.delay}ms (${e.count})`),this._logger?.log(C.SOCKET_ACTION,`reconnect`)}_onTransportConnectionDead(){this._debug.warn(`[signaling] socket is dead, trying to reconnect`),this._logTransportStat(wr.FAILED_PINGS)}_attachNotificationCallError(e){e.callError||!e.reason||e.reason===O.FAILED||e.reason===O.UNKNOWN_ERROR||!Ua.has(e.reason)&&!e.errorCode||(e.callError={scope:`server`,source:this._getSocketType(),code:e.errorCode||`protocol`,description:String(e.reason)})}_createSignalingCallError(e,t,n){let r=Va[e];if(r)return{scope:`server`,source:n,code:t??`protocol`,description:r}}_getSocketType(){return this.transport.type}_markTransportStat(e,t=this._getSocketType()){let n=Tr[e][t];G.setMark(n)}_logTransportStat(e,t){let n=this._getSocketType(),r=Tr[e][n];this._statAggregator?.logEventualStat({name:r,...t})}},Ga=function(e){return e.INCOMING=`INCOMING`,e.OUTGOING=`OUTGOING`,e.JOINING=`JOINING`,e}(Ga||{}),Ka=function(e){return e.USER=`USER`,e.GROUP=`GROUP`,e.CHAT=`CHAT`,e}(Ka||{}),qa=function(e){return e.ATTENDEE=`ATTENDEE`,e.HAND_UP=`HAND_UP`,e}(qa||{}),Ja=function(e){return e.ADD_PARTICIPANT=`ADD_PARTICIPANT`,e.RECORD=`RECORD`,e.MOVIE_SHARE=`MOVIE_SHARE`,e}(Ja||{}),Ya=function(e){return e.REQUIRE_AUTH_TO_JOIN=`REQUIRE_AUTH_TO_JOIN`,e.AUDIENCE_MODE=`AUDIENCE_MODE`,e.WAITING_HALL=`WAITING_HALL`,e.WAIT_FOR_ADMIN=`WAIT_FOR_ADMIN`,e.ADMIN_IS_HERE=`ADMIN_IS_HERE`,e.ASR=`ASR`,e.FEEDBACK=`FEEDBACK`,e.RECURRING=`RECURRING`,e}(Ya||{});function Xa(e,t){if(e.length!==t.length)return!1;for(let n of e)if(!t.includes(n))return!1;return!0}function Za(e,t){let n=new Set(e);for(let[e,r]of Object.entries(t))r?n.add(e):n.delete(e);return Array.from(n)}var Qa=function(e){return e.UNMUTE=`UNMUTE`,e.MUTE=`MUTE`,e.MUTE_PERMANENT=`MUTE_PERMANENT`,e}(Qa||{}),X=function(e){return e.CALLED=`CALLED`,e.ACCEPTED=`ACCEPTED`,e.REJECTED=`REJECTED`,e.HUNGUP=`HUNGUP`,e}(X||{}),$a=function(e){return e.UPDATE=`UPDATE`,e.REMOVE=`REMOVE`,e.ACTIVATE=`ACTIVATE`,e.TIMEOUT=`TIMEOUT`,e}($a||{}),eo=function(e){return e.NO_AVAILABLE_TRACKS=`no-available-tracks`,e.UNKNOWN_ERROR=`unknown-error`,e}(eo||{});function to(e){switch(e){case 1:return`no-available-tracks`;default:return`unknown-error`}}var no=function(e){return e.CREATOR=`CREATOR`,e.ADMIN=`ADMIN`,e}(no||{});function ro(e,t){if(e.length!==t.length)return!1;for(let n of e)if(!t.includes(n))return!1;return!0}var io;(function(e){function t(e){let t=e?.transport??e?.lastEffective??P.WAITING,n={transport:t,stalled:e?.stalled??!1,sessionState:e?.sessionState,sessionStateApplicable:e?.sessionStateApplicable??!1,sessionStateConnectedBySpeaker:e?.sessionStateConnectedBySpeaker??!1,lastEffective:e?.lastEffective??t};return n.lastEffective=r(n),n}e.create=t;function n(e){return e===q.CONNECTED?P.CONNECTED:e===q.CONNECTING||e===q.OPENED?P.CONNECTING:e===q.RECONNECTING?P.RECONNECT:null}e.fromTransportState=n;function r(e){return[P.HANGUP,P.ERROR,P.ONHOLD].includes(e.transport)?e.transport:e.transport===P.RECONNECT||e.transport===P.CONNECTED&&e.stalled?P.RECONNECT:e.sessionStateApplicable&&e.sessionState?.connected===!1?e.sessionStateConnectedBySpeaker&&e.transport===P.CONNECTED?P.CONNECTED:P.CONNECTING:e.transport}e.computeEffective=r;function i(e,t,n=!1){return e.sessionState=t,e.sessionStateConnectedBySpeaker=t?.connected===!1&&n,c(e)}e.setSessionState=i;function a(e,t){return e.transport=t,t!==P.CONNECTED&&(e.sessionStateConnectedBySpeaker=!1),c(e)}e.setTransport=a;function o(e,t){return e.stalled=t,c(e)}e.setStalled=o;function s(e,t){return e.sessionStateApplicable=t,t||(e.sessionStateConnectedBySpeaker=!1),c(e)}e.setSessionStateApplicable=s;function c(e){let t=r(e);return e.lastEffective===t?{status:t,shouldNotify:!1}:(e.lastEffective=t,{status:t,shouldNotify:!0})}})(io||(io={}));var ao=io,oo=function(e){return e.USER=`USER`,e.ANONYM=`ANONYM`,e.GROUP=`GROUP`,e}({}),Z;(function(e){function t(e){return e.length?typeof e[0]==`object`?e:e.map(e=>n(e)):[]}e.fromIds=t;function n(e,t=`USER`,n=0){return{id:e,type:t,deviceIdx:n}}e.fromId=n;function r(e,t=!0,n=!1){let r=t?e.decorativeExternalUserId:e.externalId,a=e.deviceIdx??0;if(r)return i(r,a);if(n&&t&&e.externalId)return i(e.externalId,a)}e.fromSignalingParticipant=r;function i(e,t=0){let n=e.type===`ANONYM`?`ANONYM`:`USER`;return{id:e.id,type:n,deviceIdx:t}}e.fromSignaling=i;function a(e){return e.id}e.toSignaling=a;function o(e){let t=e.deviceIdx||0;return`{"id":"${e.id}","type":"${e.type}","deviceIdx":${t}}`}e.toString=o;function s(e,t=`USER`,r=0){return o(n(e,t,r))}e.fromIdToString=s;function c(e){try{return JSON.parse(e)}catch{throw Error(`Failed to parse ExternalId from string '${e}'`)}}e.fromString=c;function l(e,t){return e.id===t.id&&e.type===t.type&&e.deviceIdx===t.deviceIdx}e.compare=l;function u(e){return e?.deviceIdx||0}e.getDeviceIdx=u})(Z||(Z={}));function so(e){try{return btoa(JSON.stringify(e))}catch(t){z.warn(`WaitingParticipant: failed convert to string`,e,t)}return null}function co(e){try{return JSON.parse(atob(e))}catch(t){z.warn(`WaitingParticipant: failed convert from string`,e,t)}return null}var lo=(e,t)=>M.objectReduce(e,(e,n,r)=>(n===t&&e.push(r),e),[]);function uo(e){if(e.conversation?.muteStates)return e.conversation.muteStates;if(e.muteState&&e.muteOptions)return e.muteOptions.reduce((t,n)=>(t[n]=e.muteState,t),{})}function fo(e,t){switch(e){case S.AUDIO:return!!t.isAudioEnabled;case S.AUDIO_SHARING:return!!t.isAudioSharingEnabled;case S.VIDEO:return!!t.isVideoEnabled;case S.SCREEN_SHARING:return!!t.isFastScreenSharingEnabled||!!t.isScreenSharingEnabled;default:return!1}}function po(e,t){return M.objectReduce(e,(e,n,r)=>{switch(n){case Qa.MUTE:case Qa.MUTE_PERMANENT:fo(r,t)||(e[r]=n);break;default:e[r]=n;break}return e},{})}function mo(e){let{muteStates:t={},mediaSettings:n}=e;return po(t,n)}function ho(e,t){let n=e.conversation.participants.find(t=>M.comparePeerId(t.peerId,e.peerId));if(!n)return t;let{mediaSettings:r}=n;return po(t,r)}function go(e){if(!e)return null;let t=Array.from(new Set((e.urls??[]).map(e=>e.trim()).filter(e=>e.length>0)));return t.length?{...e,urls:t}:null}function _o(e,t){let n=[],r=go(e),i=go(t);if(r&&n.push(r),i){let e=[...i.urls];e.push(`${e[e.length-1]}?transport=tcp`),n.push({...i,urls:e})}return n}function vo(e,t){let n=new Uint8Array(t),r=0,i=0;for(;r<e.length&&i<t;){let a=e[r++],o=a>>4,s=a&15;if(o===15){let t;do t=e[r++],o+=t;while(t===255)}for(let a=0;a<o&&!(i>=t);a++)n[i++]=e[r++];if(r>=e.length||i>=t)break;let c=e[r]|e[r+1]<<8;if(r+=2,s===15){let t;do t=e[r++],s+=t;while(t===255)}s+=4;let l=i-c;for(let e=0;e<s&&!(i>=t);e++)n[i++]=n[l+e]}return n}function yo(e){let t,n=!1,r,i=async()=>{let t=!1,i;for(;n;){let a=r;n=!1;try{await e(a),t=!1}catch(e){t=!0,i=e}!t&&n&&Object.is(r,a)&&(n=!1)}if(t)throw i};return e=>(r=e,n=!0,t??(t=i().finally(()=>{t=void 0})),t)}var bo=class{constructor(e,t=z,n=null){h(this,`_fixNoPacketsApplied`,!1),h(this,`_fixNoPacketsChecked`,!1),h(this,`_fixTooManyPacketsApplied`,!1),h(this,`_fixTooManyPacketsSucceeded`,!1),h(this,`_fixTooManyPacketsFailed`,!1),h(this,`_fixTooManyPacketsTime`,void 0),h(this,`_mediaSource`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_lastPacketsSent`,void 0),h(this,`_lastPacketsSentTime`,void 0),h(this,`_toggleAudioPromise`,null),h(this,`_fixNoPacketsAppliedVideo`,!1),this._mediaSource=e,this._debug=t,this._logger=n}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,this._logger?.log(C.ERROR,`audio_device_recover_${e.bandwidth?`success`:`fail`}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&e.packetsSent>0&&(this._fixNoPacketsApplied=!0,this._logger?.log(C.ERROR,`audio_device_recover`),this._debug.log(`[AudioFix] Trying to fix RV (no packets)`),this._toggleAudioPromise=this._mediaSource.toggleAudio(E.getMicrophonePermissionState()!==`denied`),this._toggleAudioPromise.catch(()=>void 0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=t,this._lastPacketsSent=e.packetsSent);else if(t-this._lastPacketsSentTime>500){let n=(e.packetsSent-this._lastPacketsSent)*1e3/(t-this._lastPacketsSentTime);this._lastPacketsSentTime=t,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?n>75?(this._debug.log(`[AudioFix] Failed to fix RV`),this._logger?.log(C.ERROR,`audio_device_recover_rv_fail`),this._fixTooManyPacketsFailed=!0):t-this._fixTooManyPacketsTime>6e4&&(this._debug.log(`[AudioFix] Fixed RV`),this._logger?.log(C.ERROR,`audio_device_recover_rv_success`),this._fixTooManyPacketsSucceeded=!0):n>75&&(this._fixTooManyPacketsApplied=!0,this._logger?.log(C.ERROR,`audio_device_recover`),this._debug.log(`[AudioFix] Trying to fix RV (too many packets)`),this._mediaSource.toggleAudio(!0).catch(e=>{this._debug.warn(`[AudioFix] Failed to fix RV (too many packets)`,e)}),this._fixTooManyPacketsTime=t)}}fix(e){if(!this._mediaSource)return;let t=e.find(e=>e.kind===A.audio);t&&(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}fixVideo(e){if(!this._mediaSource||this._fixNoPacketsAppliedVideo||!this._toggleAudioPromise)return;let t=e.find(e=>e.kind===A.video);t&&!t.bandwidth&&(this._fixNoPacketsAppliedVideo=!0,this._toggleAudioPromise.then(()=>{if(this._mediaSource.mediaSettings.isVideoEnabled)return this._mediaSource.toggleVideo(!0)}).catch(e=>{this._debug.warn(`[AudioFix] Failed to fix RV (no packets): video restart`,e)}))}},xo=class{constructor(e,t=!1,n=z,r=null){h(this,`_audioElement`,null),h(this,`_debug`,void 0),h(this,`_preparedAudioElement`,void 0),h(this,`_audioTracks`,new Map),h(this,`_allowMultipleTracks`,void 0),h(this,`_volume`,1),h(this,`_features`,{setSinkId:!!Audio.prototype.setSinkId}),h(this,`_statFirstMediaReceived`,void 0),h(this,`_logger`,void 0),this._statFirstMediaReceived=e,this._allowMultipleTracks=t,this._debug=n,this._logger=r,this._preparedAudioElement=this._prepareAudioElement()}add(e,t){this._allowMultipleTracks||this._clearTracks();let n=this._audioTracks.get(e);n&&n!==t&&(this._removeTrackFromAudioElement(n),n.stop()),this._audioTracks.set(e,t),this._audioElement?this._addTrackToAudioElement(t):this._initAudioElement()}remove(e,t){let n=this._audioTracks.get(e);if(!n){t.stop();return}if(n!==t){t.stop();return}if(!this._allowMultipleTracks){this.destroy();return}this._removeTrackFromAudioElement(t),t.stop(),this._audioTracks.delete(e),this._audioTracks.size||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._audioElement&&(this._audioElement.volume=this._volume)}destroy(){!this._audioElement&&!this._audioTracks.size||(this._stopAudioElement(),this._audioElement=null,this._audioTracks.clear())}async changeOutput(){try{if(!this._features.setSinkId)throw Error(`Feature "setSinkId" is not supported`);if(!this._audioElement)return;let e=E.getSavedOutput();e&&await this._audioElement.setSinkId?.(e.deviceId)}catch(e){throw this._logger?.log(C.ERROR,`change_output`),this._debug.error(`[audio] Output change failed`,e),e}}_getTracks(){return Array.from(this._audioTracks.values())}_initAudioElement(){if(N.muteMode)return;let e=this._getTracks();if(!e.length)return;let t=this._preparedAudioElement??this._createAudioElement();t.muted=!1,t.volume=this._volume,t.preload=`auto`;let n=()=>{this._debug.warn(`[audio] Error on play audio`),R.onAutoplayError()},r=e=>{this._debug.debug(`[audio] Play audio`),t.srcObject=null,t.srcObject=new MediaStream(e),t.load();let r=t.play();r&&r.catch(n)},i=()=>{this._debug.debug(`[audio] Recover audio playback`);let e=this._getTracks();e.length?r(e):this._debug.warn(`[audio] Broken audio tracks`)};t.onpause=i,t.onstalled=i,t.onerror=i,t.onloadeddata=()=>{this._statFirstMediaReceived.measure()},r(e),this._audioElement=t;let a=E.getSavedOutput()?.deviceId;a&&t.setSinkId?.(a).catch(e=>{this._debug.warn(`[audio] Failed to set output device '${a}'`,e)})}_stopAudioElement(){this._audioElement&&(this._audioElement.onpause=null,this._audioElement.onstalled=null,this._audioElement.onerror=null,this._audioElement.onloadeddata=null,this._audioElement.pause(),this._audioElement.srcObject=null);for(let e of this._audioTracks.values())e.stop()}_createAudioElement(){let e=E.browserName()!==`Safari`||E.isMobile()||N.safariAudioElement;return document.createElement(e?`audio`:`video`)}_prepareAudioElement(){if(N.muteMode||E.browserName()!==`Safari`||E.isMobile())return null;let e=this._createAudioElement();return e.load(),e}_addTrackToAudioElement(e){if(!this._audioElement)return;this._debug.debug(`[audio] Adding track ${e}`);let t=this._audioElement.srcObject;t||(t=new MediaStream,this._audioElement.srcObject=t),t.addTrack(e)}_removeTrackFromAudioElement(e){this._audioElement?.srcObject&&(this._debug.debug(`[audio] Removing track ${e}`),this._audioElement.srcObject.removeTrack(e))}_clearTracks(){for(let e of this._audioTracks.values())this._removeTrackFromAudioElement(e),e.stop();this._audioTracks.clear()}};function So(e,t){e||wo(t,`response-empty`),e.id||wo(t,`id-empty`),e.endpoint||wo(t,`endpoint-empty`),!Co(e.stun_server)&&!Co(e.turn_server)&&wo(t,`ice-servers-empty`)}function Co(e){return Array.isArray(e?.urls)&&e.urls.length>0}function wo(e,t){let n=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),r=e===`fastStart`||e===`fastJoin`;throw new k(r?e===`fastStart`?O.FAST_START_ERROR:O.FAST_JOIN_ERROR:O.UNKNOWN_ERROR,{message:`Invalid ${e} response: ${t}`,callError:r?{scope:`external`,source:`api`,code:`invalid-response`,description:`${n}-${t}`}:{scope:`server`,source:`api`,code:`invalid-response`,description:`${n}-${t}`}})}var To=90,Eo=3,Do=class extends b{constructor(e=z){super(),h(this,`_lastMemoryStat`,{percent:0,bytes:0}),h(this,`_debug`,void 0),this._debug=e}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(e=>{e.userId=(typeof e.userId==`string`&&t[e.userId]||null)?.externalId}),R.onStatistics(e,this._lastMemoryStat)}_calcMemory(){let e=window?.performance?.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),n=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>To?this._debug.warn(`High memory usage: ${t}% (${n} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Eo)&&(this._debug.debug(`Memory usage: ${t}% (${n} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}},Oo=class{constructor({api:e,debug:t,getParticipants:n,isMe:r,updateDisplayLayout:i,onNonFatalError:a}){h(this,`_api`,void 0),h(this,`_debug`,void 0),h(this,`_getParticipants`,void 0),h(this,`_isMe`,void 0),h(this,`_updateDisplayLayout`,void 0),h(this,`_onNonFatalError`,void 0),h(this,`_requestedLayouts`,{}),h(this,`_uncertainLayouts`,{}),h(this,`_pendingRequests`,null),h(this,`_pendingPromises`,[]),h(this,`_lastRequests`,null),h(this,`_timer`,null),h(this,`_inFlight`,!1),h(this,`_lastFlushAt`,null),h(this,`_generation`,0),h(this,`_forceNextFlush`,!1),this._api=e,this._debug=t,this._getParticipants=n,this._isMe=r,this._updateDisplayLayout=i,this._onNonFatalError=a}request(e){this._pendingRequests=e.slice(),this._lastRequests=e.slice();let t=new Promise((e,t)=>{this._pendingPromises.push({resolve:e,reject:t})});return this._schedule(),t}resend(){this._lastRequests&&(this._pendingRequests=this._lastRequests.slice(),this._forceNextFlush=!0,this._schedule())}cleanupParticipant(e){for(let t of Object.keys(this._requestedLayouts))In(t).participantId===e&&delete this._requestedLayouts[t];for(let t of Object.keys(this._uncertainLayouts))In(t).participantId===e&&delete this._uncertainLayouts[t]}clear(){this._generation++,this._timer!==null&&(window.clearTimeout(this._timer),this._timer=null),this._pendingPromises.forEach(({resolve:e})=>e()),this._requestedLayouts={},this._uncertainLayouts={},this._pendingRequests=null,this._pendingPromises=[],this._lastRequests=null,this._inFlight=!1,this._lastFlushAt=null,this._forceNextFlush=!1}_schedule(){if(this._inFlight||this._timer!==null)return;let e=this._lastFlushAt===null?0:Math.max(0,N.requestDisplayLayoutThrottleMs-(Date.now()-this._lastFlushAt));this._timer=window.setTimeout(()=>{this._timer=null,this._flush()},e)}async _flush(){if(this._inFlight||!this._pendingRequests)return;this._inFlight=!0;let e=this._generation,t=this._pendingRequests,n=this._pendingPromises;this._pendingRequests=null,this._pendingPromises=[];let r={};try{let i=this._getRequestLayouts(t);if(!i){n.forEach(({resolve:e})=>e());return}r=i;let a=this._forceNextFlush||Object.keys(this._uncertainLayouts).length>0;this._forceNextFlush=!1;let o=this._getDiff(r,a);o.length&&await this._updateDisplayLayout(o),e===this._generation&&(this._requestedLayouts=r,this._uncertainLayouts={}),n.forEach(({resolve:e})=>e())}catch(t){e===this._generation?(this._uncertainLayouts={...this._uncertainLayouts,...r},n.forEach(({reject:e})=>e(t))):n.forEach(({resolve:e})=>e())}finally{e===this._generation&&(this._lastFlushAt=Date.now(),this._inFlight=!1,this._pendingRequests&&this._schedule())}}_getRequestLayouts(e){let t={},n=[],r=this._getParticipants();for(let i of e){let e=typeof i.uid==`object`?i.uid:Z.fromId(i.uid),a=this._api.getCachedParticipantIdByExternalId(e);if(!a){this._debug.log(`Unknown participant external ID ${typeof i.uid==`object`?Z.toString(i.uid):i.uid}`),n.push(e.id);continue}if(!r[a]&&!this._isMe(a))continue;let o=Fn({participantId:a,mediaType:i.mediaType,streamName:i.streamName});t[o]={uid:i.uid,mediaType:i.mediaType,width:i.width,height:i.height,fit:i.cover?`cv`:`cn`,...i.priority===void 0?{}:{priority:i.priority},...i.streamName===void 0?{}:{streamName:i.streamName}}}return n.length?(this._onNonFatalError(`Participant ID mapping not found for external IDs "${Array.from(new Set(n)).join(`", "`)}" while handling requestDisplayLayout`),null):t}_getDiff(e,t=!1){let n=[];if(t){let t={...this._requestedLayouts,...this._uncertainLayouts};n.push(...Object.values(e));for(let[r,i]of Object.entries(t))e[r]||n.push({uid:i.uid,mediaType:i.mediaType,stopStream:!0,...i.streamName===void 0?{}:{streamName:i.streamName}});return n}for(let[t,r]of Object.entries(e)){let e=this._requestedLayouts[t];(!e||this._isChanged(e,r))&&n.push(r)}for(let[t,r]of Object.entries(this._requestedLayouts))e[t]||n.push({uid:r.uid,mediaType:r.mediaType,stopStream:!0,...r.streamName===void 0?{}:{streamName:r.streamName}});return n}_isChanged(e,t){let n=e,r=t;return n.width!==r.width||n.height!==r.height||n.fit!==r.fit||n.priority!==r.priority}},ko=44100,Ao=class{constructor(e,t){h(this,`_analyser`,null),h(this,`_gainNode`,null),h(this,`_fftBins`,null),h(this,`_mediaStreamSource`,null),h(this,`_lastSmoothedLevel`,0),h(this,`_trackId`,void 0),h(this,`_track`,void 0),h(this,`_stream`,void 0),this._trackId=e,this._track=t,this._stream=new MediaStream([t]);try{let e=E.getAudioContext();this._analyser=e.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,E.browserName()===`Safari`&&(this._gainNode=e.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(e.destination),this._analyser.connect(this._gainNode)),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=e.createMediaStreamSource(this._stream),this._mediaStreamSource.connect(this._analyser)}catch{}}get track(){return this._track}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=ko/this._fftBins.length,t=Math.ceil(N.voiceParams.minFreq/e),n=Math.floor(N.voiceParams.maxFreq/e);return this._fftBins.subarray(t,n)}getLevel(){let e=this._getBins(),t=e.reduce((e,t)=>e+t,0)/e.length/255,n=this._lastSmoothedLevel*N.voiceParams.smoothing+t*(1-N.voiceParams.smoothing);return this._lastSmoothedLevel=n,{real:t,smoothed:n}}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),this._stream.removeTrack(this._track)}},jo=class extends b{constructor(e){super(),h(this,`_detector`,null),h(this,`_interval`,null);let t=()=>{this._detector&&R.onLocalVolume(this._detector.getLevel().real,e.mediaSettings.isAudioEnabled),this._interval=window.setTimeout(t,N.voiceParams.interval)};this._interval=window.setTimeout(t,N.voiceParams.interval);let n=()=>{let t=e.getSendAudioTrack();t&&this.init(t)};this.subscribe(e,Jt.SOURCE_CHANGED,t=>{t.kind===A.audio&&e.mediaSettings.isAudioEnabled&&n()}),this.subscribe(e,Jt.SOURCE_READY,n),n()}init(e){this._stopDetector(),this._detector=new Ao(`local`,e.clone())}_stopDetector(){this._detector&&(this._detector.track.stop(),this._detector.destroy(),this._detector=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}},Mo=class{constructor(e,t=z){h(this,`processor`,void 0),h(this,`queue`,[]),h(this,`isProcessing`,!1),h(this,`_debug`,void 0),this.processor=e,this._debug=t}add(e){this.queue.push(e),this.processQueue()}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length;){let e=this.queue.shift();if(e)try{await this.processor(e)}catch{this._debug.error(`Can't process message ${JSON.stringify(e)}`)}}this.isProcessing=!1}}},No=function(e){return e.VOLUMES_DETECTED=`VOLUMES_DETECTED`,e}({}),Po=class extends b{constructor(e){super(),h(this,`_detectors`,new Map),h(this,`_interval`,null),h(this,`_activeParticipants`,void 0),h(this,`_removedParticipants`,void 0),h(this,`_topology`,void 0),this._topology=e.getTopology(),this.subscribe(e,Y.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,Y.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,Y.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,Y.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),this._destroyDetectors()}_onRemoteTrackAdded(e,t,n){if(n.kind===A.audio&&(this._detectors.get(e)?.destroy(),this._detectors.set(e,new Ao(e,n)),!this._interval)){let e=()=>{this._collectVolumes(),this._interval=window.setTimeout(e,N.voiceParams.interval)};this._interval=window.setTimeout(e,N.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,n){if(n.kind!==A.audio)return;let r=this._detectors.get(e);!r||r.track!==n||(r.destroy(),this._detectors.delete(e))}_collectVolumes(){if(!this._detectors.size)return;let e={};if(this._topology===J.SERVER){if(this._activeParticipants)for(let t of this._activeParticipants){let n=this._getAudioTrackLevelByParticipantId(t);n&&(e[t]=n)}if(this._removedParticipants){for(let t of this._removedParticipants)e[t]={real:0,smoothed:0};this._removedParticipants=null}}else for(let[t,n]of this._detectors.entries())e[t]=n.getLevel();this._triggerEvent(`VOLUMES_DETECTED`,e)}_getAudioTrackLevelByParticipantId(e){let t=this._detectors.get(Zr.AUDIO_MIX);return t?t.getLevel():this._getTransparentAudioLevelByParticipantId(e)}_getTransparentAudioLevelByParticipantId(e){if(!this._activeParticipants?.includes(e))return null;let t=null;return this._detectors.forEach((e,n)=>{if(!n.startsWith(`${Zr.TRANSPARENT_AUDIO_TRACK_PREFIX}-`))return;let r=e.getLevel();(!t||r.real>t.real)&&(t=r)}),t}_onSignalledActiveParticipants(e){this._removedParticipants=this._activeParticipants?.filter(t=>!e.includes(t))??null,this._activeParticipants=e}_onTopologyChanged(e){this._topology=e,this._destroyDetectors(),e===J.DIRECT&&(this._activeParticipants=null,this._removedParticipants=null)}_destroyDetectors(){this._detectors.forEach(e=>{e.destroy()}),this._detectors.clear()}},Fo=function(e){return e.SPEAKER_CHANGED=`SPEAKER_CHANGED`,e}({}),Io=class extends b{constructor(e,t,n){super(),h(this,`_speakerId`,null),h(this,`_serverSideSpeakerDetection`,!1),this._serverSideSpeakerDetection=n===J.SERVER,this.subscribe(e,No.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,Y.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,Y.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,n=null;if(Object.keys(e).forEach(r=>{let i=e[r].smoothed;i>t&&i>N.voiceParams.threshold&&(t=i,n=r)}),n&&n!==this._speakerId){let r=this._speakerId&&Object.hasOwn(e,this._speakerId)?e[this._speakerId].smoothed:0;t>r*N.voiceParams.speakerLevelMultiplier&&(this._speakerId=n,this._triggerEvent(`SPEAKER_CHANGED`,n))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent(`SPEAKER_CHANGED`,e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e===J.SERVER}},Lo=15e3,Ro=15e3,zo=class extends b{constructor(e,t,n,r=z,i=null){super(),h(this,`_transport`,void 0),h(this,`_volumes`,{}),h(this,`_participants`,{}),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_connectionTimeout`,0),h(this,`_connectionTimeoutSuppressed`,!1),h(this,`_volumeTimeout`,0),this._transport=e,this._participants=n,this._debug=r,this._logger=i,this.subscribe(e,Y.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,No.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)}onParticipantHoldChanged(){this._connectionTimeout||!this._connectionTimeoutSuppressed||this._reportConnectionTimeout()}_getConnectionTimeout(){return this._transport.getTopology()===J.DIRECT?Lo:N.specListenerParams.connectionTimeout}_getVolumeTimeout(){return this._transport.getTopology()===J.DIRECT?Ro:N.specListenerParams.volumeTimeout}_onTransportStateChanged(e,t){t===q.OPENED&&(this._connectionTimeout||(this._connectionTimeoutSuppressed=!1,this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),this._getConnectionTimeout()))),t===q.CONNECTED&&(this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),this._getVolumeTimeout())),this._volumeTimeout&&(window.clearTimeout(this._volumeTimeout),this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),this._getVolumeTimeout()))),t===q.FAILED&&this._connectionTimeout&&(this._debug.warn(`Transport failed, send callSpecError`),this._logger?.log(C.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(){this._reportConnectionTimeout(),this._connectionTimeout=0}_reportConnectionTimeout(){let e=!1,t=!1;Object.entries(this._transport.getStates()).forEach(([n,r])=>{if(r!==q.CONNECTED){if(this._participants[n]?.isOnHold){e=!0;return}t=!0}}),this._connectionTimeoutSuppressed=e&&!t,t&&(this._debug.warn(`There is not connected transport, send callSpecError`),this._logger?.log(C.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0||this._participants[t]?.isOnHold)return;let n=`UNKNOWN`,r=this._participants[t];r&&r.platform&&(n=r.platform),e.indexOf(n)<0&&(e.push(n),this._logger?.log(C.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${n}`))}),e.length&&this._debug.warn(`There is silent participant, send callSpecError`),this._volumeTimeout=0}},Bo=function(e){return e[e.PARAM_SESSION_EXPIRED=102]=`PARAM_SESSION_EXPIRED`,e[e.PARAM_SESSION_KEY=103]=`PARAM_SESSION_KEY`,e[e.PARAM_SIGNATURE=104]=`PARAM_SIGNATURE`,e[e.AUTH_LOGIN=401]=`AUTH_LOGIN`,e}(Bo||{});function Vo(e){return e===102||e===103||e===104}var Ho,Uo=`ok-calls-sdk-stats`,Wo=1,Go=`events`,Ko=100,qo=5e3,Jo=10080*60*1e3,Yo=5e3,Xo=6e4,Q=class e{static isSupported(){return e._supported}static async append(t){let n=await e._open();if(!n)return null;let r=await e._runTransaction(n,`readwrite`,e=>{let n=e.add(t);return new Promise(e=>{n.onsuccess=()=>e(n.result)})}).catch(e=>(z.error(`[StatQueue] failed to append event`,e),null));return r===null?null:(e._appendsSinceEvictCheck+=1,e._appendsSinceEvictCheck>=Ko&&(e._appendsSinceEvictCheck=0,await e.evictToLimit(qo)),r)}static async fillDelta(t,n){if(t.length===0)return;let r=await e._open();if(r)return e._runTransaction(r,`readwrite`,e=>new Promise(r=>{let i=t.length;for(let a of t){let t=e.get(a);t.onsuccess=()=>{let a=t.result;a&&typeof a.delta!=`number`&&e.put({...a,delta:n}),--i,i===0&&r()}}})).catch(e=>{z.error(`[StatQueue] failed to fill delta`,e)})}static async count(){let t=await e._open();return t?e._runTransaction(t,`readonly`,e=>{let t=e.count();return new Promise(e=>{t.onsuccess=()=>e(t.result)})}).catch(e=>(z.error(`[StatQueue] failed to count events`,e),0)):0}static async readOldest(t,n){let r=await e._open();return r?e._runTransaction(r,`readonly`,e=>{let r=e.index(`by_uid`).getAll(IDBKeyRange.only(t),n);return new Promise(e=>{r.onsuccess=()=>e(r.result)})}).catch(e=>(z.error(`[StatQueue] failed to read events`,e),[])):[]}static async remove(t){if(t.length===0)return;let n=await e._open();if(n)return e._runTransaction(n,`readwrite`,e=>{t.forEach(t=>e.delete(t))}).catch(e=>{z.error(`[StatQueue] failed to remove events`,e)})}static async listUids(){let t=await e._open();return t?e._runTransaction(t,`readonly`,e=>{let t=e.index(`by_uid`).openKeyCursor(null,`nextunique`),n=[];return new Promise(e=>{t.onsuccess=()=>{let r=t.result;if(!r){e(n);return}n.push(r.key),r.continue()}})}).catch(e=>(z.error(`[StatQueue] failed to list uids`,e),[])):[]}static async evictToLimit(t){let n=await e._open();if(!n)return;let r=1e3;for(;r>0;)if(--r,!await e._runTransaction(n,`readwrite`,async n=>{if(await new Promise(e=>{let t=n.count();t.onsuccess=()=>e(t.result)})<=t)return!1;let r=await e._readOldestRecord(n);return r?r.vcid===null?(n.delete(r.id),!0):(await e._deleteConversation(n,r.vcid),!0):!1}).catch(e=>(z.error(`[StatQueue] failed to evict events`,e),!1)))return}static async evictOlderThan(t,n=Date.now()){let r=await e._open();if(!r)return;let i=n-t;return e._runTransaction(r,`readwrite`,async t=>{let n=new Set;await new Promise(e=>{let r=t.openCursor();r.onsuccess=()=>{let t=r.result;if(!t){e();return}let a=t.value;a.ts<i&&(a.vcid===null?t.delete():n.add(a.vcid)),t.continue()}});for(let r of n)await e._deleteConversation(t,r)}).catch(e=>{z.error(`[StatQueue] failed to evict stale events`,e)})}static async __resetForTests(){if(e._appendsSinceEvictCheck=0,e._lastOpenFailureAt=null,e._supported=e._checkSupport(),e._dbName===Uo&&(e._dbName=`${Uo}-test-${Math.random().toString(36).slice(2)}`,e._close()),e._supported){let t=await e._open();t&&await e._runTransaction(t,`readwrite`,e=>{e.clear()}).catch(e=>{z.error(`[StatQueue] failed to reset storage`,e)})}e._close()}static _checkSupport(){return typeof window<`u`&&!!window.indexedDB}static _open(){if(!e._checkSupport())return e._supported=!1,Promise.resolve(null);if(e._dbPromise)return e._dbPromise;if(e._lastOpenFailureAt!==null&&Date.now()-e._lastOpenFailureAt<Xo)return Promise.resolve(null);let t=!1,n=new Promise(n=>{let r=(r,i)=>{t||(t=!0,z.error(r,i),e._supported=!1,e._dbPromise=null,e._lastOpenFailureAt=Date.now(),n(null))},i;try{i=window.indexedDB.open(e._dbName,Wo)}catch(e){r(`[StatQueue] storage is not accessible`,e);return}let a=window.setTimeout(()=>r(`[StatQueue] storage opening timed out`),Yo);i.onupgradeneeded=()=>{e._createSchema(i.result)},i.onsuccess=()=>{if(window.clearTimeout(a),t){i.result.close();return}t=!0,e._db=i.result,e._supported=!0,e._lastOpenFailureAt=null,e._db.onversionchange=()=>e._close(),e._db.onclose=()=>e._close(),n(e._db)},i.onerror=()=>{window.clearTimeout(a),r(`[StatQueue] failed to open storage`,i.error)},i.onblocked=()=>{z.error(`[StatQueue] storage opening is blocked`)}});return t||(e._dbPromise=n),n}static _close(){e._db&&(e._db.close(),e._db=null),e._dbPromise=null}static _createSchema(e){if(e.objectStoreNames.contains(Go))return;let t=e.createObjectStore(Go,{keyPath:`id`,autoIncrement:!0});t.createIndex(`by_uid`,`uid`,{unique:!1}),t.createIndex(`by_vcid`,`vcid`,{unique:!1})}static _runTransaction(e,t,n){return new Promise((r,i)=>{let a=e.transaction(Go,t),o;a.oncomplete=()=>r(o),a.onerror=()=>i(a.error),a.onabort=()=>i(a.error),Promise.resolve(n(a.objectStore(Go))).then(e=>{o=e}).catch(e=>{try{a.abort()}catch{}i(e)})})}static _readOldestRecord(e){let t=e.openCursor();return new Promise(e=>{t.onsuccess=()=>e(t.result?t.result.value:null)})}static _deleteConversation(e,t){let n=e.index(`by_vcid`).getAllKeys(IDBKeyRange.only(t));return new Promise(t=>{n.onsuccess=()=>{n.result.forEach(t=>e.delete(t)),t()}})}};Ho=Q,h(Q,`_db`,null),h(Q,`_dbPromise`,null),h(Q,`_dbName`,Uo),h(Q,`_supported`,Ho._checkSupport()),h(Q,`_appendsSinceEvictCheck`,0),h(Q,`_lastOpenFailureAt`,null);var Zo=null,Qo=null,$o=64*1024;function es(){Zo=null,Qo=null}function ts(e){return e?.endsWith(`/`)?e.slice(0,-1):e}async function ns(e=null,t){let n=ts(e??N.apiBaseUrl);if(n)return n;if((t??N.apiEnv)!==`AUTO`)return N.apiEndpoint(t);try{let e=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),t=(await(await fetch(e,{method:`GET`,mode:`cors`,cache:`no-cache`})).json())?.Answer[0]?.data;if(!t)throw Error(`Wrong DNS response`);return z.debug(`Resolved API endpoint`,t),t}catch(e){return z.warn(`Failed to resolve API endpoint using DNS, default is used`,e),N.apiEndpoint(t)}}async function rs(){return Zo||Qo||(Qo=ns(),Zo=await Qo,Qo=null,Zo)}async function is(e,t={},n=!1){if(!window.Blob||!window.navigator.sendBeacon)return;await rs();let r=us(e,t,n),i=new window.Blob([r],{type:`application/x-www-form-urlencoded`});window.navigator.sendBeacon(`${Zo}/fb.do`,i)}async function as(e,t={},n=!1,r){return await rs(),ss(us(e,t,n),r)}async function os(e,t={},n=!1){await rs();let r=us(e,t,n);return ss(r,void 0,new Blob([r]).size<=$o)}async function ss(e,t,n=!1){let r=`${t??Zo}/fb.do`,i=new AbortController,a=new k(x.NETWORK,{callError:{scope:`network`,source:`api`,code:`timeout`,description:`request-timeout`}}),o=setTimeout(()=>i.abort(a),N.apiTimeout);try{let t=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:e,signal:i.signal,...n&&{keepalive:!0}}),a=await t.text(),o;try{o=JSON.parse(a)}catch{o={result:a}}if(!t.ok&&!cs(o))throw new k(x.API,{callError:{scope:`server`,source:`api`,code:`http-${t.status}`,description:`http-error`}});if(cs(o))throw o;return o}catch(e){throw e instanceof k?e:i.signal.aborted?a:cs(e)?e:new k(x.NETWORK,{callError:{scope:`network`,source:`api`,code:`fetch-failed`,description:`request-failed`}})}finally{clearTimeout(o)}}function cs(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.error_code==`number`&&typeof t.error_msg==`string`}async function ls(e,t){try{let n=await fetch(e,{method:`POST`,body:t});if(!n.ok)throw Error(`HTTP error! status: ${n.status}`);let r=await n.text();z.debug(`Form data sent successfully`,r)}catch(e){throw z.warn(`Failed to send form data`,e),e}}function us(e,t={},n=!1){t.method=e,t.format=`JSON`,t.application_key||(t.application_key=N.apiKey),n||(y.sessionKey?t.session_key=y.sessionKey:y.accessToken&&(t.access_token=y.accessToken));for(let[e,n]of Object.entries(t))typeof n==`object`&&(t[e]=JSON.stringify(n));let r=``;for(let[e,n]of Object.entries(t))r&&(r+=`&`),r+=`${e}=${encodeURIComponent(n)}`;return r}var ds=`sessions`,fs=5,ps=class e{static remember(t,n){let r=e._read();r[String(t)]={...n,savedAt:Date.now()};let i=Object.keys(r);i.length>fs&&i.sort((e,t)=>r[e].savedAt-r[t].savedAt).slice(0,i.length-fs).forEach(e=>delete r[e]),e._write(r)}static get(t){return e._read()[String(t)]??null}static forget(t){let n=e._read();String(t)in n&&(delete n[String(t)],e._write(n))}static prune(t=Date.now()){let n=e._read(),r=!1;Object.keys(n).forEach(e=>{t-n[e].savedAt>6048e5&&(delete n[e],r=!0)}),r&&e._write(n)}static currentEndpoint(){return String(ts(N.apiBaseUrl)||N.apiEndpoint())}static _read(){let t=w.get(ds);if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};return Object.entries(t).forEach(([t,r])=>{e._isValid(r)&&(n[t]=r)}),n}static _write(e){if(Object.keys(e).length===0){w.remove(ds);return}w.set(ds,e)}static _isValid(e){let t=e;return typeof t==`object`&&!!t&&typeof t.sessionKey==`string`&&t.sessionKey.length>0&&typeof t.endpoint==`string`&&typeof t.savedAt==`number`}},ms=15e3,hs=class e{static setApi(t){e._api=t}static delta(){return e._delta}static ensure(){e._delta===null&&e._api&&e.get()}static get(){return e._delta===null?!e._api||!e._hasCredentials()||e._lastFailureAt!==null&&Date.now()-e._lastFailureAt<ms?Promise.resolve(0):(e._pending||(e._pending=e._measure().finally(()=>{e._pending=null})),e._pending):Promise.resolve(e._delta)}static noteAppended(t){if(e._delta!==null){Q.fillDelta([t],e._delta);return}e._idsAwaitingDelta.push(t)}static __resetForTests(){e._api=null,e._delta=null,e._pending=null,e._idsAwaitingDelta=[],e._lastFailureAt=null}static _hasCredentials(){return!!y.sessionKey||!!y.accessToken}static async _measure(){let t;try{let n=await e._api.getServerTime();t=Date.now()-n}catch{return e._lastFailureAt=Date.now(),0}e._lastFailureAt=null,e._delta=t;let n=e._idsAwaitingDelta;return e._idsAwaitingDelta=[],await Q.fillDelta(n,t),t}};h(hs,`_api`,null),h(hs,`_delta`,null),h(hs,`_pending`,null),h(hs,`_idsAwaitingDelta`,[]),h(hs,`_lastFailureAt`,null);var gs=`okcls-stat-unload.`,_s=class e{static beginTabSession(){e._tabKey=null,e._entries=[]}static writeSync(t){let n=e._storage();if(!n)return!1;try{return e._tabKey||(e._tabKey=gs+M.uuid()),e._entries.length>0&&n.getItem(e._tabKey)===null&&(e._entries=[]),e._entries.push(t),n.setItem(e._tabKey,JSON.stringify(e._entries)),!0}catch(e){return z.error(`[StatUnloadJournal] failed to write`,e),!1}}static async drainToQueue(){let t=e._storage();if(!t)return 0;let n=[];try{for(let e=0;e<t.length;e+=1){let r=t.key(e);r&&r.startsWith(gs)&&n.push(r)}}catch(e){return z.error(`[StatUnloadJournal] failed to scan journals`,e),0}let r=0;e.beginTabSession();for(let i of n){let n=e._take(t,i);if(n===null)continue;let a=null;try{a=JSON.parse(n)}catch{z.error(`[StatUnloadJournal] dropping corrupted journal`,i)}if(Array.isArray(a))for(let t of a)e._isValidEntry(t)&&await Q.append(t)&&(r+=1)}return r}static __resetForTests(){e._tabKey=null,e._entries=[]}static _take(e,t){try{let n=e.getItem(t);return n===null?null:(e.removeItem(t),n)}catch(e){return z.error(`[StatUnloadJournal] failed to take journal`,e),null}}static _storage(){try{return window.localStorage}catch{return null}}static _isValidEntry(e){let t=e;return typeof t==`object`&&!!t&&typeof t.uid==`number`&&(t.vcid===null||typeof t.vcid==`string`)&&typeof t.ts==`number`&&(t.delta===void 0||t.delta===null||typeof t.delta==`number`)&&typeof t.ev==`object`&&t.ev!==null}};h(_s,`_tabKey`,null),h(_s,`_entries`,[]);var vs=500,ys=100,bs=3e4,xs=1e3,Ss=5e3,Cs=3e3,ws=`okcls-stat-drain`,Ts=class e{static setApi(t){e._api=t,hs.setApi(t)}static start(t){e.setApi(t),_s.drainToQueue().catch(e=>z.error(`[StatDrainScheduler] failed to import unload journal`,e)).then(async()=>(ps.prune(),await Q.evictOlderThan(Jo),await Q.evictToLimit(qo),e._drain())).catch(e=>z.error(`[StatDrainScheduler] failed to start`,e))}static notifyAppended(){if(e._api){if(e._localCount+=1,e._localCount>=ys){e._drain();return}e._state===`IDLE`&&e._arm(bs)}}static notifyCallFinished(){if(e._api){if(e._directBuffer.length>0&&e._armDirect(xs),e._state===`DRAINING`){e._callFinishedDuringDrain=!0;return}e._arm(xs)}}static drainOnce(){return e._withLock(async()=>{let t=e._api;if(!t)return!1;let n=e._currentUserId(),r=await Q.listUids(),i=!1,a=null;for(let o of r)try{(o===n?await e._drainCurrent(t,o):await e._drainStored(t,o))===vs&&(i=!0)}catch(e){a===null&&(a=e)}if(a!==null)throw a;return i})}static sendDirect(t){if(e._api){if(t.uid!==e._currentUserId()){z.error(`[StatDrainScheduler] direct send skipped: event belongs to another user`);return}e._directBuffer.push(t),e._directTimer===null&&e._armDirect(Cs)}}static __resetForTests(){hs.__resetForTests(),e._clearTimer(),e._clearDirectTimer(),e._directBuffer=[],e._api=null,e._state=`IDLE`,e._localCount=0,e._callFinishedDuringDrain=!1,e._blockedSession=null}static _currentUserId(){return y.userId}static async _drainCurrent(t,n){if(e._isSessionBlocked())return 0;let r=await Q.readOldest(n,vs);if(r.length===0)return 0;let i=await hs.get(),a=r.map(t=>e._toClientStats(t,i)),o=r.map(e=>e.id);try{await t.logClientStats(a)}catch(t){if(e._isRetryable(t))throw t;if(e._isReauthorizeFailure(t))throw e._blockSession(),t;return z.error(`[StatDrainScheduler] batch rejected, dropping`,t),await Q.remove(o),r.length}return await Q.remove(o),r.length}static async _drainStored(t,n){let r=ps.get(n);if(!r||r.endpoint!==ps.currentEndpoint())return 0;let i=await Q.readOldest(n,vs);if(i.length===0)return 0;let a=await hs.get(),o=i.map(t=>e._toClientStats(t,a)),s=i.map(e=>e.id);try{await t.logClientStatsWith(r.sessionKey,o),z.debug(`[StatDrainScheduler] delivered`,i.length,`stored events of uid`,n)}catch(t){if(e._isAuthError(t))return z.error(`[StatDrainScheduler] stored session expired, skipping uid`,n),ps.forget(n),0;if(e._isRetryable(t))throw t;return z.error(`[StatDrainScheduler] batch rejected, dropping`,t),await Q.remove(s),i.length}return await Q.remove(s),i.length}static _withLock(e){return typeof navigator>`u`||!navigator.locks?e():navigator.locks.request(ws,e)}static _isSessionError(e){return Vo(e?.error_code)}static _isReauthorizeFailure(e){return e?.error===x.AUTH}static _blockSession(){e._blockedSession={key:y.sessionKey}}static _isSessionBlocked(){return e._blockedSession?e._blockedSession.key===y.sessionKey?!0:(e._blockedSession=null,!1):!1}static _isAuthError(t){let n=t?.error_code;return e._isSessionError(t)||n===Bo.AUTH_LOGIN}static _isRetryable(t){if(e._isSessionError(t))return!0;let n=t?.callError;return n?n.scope===`network`?!0:!(`code`in n)||typeof n.code!=`string`?!1:n.code.startsWith(`http-5`)||n.code===`http-429`:!1}static _toClientStats(e,t){return{...e.ev,vcid:e.vcid,timestamp:e.ts-(e.delta??t)}}static _clearDirectTimer(){e._directTimer!==null&&(window.clearTimeout(e._directTimer),e._directTimer=null)}static _armDirect(t){e._clearDirectTimer(),e._directTimer=window.setTimeout(()=>{e._directTimer=null,e._flushDirect()},t)}static async _flushDirect(){let t=e._api,n=e._directBuffer;if(e._directBuffer=[],!(!t||n.length===0))try{let r=await hs.get();await t.logClientStats(n.map(t=>e._toClientStats(t,r)))}catch(e){z.error(`[StatDrainScheduler] direct send failed, events lost`,e)}}static _clearTimer(){e._timer!==null&&(window.clearTimeout(e._timer),e._timer=null)}static _arm(t){e._clearTimer(),e._state=`ARMED`,e._timer=window.setTimeout(()=>{e._timer=null,e._drain()},t)}static async _drain(){if(e._state!==`DRAINING`){e._clearTimer(),e._state=`DRAINING`,e._localCount=0,e._callFinishedDuringDrain=!1;try{if(await e.drainOnce()){e._arm(Ss);return}if(e._callFinishedDuringDrain){e._arm(xs);return}if(e._localCount>0){e._arm(bs);return}e._state=`IDLE`}catch(t){z.error(`[StatDrainScheduler] drain failed`,t),e._arm(bs)}}}};h(Ts,`_api`,null),h(Ts,`_state`,`IDLE`),h(Ts,`_timer`,null),h(Ts,`_localCount`,0),h(Ts,`_callFinishedDuringDrain`,!1),h(Ts,`_blockedSession`,null),h(Ts,`_directBuffer`,[]),h(Ts,`_directTimer`,null);var Es=class extends m{constructor(e,t,n,r=()=>void 0){super(),h(this,`_externalLogger`,void 0),h(this,`_api`,void 0),h(this,`_conversationIdProvider`,void 0),h(this,`_topologyProvider`,void 0),h(this,`_batchInterval`,3e3),h(this,`_batchedClientStats`,[]),h(this,`_batchTimeout`,null),h(this,`_serverTimeDelta`,0),h(this,`_waitingForServerTime`,!0),h(this,`_deferredClientStats`,[]),this._api=e,this._externalLogger=t,this._conversationIdProvider=n,this._topologyProvider=r,this._calculateServerTimeDelta()}log(e,t,n=!1){this._externalLogger&&this._externalLogger.log(e,t,n)}logClientStats(e,t=!1){let n=typeof t==`boolean`?{immediately:t}:t,r={...e,call_topology:e.call_topology??this._getCallTopology()};if(n.deferUntilServerTime&&this._waitingForServerTime){this._deferredClientStats.push({data:r,options:{...n}}),n.immediately&&this._flushDeferredClientStats();return}this._logClientStats(r,n)}destroy(){this._flushDeferredClientStats(),this._sendBatch(),this._stopTimeout()}_logClientStats(e,t){let n={...e,vcid:t.conversationId===void 0?this._getConversationId():t.conversationId,timestamp:t.occurredAt===void 0?this._now():t.occurredAt-this._serverTimeDelta};Object.keys(n).forEach(e=>{n[e]===void 0&&delete n[e]}),this._batchedClientStats.push(n),(t.immediately||!this._batchTimeout)&&this._sendBatch()}_getConversationId(){try{return this._conversationIdProvider()}catch{return null}}_getCallTopology(){try{return this._topologyProvider()===J.SERVER?`S`:`D`}catch{return`D`}}_sendBatch(){this._stopTimeout();let e=!1;this._batchedClientStats.length>0&&(this._sendClientStats(this._batchedClientStats),this._batchedClientStats=[],e=!0),e&&this._startTimeout()}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_sendClientStats(e){this._api.logClientStats(e)}async _calculateServerTimeDelta(){try{let e=await this._api.getServerTime();this._serverTimeDelta=Date.now()-e}catch{}finally{this._flushDeferredClientStats()}}_flushDeferredClientStats(){if(!this._waitingForServerTime)return;this._waitingForServerTime=!1;let e=this._deferredClientStats;this._deferredClientStats=[];for(let{data:t,options:n}of e)this._logClientStats(t,n)}_now(){return Date.now()-this._serverTimeDelta}},Ds=class e extends m{static __resetForTests(){e._pending=[],e._pendingOverflow=!1}static _remember(t){if(e._pending.length>=5e3){e._pendingOverflow||(e._pendingOverflow=!0,z.error(`[StatEventCollector] pending buffer is full, dropping events until userId is known`));return}e._pending.push(t)}static _takePending(){let t=e._pending;return e._pending=[],e._pendingOverflow=!1,t}constructor(e,t,n,r=()=>void 0){super(),h(this,`_externalLogger`,void 0),h(this,`_conversationIdProvider`,void 0),h(this,`_topologyProvider`,void 0),h(this,`_unloadMode`,!1),h(this,`_legacy`,void 0),this._externalLogger=t,this._conversationIdProvider=n,this._topologyProvider=r,this._legacy=N.statQueueEnabled?null:new Es(e,t,n,r)}log(e,t,n=!1){this._externalLogger&&this._externalLogger.log(e,t,n)}enterUnloadMode(){this._legacy||(this._unloadMode=!0,_s.beginTabSession())}exitUnloadMode(){this._legacy||!this._unloadMode||(this._unloadMode=!1,_s.drainToQueue().then(e=>{e>0&&Ts.notifyAppended()}).catch(e=>z.error(`[StatEventCollector] failed to import unload journal`,e)))}logClientStats(t,n={}){if(this._legacy){this._legacy.logClientStats(t,n);return}let r={...t,call_topology:t.call_topology??this._getCallTopology()};Object.keys(r).forEach(e=>{r[e]===void 0&&delete r[e]}),hs.ensure();let i={vcid:n.conversationId===void 0?this._getConversationId():n.conversationId,ts:n.occurredAt===void 0?Date.now():n.occurredAt,delta:hs.delta(),ev:r},a=y.userId;if(a===null){e._remember(i);return}for(let t of e._takePending())this._store({...t,uid:a});this._store({...i,uid:a})}destroy(){if(this._legacy){this._legacy.destroy();return}}_store(e){this._unloadMode&&_s.writeSync(e)||Q.append(e).then(t=>{if(t!==null){typeof e.delta!=`number`&&hs.noteAppended(t),Ts.notifyAppended();return}z.error(`[StatEventCollector] failed to store event, sending directly`),Ts.sendDirect(e)}).catch(e=>z.error(`[StatEventCollector] failed to store event`,e))}_getConversationId(){try{return this._conversationIdProvider()}catch{return null}}_getCallTopology(){try{return this._topologyProvider()===J.SERVER?`S`:`D`}catch{return`D`}}};h(Ds,`_pending`,[]),h(Ds,`_pendingOverflow`,!1);var Os=`invalid-error-metadata`,ks=64,As=new Set(Object.values(O)),js=new Set(Object.values(x)),Ms={[O.CANCELED]:{type:`semantic`,reason:`canceled`},[O.REJECTED]:{type:`semantic`,reason:`rejected`},[O.REMOVED]:{type:`semantic`,reason:`removed`},[O.HUNGUP]:{type:`semantic`,reason:`hangup`},[O.MISSED]:{type:`semantic`,reason:`missed`},[O.BUSY]:{type:`semantic`,reason:`busy`},[O.FAILED]:{type:`failed`},[O.NETWORK_ERROR]:{type:`requires-call-error`},[O.KILLED]:{type:`semantic`,reason:`killed`},[O.BANNED]:{type:`semantic`,reason:`banned`},[O.HAS_ACTIVE_CALL]:{type:`semantic`,reason:`initially_closed`},[O.CALLER_IS_BLOCKED]:{type:`requires-call-error`},[O.NOT_FRIENDS]:{type:`direct-error`,error:{scope:`server`,source:`api`,code:1103,description:`friendship-required`}},[O.CALLEE_IS_OFFLINE]:{type:`direct-error`,error:{scope:`server`,source:`api`,code:1102,description:`target-user-unavailable`}},[O.CALLEE_UNAVAILABLE]:{type:`semantic`,reason:`unavailable`},[O.CALLER_IS_REJECTED]:{type:`direct-error`,error:{scope:`server`,source:`api`,code:1113,description:`caller-is-rejected`}},[O.UNKNOWN_ERROR]:{type:`failed`},[O.UNSUPPORTED]:{type:`direct-error`,error:{scope:`internal`,code:`observer-mode`,description:`video-tracks-count-must-be-zero`}},[O.SERVICE_DISABLED]:{type:`direct-error`,error:{scope:`server`,source:`api`,code:1101,description:`vchat-service-disabled`}},[O.SERVICE_UNAVAILABLE]:{type:`requires-call-error`},[O.EXTERNAL_API_ERROR]:{type:`requires-call-error`},[O.SOCKET_CLOSED]:{type:`semantic`,reason:`socket_closed`},[O.ENDED]:{type:`requires-call-error`},[O.KILLED_WITHOUT_DELETE]:{type:`semantic`,reason:`killed_without_delete`},[O.ANOTHER_DEVICE]:{type:`semantic`,reason:`another_device`},[O.NOT_FOUND]:{type:`requires-call-error`},[O.VCHAT_DETAILED_ERROR]:{type:`requires-call-error`},[O.TIMEOUT]:{type:`semantic`,reason:`timeout`},[O.PARTICIPANT_LIMIT_REACHED]:{type:`requires-call-error`},[O.FAST_START_ERROR]:{type:`failed`},[O.FAST_JOIN_ERROR]:{type:`failed`},[O.CALL_TIMEOUT]:{type:`semantic`,reason:`call_timeout`},[O.OBSOLETE_CLIENT]:{type:`semantic`,reason:`obsolete_client`}},Ns={[x.MIC_CAMERA_PERMISSION]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`mic-camera-permission`}},[x.CAMERA_PERMISSION]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`camera-permission`}},[x.MIC_PERMISSION]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`microphone-permission`}},[x.CAMERA_ACCESS]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`camera-access`}},[x.MIC_ACCESS]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`microphone-access`}},[x.MIC_NOT_FOUND]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`microphone-not-found`}},[x.SCREEN_PERMISSION]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`screen-permission`}},[x.SCREEN_ACCESS]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`screen-access`}},[x.CONNECTION]:{type:`direct-error`,error:{scope:`network`,source:`rtc`,code:`connection`,description:`connection-failed`}},[x.NETWORK]:{type:`requires-call-error`},[x.UNKNOWN]:{type:`failed`},[x.UNSUPPORTED]:{type:`requires-call-error`},[x.SIGNALING_FAILED]:{type:`requires-call-error`},[x.API]:{type:`requires-call-error`},[x.AUTH]:{type:`requires-call-error`},[x.OVERCONSTRAINED]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`overconstrained`}}};function Ps(e){if(typeof e!=`string`&&typeof e!=`number`||typeof e==`number`&&!Number.isFinite(e))return Os;let t=String(e).trim();if(!t)return Os;let n=t.toLowerCase().replace(/[\s_:]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);return!n||!/^[a-z0-9.-]+$/.test(n)?Os:n.length>ks?`${n.slice(0,ks-3)}...`:n}function Fs(e){if(!e||typeof e!=`object`)return!1;let t=e;switch(t.scope){case`unknown`:case`internal`:return!0;case`external`:return t.source===`api`;case`server`:return t.source===`api`||t.source===`ws`||t.source===`wt`;case`network`:return t.source===`api`||t.source===`rtc`||t.source===`ws`||t.source===`wt`;default:return!1}}function Is(e){let t=Ps(e.description);if(e.scope===`unknown`)return`unknown:${t}`;let n=Ps(e.code);return e.scope===`internal`?`internal:${n}:${t}`:`${e.scope}:${e.source}:${n}:${t}`}function Ls(e,t){return t===null?e.type===`direct-error`?{reason:`error`,string_value:Is(e.error)}:{reason:`failed`}:Fs(t)?{reason:`error`,string_value:Is(t)}:{reason:`failed`}}function Rs(e){if(e.hangup){let t=Ms[e.hangup];return t?t.type===`semantic`?e.hangup===O.OBSOLETE_CLIENT&&e.custom_error?.vchat_detailed_api_error.code?{reason:t.reason,string_value:e.custom_error.vchat_detailed_api_error.code}:{reason:t.reason}:Ls(t,e.callError):{reason:`failed`}}if(e.error){let t=Ns[e.error];return t?Ls(t,e.callError):{reason:`failed`}}return{reason:`failed`}}function zs(e){return e instanceof k?Rs(e):typeof e==`string`&&(As.has(e)||js.has(e))?Rs(new k(e)):{reason:`failed`}}var Bs={wallNow:()=>Date.now(),monotonicNow:()=>performance.now()};function Vs(e){return e===`anonym_join`?`join`:e}var Hs=class{constructor(e,t=Bs){h(this,`_logger`,void 0),h(this,`_clock`,void 0),h(this,`_conversationId`,null),h(this,`_callStartLabel`,null),h(this,`_lifecycleStartedAtMonotonic`,0),h(this,`_pendingEvents`,[]),h(this,`_callStarted`,!1),h(this,`_accepted`,!1),h(this,`_firstMediaSent`,!1),h(this,`_finished`,!1),h(this,`_destroyed`,!1),this._logger=e,this._clock=t}get firstMediaSentReported(){return this._firstMediaSent}get terminated(){return this._finished||this._destroyed}markInitializationStarted({source:e,conversationId:t}){if(this._destroyed||this._callStartLabel!==null)return;let n=this._clock.wallNow();this._callStartLabel=Vs(e),this._lifecycleStartedAtMonotonic=this._clock.monotonicNow(),t&&(this._conversationId=t),this._record({name:U.CALL_INIT,source:e},n)}bindConversationId(e){this._destroyed||this._conversationId||!e||(this._conversationId=e,this._flushPendingEvents())}markCallStarted(){!this._canRecord()||this._callStarted||!this._callStartLabel||(this._callStarted=!0,this._record({name:U.CALL_START,value:this._durationSince(this._lifecycleStartedAtMonotonic),string_value:JSON.stringify({labels:[this._callStartLabel]})}))}markOutgoingAccepted(){!this._canRecord()||this._accepted||(this._accepted=!0,this._record({name:U.CALL_ACCEPTED_OUTGOING}))}markIncomingAccepted(e){!this._canRecord()||this._accepted||(this._accepted=!0,this._record({name:U.CALL_ACCEPTED_INCOMING,...e&&{string_value:`concurrent`}}))}markFirstMediaSent(){!this._canRecord()||this._firstMediaSent||(this._firstMediaSent=!0,this._record({name:U.FIRST_MEDIA_SENT}))}markFinished(e){this._finish(zs(e))}markTerminated(){this._finish({reason:`terminated`})}destroy(){this._destroyed||(this._destroyed=!0,this._pendingEvents=[])}_canRecord(){return this._callStartLabel!==null&&!this._finished&&!this._destroyed}_durationSince(e){return Math.max(0,Math.round(this._clock.monotonicNow()-e))}_finish({reason:e,string_value:t}){this._canRecord()&&(this._finished=!0,this._ensureConversationId(),this._record({name:U.CALL_FINISH,reason:e,...t&&{string_value:t}},void 0,!0))}_ensureConversationId(){this._conversationId||(this._conversationId=M.uuid(),this._flushPendingEvents())}_record(e,t=this._clock.wallNow(),n=!1){if(this._destroyed)return;let r={data:e,occurredAt:t,immediately:n};if(!this._conversationId){this._pendingEvents.push(r);return}this._logEvent(r)}_flushPendingEvents(){if(!this._conversationId||!this._pendingEvents.length)return;let e=this._pendingEvents;this._pendingEvents=[];for(let t of e)this._logEvent(t)}_logEvent({data:e,occurredAt:t,immediately:n}){this._logger.logClientStats(e,{conversationId:this._conversationId,deferUntilServerTime:!0,occurredAt:t,...n&&{immediately:!0}})}},Us=class{constructor(e,t){h(this,`_logger`,void 0),h(this,`_codecUsages`,new Map),h(this,`getCurrentTransportTopology`,void 0),this._logger=e,this.getCurrentTransportTopology=t}reportUsage(e){let t=this.getCurrentTransportTopology();if(!t)return;let n=e.rtps.filter(e=>e.type===`outbound-rtp`&&!e.mid?.endsWith(`s`));N.simulcast&&(n=n.reduce((e,t)=>{if(t.kind!==`video`)return e.concat(t);let n=e.find(e=>e.kind===`video`);return n?n.totalEncodeTime=(n.totalEncodeTime??0)+(t.totalEncodeTime??0):e.push(t),e},[])),n.forEach(e=>{let n=e.kind,r=e.mimeType;if((n===`audio`||n===`video`)&&r){let i=[r,`encoder`,e.encoderImplementation].filter(Boolean).join(`/`);this.saveUsage({kind:n,codecName:i,totalEncodeTime:(e.totalEncodeTime??0)*1e3,audioCodecParams:e.sdpFmtpLine,topology:t})}})}saveUsage({kind:e,codecName:t,totalEncodeTime:n,audioCodecParams:r,topology:i}){let a=this._codecUsages.get(e);if(a&&a.codecName!==t&&this.report(a),a&&a.codecName===t){this._codecUsages.set(e,{...a,totalEncodeTime:n,topology:i});return}this._codecUsages.set(e,{kind:e,codecName:t,audioCodecParams:r,totalEncodeTime:n,topology:i})}report(e){if(e.kind===`video`&&e.totalEncodeTime===0)return;let t={name:U.CODEC_USAGE,codec_implementation:e.codecName,value:Number.parseFloat(e.totalEncodeTime.toFixed(3)),call_topology:e.topology===J.DIRECT?`D`:`S`};e.audioCodecParams&&(t.string_value=e.audioCodecParams),this._logger.logClientStats(t)}destroy(){this._codecUsages.forEach(e=>{this.report(e)}),this._codecUsages.clear()}},Ws=class{constructor(e){h(this,`_logger`,void 0),h(this,`_eventualLogs`,new Set),h(this,`_lastCallStatContext`,null),this._logger=e}logCallStat(e){this._lastCallStatContext=this._getCallStatContext(e),this._flushEventualStats(),this._logger.logClientStats(e)}logEventualStat(e){let t=Date.now();e.value===void 0&&(e.value=G.measureMark(e.name)),e.value!==null&&this._eventualLogs.add({data:e,occurredAt:t})}destroy(){this._flushEventualStats()}_getCallStatContext(e){return{call_topology:e.call_topology,local_address:e.local_address,local_connection_type:e.local_connection_type,network_type:e.network_type,remote_address:e.remote_address,remote_connection_type:e.remote_connection_type,transport:e.transport}}_flushEventualStats(){let e=[...this._eventualLogs];for(let t of e)this._logEventualStat(t),this._eventualLogs.delete(t)}_logEventualStat({data:e,occurredAt:t}){this._logger.logClientStats({...e,...this._lastCallStatContext??{}},{occurredAt:t})}},Gs=class{constructor(e){if(h(this,`q`,void 0),h(this,`inits`,[]),h(this,`n`,[1,2,3,4,5]),h(this,`np`,[1,1,1,1,1]),h(this,`qv`,[]),!(e>0&&e<1))throw Error(`q must be in (0,1)`);this.q=e}add(e){if(this.inits.length<5){this.inits.push(e),this.inits.length===5&&this.bootstrap();return}let t=0;if(e<this.qv[0])this.qv[0]=e,t=0;else if(e>=this.qv[4])this.qv[4]=e,t=3;else for(;!(e<this.qv[t+1]);)t++;for(let e=0;e<5;e++)this.n[e]+=e<=t?0:1;this.np[0]=1,this.np[1]+=this.q/2,this.np[2]+=this.q,this.np[3]+=(1+this.q)/2,this.np[4]+=1;for(let e=1;e<=3;e++){let t=this.np[e]-this.n[e];if(t>=1&&this.n[e+1]-this.n[e]>1||t<=-1&&this.n[e]-this.n[e-1]>1){let n=Math.sign(t),r=this.qv[e]+n/(this.n[e+1]-this.n[e-1])*((this.n[e]-this.n[e-1]+n)*(this.qv[e+1]-this.qv[e])/(this.n[e+1]-this.n[e])+(this.n[e+1]-this.n[e]-n)*(this.qv[e]-this.qv[e-1])/(this.n[e]-this.n[e-1]));r>this.qv[e-1]&&r<this.qv[e+1]?this.qv[e]=r:this.qv[e]=this.qv[e]+n*(this.qv[e+n]-this.qv[e])/(this.n[e+n]-this.n[e]),this.n[e]+=n}}}value(){if(this.inits.length===0)return NaN;if(this.inits.length<5){let e=[...this.inits].sort((e,t)=>e-t),t=this.q*(e.length-1),n=Math.floor(t),r=t-n;return n+1<e.length?e[n]*(1-r)+e[n+1]*r:e[n]}return this.qv[2]}bootstrap(){this.inits.sort((e,t)=>e-t),this.qv=this.inits.slice(0,5),this.n=[1,2,3,4,5],this.np=[1,1+2*this.q,1+4*this.q,3+2*this.q,5]}},Ks=class{constructor(){h(this,`n`,0),h(this,`mean`,0)}add(e){this.n++;let t=e-this.mean;this.mean+=t/this.n}get avg(){return this.n?this.mean:NaN}},qs=class{constructor(){h(this,`count`,0),h(this,`minVal`,1/0),h(this,`maxVal`,-1/0),h(this,`mean`,new Ks),h(this,`p50`,new Gs(.5)),h(this,`p95`,new Gs(.95))}add(e){e<this.minVal&&(this.minVal=e),e>this.maxVal&&(this.maxVal=e),this.mean.add(e),this.p50.add(e),this.p95.add(e),this.count++}snapshot(){return{min:this.minVal===1/0?NaN:this.minVal,max:this.maxVal===-1/0?NaN:this.maxVal,avg:+this.mean.avg.toFixed(),median:+this.p50.value().toFixed(),p95:+this.p95.value().toFixed(),count:this.count}}get hasData(){return this.count>0}},Js=class{constructor(e){h(this,`_logger`,void 0),h(this,`trackerByTransport`,{ws:new qs,wt:new qs}),h(this,`lastSeen`,{}),this._logger=e}mark(e){let t=Date.now(),n=this.lastSeen[e];if(typeof n==`number`){let r=t-n;r>=0&&this.trackerByTransport[e].add(r)}this.lastSeen[e]=t}logMetrics(){[Cr.WEBSOCKET,Cr.WEBTRANSPORT].forEach(e=>{if(!this.trackerByTransport[e].hasData)return;let t=this.trackerByTransport[e].snapshot();this._logger.logClientStats({name:U.SIGNALING_PING_SUMMARY,min_value:t.min,max_value:t.max,avg_value:t.avg,median_value:t.median,p95_value:t.p95,values_count:t.count,signaling_transport:e})})}destroy(){this.trackerByTransport={ws:new qs,wt:new qs},this.lastSeen={}}},Ys=class{constructor(e){h(this,`_logger`,void 0),h(this,`trackerByCommand`,new Map),this._logger=e}mark(e,t,n){let r=`${e}|${n}`,i;this.trackerByCommand.has(r)?i=this.trackerByCommand.get(r):(i=new qs,this.trackerByCommand.set(r,i)),i.add(t)}logMetrics(){for(let[e,t]of this.trackerByCommand.entries()){if(!t.hasData)continue;let[n,r]=e.split(`|`),i=t.snapshot();this._logger.logClientStats({name:U.SIGNALING_COMMAND_SUMMARY,api_method:n,min_value:i.min,max_value:i.max,avg_value:i.avg,median_value:i.median,p95_value:i.p95,values_count:i.count,signaling_transport:r})}}destroy(){this.trackerByCommand.clear()}},Xs=class{constructor(e,t,n,r){h(this,`logger`,void 0),h(this,`lifecycle`,void 0),h(this,`statAggregator`,void 0),h(this,`codecStatsAggregator`,void 0),h(this,`pings`,void 0),h(this,`signalingCommands`,void 0),h(this,`_unloading`,!1),this.logger=new Ds(e,t,n,r),this.lifecycle=new Hs(this.logger),this.statAggregator=new Ws(this.logger),this.codecStatsAggregator=new Us(this.logger,r),this.pings=new Js(this.logger),this.signalingCommands=new Ys(this.logger)}prepareForUnload(){N.statQueueEnabled&&(this._unloading=!0,this.logger.enterUnloadMode(),this.pings.logMetrics(),this.signalingCommands.logMetrics())}restoreAfterUnload(){N.statQueueEnabled&&(this._unloading=!1,this.logger.exitUnloadMode())}logHangup(e){this.lifecycle.markFinished(e)}flushCallMetrics(){this.codecStatsAggregator.destroy(),this.pings.logMetrics(),this.pings.destroy(),this.signalingCommands.logMetrics(),this.signalingCommands.destroy()}destroy(){this.lifecycle.markTerminated(),this.lifecycle.destroy(),this.statAggregator.destroy(),this.codecStatsAggregator.destroy(),this.pings.destroy(),this.signalingCommands.destroy(),this.logger.destroy(),N.statQueueEnabled&&!this._unloading&&Ts.notifyCallFinished()}},Zs=class{constructor(e){h(this,`_statAggregator`,void 0),h(this,`_isCallMarked`,!1),h(this,`_isFinished`,!1),h(this,`_callType`,null),this._statAggregator=e}markAcceptCall(e){this.mark(e===J.DIRECT?`direct_incoming`:`server_incoming`)}markAcceptedCall(e){e===J.DIRECT&&this.mark(`direct_outgoing`)}markOnJoin(e){this.mark(e===J.DIRECT?`direct_join`:`server_join_server`,e===J.DIRECT)}markTopologyChanged(e){this._isFinished||e!==J.SERVER||(this._callType=`server_change_topology`)}mark(e,t=!1){(!this._isCallMarked||t)&&(this._isCallMarked=!0,this._callType=e,G.setMark(U.FIRST_MEDIA_RECEIVED))}measure(){this._isFinished||(this._isFinished=!0,this._callType&&this._statAggregator.logEventualStat({name:U.FIRST_MEDIA_RECEIVED,call_type:this._callType}))}},Qs=1e3,$s=1e4;function ec(e,t,n,r){return new k(e,{callError:{scope:`external`,source:`api`,code:t,description:n},message:r})}var tc=15,$=class e extends b{constructor(e,t){super(),h(this,`_api`,void 0),h(this,`_signaling`,void 0),h(this,`_signalingActor`,void 0),h(this,`_displayLayoutRequester`,void 0),h(this,`_mediaSource`,null),h(this,`_conversation`,null),h(this,`_myLastRequestedLayouts`,{}),h(this,`_state`,`IDLE`),h(this,`_previousState`,null),h(this,`_waitingHallHoldPending`,!1),h(this,`_participantState`,X.CALLED),h(this,`_participants`,{}),h(this,`_directTransportIsMaster`,void 0),h(this,`_transport`,null),h(this,`_debugInfo`,null),h(this,`_debug`,z.createSessionLogger()),h(this,`_volumesDetector`,null),h(this,`_speakerDetector`,null),h(this,`_localVolumeDetector`,null),h(this,`_specListener`,null),h(this,`_activeSpeakerId`,null),h(this,`_lastSignalledActiveSpeakerId`,null),h(this,`_isRealTimeAsrRequested`,!1),h(this,`_serverSettings`,Nr()),h(this,`_serverTimeOffset`,0),h(this,`_delayedHangup`,!1),h(this,`_onFastHangup`,void 0),h(this,`_hangupEmitted`,!1),h(this,`_hangupPromise`,null),h(this,`_abortController`,null),h(this,`_registeredPeerReceived`,!1),h(this,`_calleeUnavailableTimer`,null),h(this,`_reservedId`,null),h(this,`_onUnload`,void 0),h(this,`_onRestore`,void 0),h(this,`_audioOutput`,void 0),h(this,`_stats`,void 0),h(this,`_lastStalled`,{}),h(this,`_audioMixStalled`,!1),h(this,`_audioFix`,null),h(this,`_streamByStreamId`,new Map),h(this,`_streamIdByStreamDescription`,new Map),h(this,`_streamWaitTimerByStreamDescription`,new Map),h(this,`_sequenceNumberByStreamDescription`,new Map),h(this,`_cooldownTimestampByStreamDescription`,new Map),h(this,`_cooldownQueueCleanupTimer`,null),h(this,`_statFirstMediaReceived`,void 0),h(this,`_toggleLocalVideo`,yo(e=>{if(this._mediaSource)return this._stats.logger.log(C.MEDIA_STATUS,e?`video_1`:`video_0`),this._mediaSource.toggleVideo(e)})),h(this,`_toggleLocalAudio`,yo(e=>{if(this._mediaSource)return this._stats.logger.log(C.MEDIA_STATUS,e?`audio_1`:`audio_0`),this._mediaSource.toggleAudio(e)})),h(this,`_changeMediaSettings`,M.debounce(async e=>{if(this._signaling.ready)try{await this._signaling.changeMediaSettings(e)}catch(e){if(this._debug.warn(`changeMediaSettings failed with error`,e),e.message===`chatRoom.maxShareCountExceeded`)return this.toggleScreenCapturing({captureScreen:!1,fastScreenSharing:!1,captureAudio:!1})}},100)),this._stats=new Xs(e,t,()=>this._conversation?.id||null,()=>this._transport?.getTopology()??this._conversation?.topology),this._api=e,this._signaling=new Wa(this._debug,this._stats.logger,this._stats.statAggregator,this._stats.pings,this._stats.signalingCommands),this._signalingActor=new Mo(this._onSignalingNotification.bind(this),this._debug),this._displayLayoutRequester=new Oo({api:this._api,debug:this._debug,getParticipants:()=>this._participants,isMe:e=>this._isMe(e),updateDisplayLayout:e=>this.updateDisplayLayout(e),onNonFatalError:e=>this._onNonFatalError(e)}),this._onUnload=()=>{this._stopFirstMediaSentProbe(),this._conversation&&this._api&&this._sendHangupApi(this._conversation.id,this._state===`IDLE`?O.CANCELED:O.HUNGUP),this._stats.prepareForUnload(),this._stats.destroy()},this._onRestore=()=>{this._stats.restoreAfterUnload()},window.addEventListener(`pagehide`,this._onUnload),window.addEventListener(`pageshow`,this._onRestore),this._statFirstMediaReceived=new Zs(this._stats.statAggregator),this._audioOutput=new xo(this._statFirstMediaReceived,N.transparentAudio,this._debug,this._stats.logger),N.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Qs))}static current(){return B.getActive()??(N.hold?null:B.getFirst())}static hangupAfterInit(e){let t=nc;if(t){if(typeof e==`function`&&(t._onFastHangup=e),t._delayedHangup===!1&&!t._conversation){t._delayedHangup=!0,t._abortController?.abort(new k(O.CANCELED));return}t._conversation&&t.hangup({onFastHangup:e,reason:O.CANCELED})}}static id(){return B.getActiveId()}get id(){return this._conversation?.id??``}get externalId(){return this._conversation?.externalId}get mediaSettings(){return this._mediaSource?.mediaSettings}get isCallHeld(){return this._state===`HELD`}get isIncomingRinging(){return this._conversation?.direction===Ga.INCOMING&&this._state===`IDLE`}static debugSessionId(){return e.current()?.debugSessionId??null}static debugMessage(t,...n){let r=e.current();return r?(r._debug.send(t,...n),!0):!1}static debugMessageWithContext(e,t,...n){let r=B.get(t);return r?(r._debug.send(e,...n),!0):!1}static getSyncedTime(){return Date.now()+(e.current()?._serverTimeOffset??0)}get debugSessionId(){return this._debug.sessionId}getCachedParticipantIdByExternalId(e){return this._api.getCachedParticipantIdByExternalId(e)}_onNonFatalError(e){R.onNonFatalError(Error(e),this.id)}getIncomingCallerExternalId(){return this._conversation?.direction===Ga.INCOMING?Object.values(this._participants).find(e=>!this._isMe(e.id))?.externalId??null:null}_buildInternalParams(){let e={deviceId:this._api.deviceId(),sdkVersion:N.sdkVersion,clientAppKey:N.apiKey,platform:N.platform,protocolVersion:N.protocolVersion,domainId:N.domain,capabilities:Ea.getFlags()};return JSON.stringify(e)}async onStart({opponentIds:e,opponentType:t,mediaOptions:n,payload:r=``,joiningAllowed:i=!1,requireAuthToJoin:a=!1,onlyAdminCanShareMovie:o,externalIds:s,onFastStart:c,conversationId:l}){let u=l??M.uuid(),d=(e?.length??0)+(s?.length??0),f=t===Ka.USER&&d===1?N.calleeUnavailableWaitingTime:void 0;this._stats.lifecycle.markInitializationStarted({source:`outgoing`,conversationId:u}),this._debug.setConversationId(u),nc=this,this._abortController=new AbortController,this._api.setAbortSignal(this._abortController?.signal),this._signaling.setAbortSignal(this._abortController?.signal);try{this._mediaSource=this._createMediaSource(),await this._mediaSource.request(n);let l=this._mediaSource.mediaSettings;t===Ka.CHAT||e&&e.length>1?this._logWithMediaSettings(C.OUTGOING_MULTIPARTY_CALL,l):this._logWithMediaSettings(C.OUTGOING_CALL,l);let d=await this._startConversation({opponentIds:e,opponentType:t,direction:Ga.OUTGOING,mediaOptions:n,payload:r,joiningAllowed:i,requireAuthToJoin:a,onlyAdminCanShareMovie:o,externalIds:s,onFastStart:c,conversationId:u});if(!this._conversation)throw new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`conversation`,description:`not-initialized-after-start`}});if(this._participantState=X.ACCEPTED,this._changeMediaSettings(l),await this._processConnection(d),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),this._delayedHangup)throw new k(O.CANCELED);if(this._debug.debug(`Outgoing call`,{opponentIds:e,opponentType:t,mediaOptions:n}),this._processConnectionSharedMovieInfo(d),this._processConversationUrlSharingInfo(d),R.onLocalStream(this._mediaSource.getStream(),this._mediaSource.mediaSettings,this.id),R.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),this._getMainRoomParticipants(),void 0,this.id),this._onConversationParticipantListChunk(d),this._processPinnedParticipants(d),R.onLocalStatus(P.WAITING,this.id),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),this._conversation?.concurrent){let e=B.get(this._conversation.id);e&&e!==this&&e._close(new k(O.HUNGUP,{remote:!0}))}return B.add(this),await B.setActive(this.id),nc=null,this._conversation.concurrent&&await this._acceptConcurrent(),f&&!this._registeredPeerReceived&&this._state!==`CLOSE`&&(this._calleeUnavailableTimer=window.setTimeout(()=>{this._calleeUnavailableTimer=null,this._close(new k(O.CALLEE_UNAVAILABLE),{signalingReason:O.CANCELED})},f)),this._conversation}catch(e){throw nc=null,this._cleanupRegistry(),this._close(e,{errorText:`Unable to start conversation`}),e}}async onJoin(e){this._stats.lifecycle.markInitializationStarted({source:e.anonymous?`anonym_join`:`join`,conversationId:e.conversationId}),nc=this,this._state=`PROCESSING`,this._debug.setConversationId(e.conversationId??null),this._abortController=new AbortController,this._api.setAbortSignal(this._abortController?.signal),this._signaling.setAbortSignal(this._abortController?.signal);try{let t=!!e.observedIds?.length;if(t&&N.videoTracksCount>0)throw this._debug.error(`Observer mode: please set videoTracksCount=0`),new k(O.UNSUPPORTED,{callError:{scope:`internal`,code:`observer-mode`,description:`video-tracks-count-must-be-zero`}});this._mediaSource=this._createMediaSource(),await this._mediaSource.request(e.mediaOptions,!t);let n=this._mediaSource.mediaSettings;this._logWithMediaSettings(C.JOIN_CONVERSATION,n);let r=await this._joinConversation(e);if(!this._conversation)throw new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`conversation`,description:`not-initialized-after-join`}});return this._conversation.observer=t,R.onLocalStream(this._mediaSource.getStream(),n,this.id),this._conversation.waitForAdmin||this._conversation.waitingHall?(this._debug.log(this._conversation.waitForAdmin?`Wait for admin`:`In waiting hall`),B.add(this),nc=null,this._signaling.readyToSend(),R.onLocalStatus(this._conversation.waitForAdmin?P.WAIT_FOR_ADMIN:P.WAITING_HALL,this.id),this._conversation):this._onJoinPart2(r)}catch(e){throw nc=null,this._cleanupRegistry(),this._close(e,{errorText:`Unable to join conversation`}),e}}async _onJoinPart2(e,t=!0,n=!1){this._debug.debug(`Join conversation part 2`);try{if(this._participantState=X.ACCEPTED,!this._conversation||!this._mediaSource)throw new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`join`,description:`runtime-not-initialized`}});if(this._statFirstMediaReceived.markOnJoin(this._conversation.topology),!n&&!this._conversation.observer&&!this._isAudienceModeListener()&&this._changeMediaSettings(this._mediaSource.mediaSettings),await this._processConnection(e),t&&(this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener()),this._signaling.readyToSend(),this._state===`CLOSE`)return this._conversation;if(this._delayedHangup)throw new k(O.CANCELED);this._processConnectionSharedMovieInfo(e),this._processConversationUrlSharingInfo(e),this._processConnectionAsrInfo(e);let r=this._extractExternalRoomsData(e.rooms?.rooms,e.rooms?.roomId);R.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),this._getMainRoomParticipants(),r,this.id),this._onConversationParticipantListChunk(e),this._processPinnedParticipants(e),R.onLocalStatus(P.WAITING,this.id),this._toggleJoinAvailability(),this._changeNeedRate(),t&&(this._state=`ACTIVE`),this._changeFeatureSet(),t&&(B.add(this),n?await this._holdLocally():await B.setActive(this.id),nc=null);let i=this._extractLocalParticipantFromConnection(e);if(i){let e=M.mapParticipantState(i);Object.keys(e).length>0&&R.onLocalParticipantState(e,!1,this.id)}return t&&this._openTransport(Object.values(this._participants),!1),this._conversation}catch(e){throw nc=null,this._cleanupRegistry(),this._close(e,{errorText:`Unable to join conversation`}),e}}_extractExternalRooms(e){let t=[],n=[];return e.forEach(e=>{let{room:r,missingParticipantIds:i}=this._convertRoomToExternal(e);r&&n.push(r),t.push(...i)}),this._reportMissingExternalIds(t,`EXTRACT_EXTERNAL_ROOMS`),n.filter(e=>!!e)}_extractExternalRoomsData(e,t){if(!e||!e.length)return;let n={rooms:this._extractExternalRooms(e)};return t&&(n.roomId=t),n}async onPush(e,t=j.USER,n,r,i,a){if(B.has(e))throw new k(O.HAS_ACTIVE_CALL);B.reserve(e),this._reservedId=e,a&&this._api.setUserId(a),this._stats.lifecycle.markInitializationStarted({source:`incoming`,conversationId:e}),this._debug.setConversationId(e),nc=this,this._abortController=new AbortController,this._api.setAbortSignal(this._abortController?.signal),this._signaling.setAbortSignal(this._abortController?.signal);try{let a=await this._prepareConversation(e,t,n,r,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`conversation`,description:`incoming-not-initialized`}});if(!a.conversation.participants.find(e=>e.state===X.CALLED&&e.id===this._conversation?.userId))throw this._debug.log(`Push rejected (there is an active call)`),this._stats.logger.log(C.PUSH,`rejected`),new k(O.REJECTED);if(await this._processConnection(a),this._extractConnectionUrlSharingInfo(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._processPinnedParticipants(a),this._signaling.readyToSend(),this._stats.lifecycle.markCallStarted(),this._stats.logger.log(C.PUSH,`accepted`),B.add(this),nc=null,this._delayedHangup)throw new k(O.CANCELED)}catch(e){throw nc=null,this._cleanupRegistry(),this._close(e,{errorText:`Unable to handle inbound call push`,signalingReason:e instanceof k&&e.hangup===O.BUSY?O.BUSY:void 0}),e}}_isInWaitingHall(e){return!e.conversation||!e.conversation.options.includes(Ya.WAITING_HALL)?!1:this._isRestricted(e)}_isWaitForAdmin(e){if(!e.conversation)return!1;let t=e.conversation.options.includes(Ya.WAIT_FOR_ADMIN),n=e.conversation.options.includes(Ya.ADMIN_IS_HERE);return!t||t&&n?!1:this._isRestricted(e)}_isRestricted(e){let t=(e.conversation.participants||[]).find(t=>M.comparePeerId(t.peerId,e.peerId));return t&&t.restricted||!1}_isAudienceMode(e){return e.conversation?.options?.includes(Ya.AUDIENCE_MODE)||!1}_isAudienceModeListener(){return this._conversation?.audienceMode&&this._conversation?.restricted}async _acceptConcurrent(){if(!this._mediaSource||!this._conversation||!this._transport)throw new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`accept`,description:`runtime-not-initialized`}});this._state=`PROCESSING`;let e=this._mediaSource.mediaSettings;this._logWithMediaSettings(C.ACCEPT_CONCURRENT,e),this._debug.debug(`Concurrent call`,{conversationId:this._conversation.id});try{this._statFirstMediaReceived.markAcceptCall(this._transport.getTopology()),await this._signaling.acceptCall(this._mediaSource.mediaSettings),this._stats.lifecycle.markIncomingAccepted(!0),R.onCallAccepted(this.id),this._state=`ACTIVE`,this._participantState=X.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(e){this._close(e,{errorText:`Unable to accept concurrent call`})}}_getMainRoomParticipants(){let e=this._participants;return M.mapSharedParticipants(Object.values(e).filter(e=>!e.isInRoom))}_decodeExternalConversationParams(e){let[t,n]=e.split(`:`),r=parseInt(t,10);if(isNaN(r))throw Error(`Invalid original length in prefix`);let i=atob(n),a=new Uint8Array(i.length);for(let e=0;e<i.length;e++)a[e]=i.charCodeAt(e);try{let e=vo(a,r).reduce((e,t)=>(e+=String.fromCharCode(t),e),``),{srcp:t,stne:n,tkn:i,trne:o,trnp:s,trnu:c,wse:l,wte:u}=JSON.parse(e);return{token:i,endpoint:l,wt_endpoint:u,turn_server:{urls:o.split(`,`),username:c,credential:s},stun_server:{urls:n.split(`,`)},client_type:t}}catch(e){throw this._close(e,{errorText:`Can't decompress conversation params`}),e}}async accept(e){if(this._state!==`IDLE`)throw this._stats.logger.log(C.ERROR,`acceptIncoming`),this._debug.error(`Unable to accept a call - invalid state`),Error(`Unable to accept a call - invalid state`);if(!this._mediaSource||!this._conversation||!this._transport)throw new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`accept`,description:`runtime-not-initialized`}});this._state=`PROCESSING`,this._debug.setConversationId(this._conversation.id),this._debug.debug(`Accept incoming call`,e);try{await this._mediaSource.request(e);let t=this._mediaSource.mediaSettings;this._logWithMediaSettings(C.ACCEPT_INCOMING,t),this._changeMediaSettings(t),this._statFirstMediaReceived.markAcceptCall(this._transport.getTopology()),await this._signaling.acceptCall(t),this._stats.lifecycle.markIncomingAccepted(!1),this._participantState=X.ACCEPTED;let n=this._getMuteStatesForCurrentRoom(),r=Object.keys(n);r.length&&this._onMuteParticipant({muteStates:n,mediaOptions:r,muteAll:!0,stateUpdated:!0}),this._registerParticipantLocalMuteState({muteStates:this._conversation.muteStatesPersonal});let i=await this._signaling.getRooms(this._isCallAdmin());if(i.rooms?.rooms?.length){let e=this._participants;i.rooms.rooms.forEach(t=>{t.participantIds?.forEach(t=>{e[t]&&(e[t].isInRoom=!0)})})}this._conversation.roomId=i.rooms?.roomId||null;let a=this._extractExternalRoomsData(i.rooms?.rooms,i.rooms?.roomId);if(R.onCallAccepted(this.id),R.onLocalStream(this._mediaSource.getStream(),t,this.id),R.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),this._getMainRoomParticipants(),a,this.id),await this._emitHeldParticipantsStatus(),N.useParticipantListChunk){let e=await this._getInitialParticiapntListChunk(),t=this._participants;e?.participants?.forEach(e=>{let n=t[M.composeId(e)];n&&(n.movieShareInfos=e.movieShareInfos)}),this._onConversationParticipantListChunk({participants:e})}return R.onLocalStatus(P.WAITING,this.id),this._toggleJoinAvailability(),this._changeNeedRate(),this._state=`ACTIVE`,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0),this._processConversationUrlSharingInfo(),this._processConnectionAsrInfo(),B.setActive(this.id).catch(e=>{this._debug.error(e),this._close(e,{errorText:`Unable to activated accepted call`})}),this._conversation}catch(e){throw this._close(e,{errorText:`Unable to accept call`}),e}}async decline(e){if(this._state!==`IDLE`)throw this._stats.logger.log(C.ERROR,`declineIncoming`),this._debug.error(`Unable to decline a call - invalid state`),Error(`Unable to decline a call - invalid state`);let t=e?.reason;this._state=`PROCESSING`,this._debug.debug(`Decline incoming call`),this._logWithMediaSettings(C.DECLINE_INCOMING,this.mediaSettings),this._participantState=X.HUNGUP;let n=t??O.REJECTED,r=new k(n);this._finishLifecycle(r),this._onFastHangup=e?.onFastHangup??this._onFastHangup;let i=this._conversation?.id;i&&typeof this._onFastHangup==`function`&&this._sendHangup(i,n,this._onFastHangup),this._close(r,{signalingReason:n})}hangup(e){if(this._hangupPromise)return this._hangupPromise;let t=e?.reason;this._clearCalleeUnavailableWatchdog(),this._debug.debug(`Hangup`);let n=t??(this._state===`ACTIVE`||this._state===`HELD`?O.HUNGUP:O.CANCELED),r=new k(n),i=this._conversation?.id??null;this._onFastHangup=e?.onFastHangup??this._onFastHangup,this._stats.logger.log(C.HANGUP,n),this._finishLifecycle(r);let a=!!i&&typeof this._onFastHangup==`function`;return i&&a&&this._sendHangup(i,n,this._onFastHangup),this._hangupPromise=this._signaling.hangup(n).then(()=>void 0).catch(e=>{if(!(e instanceof Dn))throw e}).finally(()=>(i!=null&&!a&&this._sendHangupApi(i,n),this._close(r))),this._emitHangupOnce(r,i),this._cleanupTransport(),this._cleanupMediaSource(),this._hangupPromise}async addParticipant(e,t){if(!this._signaling.ready){this._close(new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`add-participant`,description:`signaling-not-ready`}}),{errorText:`Unable to add participant`});return}let n=await this._signaling.addParticipant(e.map(Z.toSignaling),t),r=null;n.type===`error`&&(r=n.error===`call-unfeasible`?n.status:O.UNKNOWN_ERROR);let i=n.participants;if(!i&&n.rejectedParticipants?.length)throw Error(n.rejectedParticipants[0].reason);for(let e of i)await this._onAddParticipant(M.composeId(e),e,r)}async addParticipantLegacy(e,t){if(!this._signaling.ready){this._close(new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`add-participant`,description:`signaling-not-ready`}}),{errorText:`Unable to add participant`});return}let n=await this._signaling.addParticipantLegacy(e,t),r=null;n.type===`error`&&(r=n.error===`call-unfeasible`?n.status:O.UNKNOWN_ERROR);let i=n.participants;for(let e of i)await this._onAddParticipant(M.composeId(e),e,r)}async removeParticipant(e,t=!1){this._signaling.ready&&(await this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){if(!this._transport)return;let n=new Set(this._transport.opened()),r=[];for(let i of e)(i.state===X.CALLED||i.state===X.ACCEPTED)&&(this._transport.isAllocated(i.id)||this._allocateParticipantTransport(i.id,t)),i.state===X.ACCEPTED&&!n.has(i.id)&&r.push(i.id);r.length?this._transport.open(r,null,!!this._conversation?.observer):this._transport.getTopology()===J.SERVER&&this._forceOpenTransportForAloneInCall()}_allocateParticipantTransport(e,t){this._transport&&(this._transport.getTopology()===J.DIRECT&&(t=this._directTransportIsMaster??(this._directTransportIsMaster=t)),this._transport.allocate(e,t))}_closeParticipantTransport(e){let t=this._transport?.getTopology()===J.DIRECT&&this._transport.opened().includes(e);this._transport?.close(e),t&&(this._directTransportIsMaster=void 0)}_cleanupRegistry(){B.remove(this._reservedId),B.remove(this.id),this._reservedId=null}_emitHangupOnce(e,t){this._hangupEmitted||(this._hangupEmitted=!0,R.onHangup(e,t))}_sendHangupApi(e,t){let n=this._signaling.getPeerId(),r={};n!=null&&(r.peerId=String(n)),this._api.hangupConversation(e,t,r)}_close(e,t={}){this._clearCalleeUnavailableWatchdog(),t.errorText&&this._debug.error(t.errorText,e),this._debug.debug(`Close conversation`,e),this._finishLifecycle(e),this._stats.flushCallMetrics();let n=t.signalingReason??(e.error?O.FAILED:void 0),r=n&&this._signaling.ready?this._signaling.hangup(n):void 0;this._signaling.readyToSend(!1),e.error||this._stats.logger.log(C.ERROR,e.hangup);let i=this._conversation&&this._conversation.id;if([O.CANCELED,O.NOT_FRIENDS,O.CALLEE_IS_OFFLINE,O.CALLEE_UNAVAILABLE,O.CALLER_IS_BLOCKED,O.CALLER_IS_REJECTED,O.HAS_ACTIVE_CALL].indexOf(e.hangup)!==-1||e.hangup===O.REJECTED&&!e.remote){this._emitHangupOnce(e,i),this._destroy(r);return}if(e.hangup===O.HUNGUP&&(!e.remote||this._isCalledState())){this._emitHangupOnce(e,i),this._destroy(r);return}if(e.hangup===O.MISSED&&!e.remote){this._emitHangupOnce(e,i),this._destroy(r);return}if(this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null),(e.hangup===O.SOCKET_CLOSED||e.hangup===O.NOT_FOUND)&&B.getActive()&&!this._conversation){this._disposeSignaling(r),this._cleanupMediaSource();return}if(e.hangup===O.BUSY&&!e.remote){this._disposeSignaling(r),this._cleanupMediaSource();return}this._state=`CLOSE`,this._participantState=X.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._disposeSignaling(r),this._api.cleanup(),this._api.setAbortSignal(void 0),this._stats.destroy(),this._cleanupRegistry(),this._conversation=null,this._myLastRequestedLayouts={},this._displayLayoutRequester.clear(),this._delayedHangup=!1,this._abortController=null,this._emitHangupOnce(e||new k(O.UNKNOWN_ERROR),i)}_sendHangup(e,t,n){typeof n==`function`?n({conversationId:e,reason:t,internalParams:this._buildInternalParams()},this._abortController?.signal).then(e=>{e?.success||this._debug.error(`Fast hangup was not successful`,e)}).catch(e=>{this._debug.error(`Fast hangup error`,e)}):this._sendHangupApi(e,t)}destroy(){this._destroy()}_destroy(e){this._clearCalleeUnavailableWatchdog();let t=this._conversation&&this._conversation.id;if(this._debug.debug(`Destroy conversation`,{conversationId:t}),this._stopFirstMediaSentProbe(),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null),this._state=`CLOSE`,this._participantState=X.HUNGUP,this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._disposeSignaling(e),this._delayedHangup&&t)try{this._sendHangup(t,O.CANCELED,this._onFastHangup)}catch{}this._api.cleanup(),this._api.setAbortSignal(void 0),this._cleanupListeners(),this._stats.destroy(),this._cleanupRegistry(),this._conversation=null,this._myLastRequestedLayouts={},this._displayLayoutRequester.clear(),this._delayedHangup=!1,this._abortController=null}async _getConversationParams(e){let t=await this._api.getConversationParams(e);this._debug.debug(`Api.getConversationParams`,t);let{turn_server:n,stun_server:r}=t;return N.iceServers=_o(r,n),N.wssBase=t.endpoint,t.wt_endpoint&&(N.wtsBase=t.wt_endpoint),N.wssToken=t.token,t.client_type&&(N.clientType=t.client_type),t.external_user_type&&(N.externalUserType=t.external_user_type),t}_setConversationParams({turn_server:e,stun_server:t,endpoint:n,wt_endpoint:r,token:i,client_type:a}){N.iceServers=_o(t,e),N.wssBase=n,N.wssToken=i,r&&(N.wtsBase=r),a&&(N.clientType=a)}_buildSignalingEndpoint({baseEndpoint:e,userId:t,type:n,deviceIdx:r,conversationId:i,token:a,conversationParams:o}){let s=new URL(e),c=s.searchParams;return c.set(`userId`,String(t)),c.set(`entityType`,n),c.set(`deviceIdx`,String(r)),c.set(`conversationId`,i),c.set(`token`,a),o?.isp_as_no&&c.set(`ispAsNo`,String(o.isp_as_no)),o?.isp_as_org&&c.set(`ispAsOrg`,o.isp_as_org),o?.loc_cc&&c.set(`locCc`,o.loc_cc),o?.loc_reg&&c.set(`locReg`,o.loc_reg),s.toString()}_clearCalleeUnavailableWatchdog(){this._calleeUnavailableTimer!==null&&(window.clearTimeout(this._calleeUnavailableTimer),this._calleeUnavailableTimer=null)}async _startConversation({opponentIds:e,opponentType:t,direction:n,mediaOptions:r,payload:i=``,joiningAllowed:a=!1,requireAuthToJoin:o=!1,onlyAdminCanShareMovie:s,externalIds:c,onFastStart:l,conversationId:u}){let d=u??M.uuid();if(B.has(d))throw new k(O.HAS_ACTIVE_CALL);B.reserve(d),this._reservedId=d,this._debug.debug(`Conversation: start`,{conversationId:d,opponentIds:e,opponentType:t,direction:n});let f=r.includes(S.VIDEO),p,m;if(l){let e;try{if(e=await l({internalParams:this._buildInternalParams(),conversationId:d,externalIds:c,payload:i,opponentType:t,mediaOptions:r,isVideo:f,joiningAllowed:a,requireAuthToJoin:o},this._abortController?.signal),!e)throw ec(O.FAST_START_ERROR,`invalid-response`,`fast-start-response-empty`);if(!e.internalCallerParams){let t=e.rejectedParticipants[0]?.status;throw ec(O.FAST_START_ERROR,t?`fast-start`:`invalid-response`,t??`fast-start-internal-caller-params-empty`,JSON.stringify(e))}}catch(e){throw this._delayedHangup&&this._abortController?.signal.aborted?new k(O.CANCELED):e instanceof k?e:e instanceof Error?new k(O.FAST_START_ERROR,{message:e.message}):new k(O.FAST_START_ERROR,{message:String(e)})}try{let t=JSON.parse(e.internalCallerParams);p={endpoint:t.endpoint,wt_endpoint:t.wtEndpoint,id:d,is_concurrent:t.isConcurrent,client_type:t.clientType,rejected_participants:e.rejectedParticipants?.map(e=>({...e,status:e.status})),stun_server:t.stun,turn_server:t.turn,token:new URL(t.endpoint).searchParams.get(`token`)??``},this._debug.debug(`FastStart`,p),m=`fastStart`}catch{throw ec(O.FAST_START_ERROR,`invalid-response`,`fast-start-internal-caller-params-invalid`)}}else p=await this._api.startConversation(d,e,t,f,i,a,o,{onlyAdminCanShareMovie:s},c),this._debug.debug(`Api.startConversation`,p),m=`startConversation`;So(p,m),this._setConversationParams(p),this._stats.lifecycle.bindConversationId(p.id);let ee=await this._connectSignaling(xr.START,p);return this._setConversation(p,ee,n),this._stats.lifecycle.markCallStarted(),ee}async _joinConversation(e){G.setMark(U.SIGNALING_CONNECTED);let{conversationId:t,mediaOptions:n,chatId:r,joinLink:i,observedIds:a,payload:o,onFastJoin:s}=e;if(this._debug.debug(`Conversation: join`,{conversationId:t,joinLink:i,observedIds:a}),t&&B.has(t))throw new k(O.HAS_ACTIVE_CALL);let c=n.includes(S.VIDEO),l,u;if(s){if(!i)throw new k(O.FAST_JOIN_ERROR,{callError:{scope:`internal`,code:`fast-join`,description:`join-link-required`}});let e;try{if(e=await s({joinLink:i,isVideo:c,internalParams:this._buildInternalParams()},this._abortController?.signal),!e)throw ec(O.FAST_JOIN_ERROR,`invalid-response`,`fast-join-response-empty`);if(!e.internalCallerParams)throw ec(O.FAST_JOIN_ERROR,`invalid-response`,`fast-join-internal-caller-params-empty`,JSON.stringify(e));if(!e.conversationId)throw ec(O.FAST_JOIN_ERROR,`invalid-response`,`fast-join-conversation-id-empty`,JSON.stringify(e))}catch(e){throw this._delayedHangup&&this._abortController?.signal.aborted?new k(O.CANCELED):e instanceof k?e:e instanceof Error?new k(O.FAST_JOIN_ERROR,{message:e.message}):new k(O.FAST_JOIN_ERROR,{message:String(e)})}try{let t=JSON.parse(e.internalCallerParams);if(B.has(e.conversationId))throw new k(O.HAS_ACTIVE_CALL);l={endpoint:t.endpoint,wt_endpoint:t.wtEndpoint,id:e.conversationId,is_concurrent:t.isConcurrent,client_type:t.clientType,stun_server:t.stun,turn_server:t.turn,token:new URL(t.endpoint).searchParams.get(`token`)??``},this._debug.debug(`FastJoin`,l),u=`fastJoin`}catch(e){throw e instanceof k?e:ec(O.FAST_JOIN_ERROR,`invalid-response`,`fast-join-internal-caller-params-invalid`)}}else if(t)l=await this._api.joinConversation(t,c,r),u=`joinConversation`;else if(i)l=await this._api.joinConversationByLink(i,c,a,o),u=`joinConversationByLink`;else throw new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`join`,description:`target-missing`}});if(this._debug.debug(`Api.joinConversation`,l),l.id&&this._stats.lifecycle.bindConversationId(l.id),So(l,u),l.id){if(B.has(l.id))throw new k(O.HAS_ACTIVE_CALL);B.reserve(l.id),this._reservedId=l.id}this._setConversationParams(l);let d=await this._connectSignaling(xr.JOIN,l);return this._setConversation(l,d,Ga.JOINING),this._stats.lifecycle.markCallStarted(),d}async _prepareConversation(e,t=j.USER,n,r,i){G.setMark(U.SIGNALING_CONNECTED),this._debug.debug(`Conversation: push`,{conversationId:e,type:t,peerId:n});let a=this._api.getUserId();if(!a)throw new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`incoming`,description:`user-id-missing`}});let o=0,s=``,c=``,l={id:e,peerId:n,endpoint:s,wt_endpoint:c,is_concurrent:!1,p2p_forbidden:!1,device_idx:0,token:``};if(r){let n=this._decodeExternalConversationParams(r);this._setConversationParams(n),s=i??this._buildSignalingEndpoint({baseEndpoint:N.wssBase,userId:a,type:t,deviceIdx:o,conversationId:e,token:N.wssToken}),l.token=n.token,l.endpoint=s,N.wtsBase&&(c=this._buildSignalingEndpoint({baseEndpoint:N.wtsBase,userId:a,type:t,deviceIdx:o,conversationId:e,token:N.wssToken}),l.wt_endpoint=c)}else{let n=await this._getConversationParams(e);o=n.device_idx||0,s=i??this._buildSignalingEndpoint({baseEndpoint:N.wssBase,userId:a,type:t,deviceIdx:o,conversationId:e,token:N.wssToken,conversationParams:n}),l.token=n.token,l.endpoint=s,l.device_idx=o,N.wtsBase&&(c=this._buildSignalingEndpoint({baseEndpoint:N.wtsBase,userId:a,type:t,deviceIdx:o,conversationId:e,token:N.wssToken,conversationParams:n}),l.wt_endpoint=c)}let u=await this._connectSignaling(xr.ACCEPT,l);return B.callsLength>=N.maxParallelCalls||!N.hold&&B.callsLength>0?(this._debug.log(`Push rejected (busy)`),this._stats.logger.log(C.PUSH,`busy`),Promise.reject(new k(O.BUSY))):(this._setConversation(l,u,Ga.INCOMING,t),u)}_createParticipant(e,t,n=!0){let r=Object.assign({id:null,externalId:null,mediaSettings:D(),participantState:{},state:X.CALLED,connectionStatus:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[],isInRoom:!1,markers:null},e),i=!!r.externalId;if(!i){let e=this._getParticipantId(t??r.id);e&&(r.externalId=e)}return n&&i&&this._api.cacheExternalId(t??r.id,r.externalId),t&&this._api.mapDecorativeId(t,r.id),r.observedIds?.length&&r.externalId&&(r.externalId.observer=!0),e.markers&&(r.markers=this._denormalizeMarkers(r.id,e.markers)),r.connectionStatus=ao.create(r.connectionStatus),r}_getParticipantId(e){let t=this._api.userId(e);if(t)return t;let{compositeUserId:n,deviceIdx:r}=M.decomposeParticipantId(e),{id:i,type:a}=M.decomposeId(n);return a===j.GROUP?Z.fromId(String(i),void 0,r):null}_cacheParticipantExternalIds(e){e.forEach(e=>{let t=M.composeId(e),n=Z.fromSignalingParticipant(e,!1);if(n){this._api.cacheExternalId(t,n);let r=M.composeDecorativeId(e),i=Z.fromSignalingParticipant(e);r&&i&&(this._api.cacheExternalId(r,i),this._api.mapDecorativeId(r,t))}})}_setConversation(e,t,n,r=j.USER){let{participants:i}=t.conversation;t.conversationParams?.serverTime&&(this._serverTimeOffset=t.conversationParams.serverTime-Date.now()),this._cacheParticipantExternalIds(i);let a=this._api.getUserId(),o=this._extractLocalParticipantFromConnection(t),s=e.device_idx||0;if(!a){if(!o)throw new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`conversation`,description:`anonymous-local-participant-missing`}});a=Number(o.id),o.idType&&(r=o.idType),o.deviceIdx&&(s=o.deviceIdx),this._api.setUserId(a)}let c=M.composeParticipantId(a,r,s);this._conversation={userId:a,compositeUserId:c,externalId:this._getExternalIdByParticipantId(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||J.DIRECT,direction:n,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:o?.roles??[],recordsInfoByRoom:new Map,asrInfoByRoom:new Map,muteStates:new Map,muteStatesPersonal:{},joinLink:e.join_link??t.conversation.joinLink,pinnedParticipantIdByRoom:new Map,mediaModifiers:t.mediaModifiers,options:[],networkRating:1,waitingHall:this._isInWaitingHall(t),waitForAdmin:this._isWaitForAdmin(t),observer:!1,asrInfo:t.conversation.asrInfo||null,roomId:t.rooms?.roomId||null,audienceMode:this._isAudienceMode(t),restricted:this._isRestricted(t),urlSharingInfoByRoom:new Map},this._debug.setConversationId(t.conversation.id||e.id),e.p2p_forbidden&&(N.forceRelayPolicy=e.p2p_forbidden),this._stats.logger.log(C.RELAY_POLICY,N.forceRelayPolicy?`1`:`0`);let l=B.get(this._conversation.id);if(l&&l!==this)this._conversation.concurrent=!0;else if(!N.hold&&B.callsLength>0)throw new k(O.HAS_ACTIVE_CALL);this._changeFeatureSet(),this._changeFeaturesPerRole(),this._logDevices()}_updateConversation(e){if(!this._conversation)throw new k(O.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`conversation`,description:`update-without-conversation`}});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||J.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1,this._conversation.waitForAdmin=!1,this._conversation.restricted=!1,this._cacheParticipantExternalIds(e.conversation.participants??[])}_createMediaSource(){let e=new Xt(this._debug,this._stats.logger);return this.subscribe(e,Jt.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Jt.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new bo(e,this._debug,this._stats.logger),e}async _connectSignaling(e,t){this._signaling.setEndpoint(t.endpoint),this._signaling.setWebTransportEndpoint(t.wt_endpoint?t.wt_endpoint:null),this.subscribe(this._signaling,Sr.NOTIFICATION,e=>this._signalingActor.add(e)),this.subscribe(this._signaling,Sr.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,Sr.RECONNECT,this._onSignalingReconnect.bind(this));let n=await this._signaling.connect(e,t);return this._stats.statAggregator.logEventualStat({name:U.SIGNALING_CONNECTED}),n}async _processConnection(e){await this._registerConnectionParticipants(e),this._processRooms(e),this._processMuteStates(e),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(qa.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants,null,null)}_onConversationParticipantListChunk(e){let t=e.participants;t&&R.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(this._createParticipantListChunk(t)),this.id)}_createParticipantListChunk(e){return{participants:[],countBefore:0,countAfter:0,markerFound:!1,...e}}_participantListChunkToExternalChunk(e){let t=this._participants,n=M.mapSharedParticipants(e.participants.reduce((e,n)=>{let r=M.composeId(n);return t[r]&&e.push(t[r]),e},[]));return{...e,participants:n}}async _registerConnectionParticipants(e){await this._registerParticipants(e.conversation.participants),e.participants?.participants&&await this._registerParticipants(e.participants?.participants);let t=e?.rooms?.rooms??[];for(let e of t)await this._registerParticipants(e?.participants?.participants??[],!0)}async _registerParticipants(e,t=!1){if(!this._conversation)return;let n=e[0]?.externalId?.type;n&&(N.externalUserType=n);let r=this._participants;for(let n of e){let e=M.composeId(n);if(z.test(`Conversation:RegisterParticipant`,e),this._isMe(e)){this._conversation.roles=n.roles||[],this._conversation.roles.length&&(this._debug.debug(`Local roles changed: ${n.roles}`),R.onLocalRolesChanged(this._conversation.roles,!0,this.id)),this._registerParticipantLocalMuteState(n);continue}if(n.state===X.HUNGUP||n.state===X.REJECTED){r[n.id]&&await this._removeParticipant(r[n.id],O.HUNGUP);continue}let i=M.composeDecorativeId(n);this._registerParticipant({id:e,externalId:Z.fromSignalingParticipant(n,!0,!0),mediaSettings:D(n.mediaSettings),participantState:M.mapParticipantState(n),state:n.state,roles:n.roles||[],connectionStatus:this._buildConnectionStatus(e,n.sessionState,void 0,n.onHold),isOnHold:!!n.onHold,muteStates:n.muteStates||{},unmuteOptions:n.unmuteOptions||[],observedIds:n.observedIds||[],markers:this._denormalizeMarkers(e,n.markers),movieShareInfos:n.movieShareInfos,isInRoom:t},i);let a=this._getParticipant(e);a&&n.roles&&n.roles.length&&(this._debug.debug(`Roles for participant [${e}] changed: ${n.roles}`),R.onRolesChanged(a.externalId,n.roles,!0,this.id)),a&&a.isOnHold&&R.onRemoteStatus([a.externalId],P.ONHOLD,null,this.id)}}_registerParticipantLocalMuteState({muteStates:e,unmuteOptions:t}){if(!e)return;let n=async()=>{let n=lo(e,Qa.MUTE),r=lo(e,Qa.MUTE_PERMANENT);for(let i of[n,r])i.length&&await this._onMuteParticipant({muteStates:e,unmuteOptions:t,mediaOptions:i,stateUpdated:!0})};M.setImmediate(()=>n().catch(e=>this._debug.error(e)))}_remoteParticipantSessionState(e,t){if(!(!N.enableSessionStateUpdates||this._isMe(e)))return t}_buildConnectionStatus(e,t,n,r=!1){return ao.create({transport:r?P.ONHOLD:ao.fromTransportState(n)??P.WAITING,sessionState:this._remoteParticipantSessionState(e,t),sessionStateApplicable:this._isParticipantSessionStateApplicable(e)})}_isParticipantSessionStateApplicable(e){return N.enableSessionStateUpdates&&!this._isMe(e)&&this._conversation?.topology===J.SERVER}_setTransportStatus(e,t){return ao.setTransport(e.connectionStatus,t)}_setSessionState(e,t){let n=ao.setSessionStateApplicable(e.connectionStatus,this._isParticipantSessionStateApplicable(e.id));this._emitParticipantTransition(e,n);let r=e.connectionStatus.sessionStateApplicable&&e.id===this._activeSpeakerId&&e.connectionStatus.transport===P.CONNECTED,i=ao.setSessionState(e.connectionStatus,t,r);return this._emitParticipantTransition(e,i),i}_emitParticipantTransition(e,t,n=null){t.shouldNotify&&R.onRemoteStatus([e.externalId],t.status,n,this.id)}_registerParticipantInCache(e){return this._participants[e.id]=e,e}_getExistedParticipantByIdOrCreate(e){let t=this._participants[e];if(t)return t;let n=this._api.getDecorativeIdByInitialId(e),r=this._getParticipantId(e),{deviceIdx:i}=M.decomposeParticipantId(e);return this._createParticipant({id:e,externalId:r?{...r,deviceIdx:i}:void 0},n,!1)}_getExternalIdByParticipantId(e){if(this._isMe(e))return this._conversation?.externalId??null;if(N.useParticipantListChunk)return this._getExistedParticipantByIdOrCreate(e).externalId;let t=this._participants;if(t[e]?.externalId)return t[e].externalId;let n=this._api.getCachedExternalIdByParticipantId(e);if(n)return n;let r=this._getParticipantId(e);return r&&this._api.cacheExternalId(e,r),r}_getExternalIdsByParticipantIds(e){let t=[],n=[];return e.forEach(e=>{let r=this._getExternalIdByParticipantId(e);r?t.push(r):n.push(e)}),{externalIds:t,missingIds:n}}_reportMissingExternalIds(e,t){e.length&&this._onNonFatalError(`External ID mapping not found for participants "${Array.from(new Set(e)).join(`", "`)}" while handling ${t}`)}_reportMissingExternalIdsById(e,t){e.length&&this._onNonFatalError(`Participant ID mapping not found for external IDs "${Array.from(new Set(e)).join(`", "`)}" while handling ${t}`)}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){if(N.useParticipantListChunk){let n=this._registerParticipantInCache(this._getExistedParticipantByIdOrCreate(e));return n.markers=this._denormalizeMarkers(n.id,t),n}return this._participants[e]}_warnParticipantNotInConversation(e){this._debug.warn(`Participant [${e}] isn't in conversation`)}_denormalizeMarkers(e,t){if(!t)return null;let n=Object.values(t).find(e=>`ts`in e&&`rank`in e);return Object.entries(t).reduce((t,[r,i])=>(t[r]={...n,...i,id:e},t),{})}_processRooms(e){let t=e.rooms?.roomId??null;this._onRoomSwitched(t,!0)}_processMuteStates(e,t=!1){let n=uo(e);this._setMuteStatesForRoomId(n,null);for(let t of e.rooms?.rooms??[])this._setMuteStatesForRoomId(t.muteStates,t.id);let r=this._getMuteStatesForCurrentRoom();t&&(r=ho(e,r));let i=Object.keys(r),a=this._conversation?.roomId;i.length&&this._onMuteParticipant({muteStates:r,mediaOptions:i,muteAll:!0,stateUpdated:!0,roomId:a},t)}_processRecordInfos(e){this._onRecordInfo(e.conversation?.recordInfo??null);for(let t of e.rooms?.rooms??[])this._onRecordInfo(t.recordInfo??null,t.id)}_processPinnedParticipants(e){e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId):this._conversation?.pinnedParticipantIdByRoom.delete(null);for(let t of e.rooms?.rooms??[])t.pinnedParticipantId?this._onPinParticipant(t.pinnedParticipantId,!1,void 0,t.id):this._conversation?.pinnedParticipantIdByRoom.delete(t.id)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new ma(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings,this._debug,this._stats.logger,this._stats.statAggregator,this._stats.codecStatsAggregator,this._getFirstMediaSentCallback()),this._debugInfo=new Do(this._debug),this.subscribe(this._transport,Y.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,Y.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,Y.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,Y.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,Y.AUDIO_MIX_STALL,this._onAudioMixStall.bind(this)),this.subscribe(this._transport,Y.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,Y.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,Y.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,Y.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,Y.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,Y.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this)),this.subscribe(this._transport,Y.ASR_TRANSCRIPTION,this._onAsrTranscription.bind(this)),this.subscribe(this._transport,Y.ANIMOJI_STREAM,this._onAnimojiStream.bind(this)),this.subscribe(this._transport,Y.ANIMOJI_ERROR,this._onAnimojiError.bind(this));let e=this._conversation.direction===Ga.OUTGOING&&!this._conversation.concurrent,t=this._participants;for(let n of Object.values(t))(n.state===X.ACCEPTED||n.state===X.CALLED)&&this._allocateParticipantTransport(n.id,e)}_createSpeakerDetector(){this._transport&&this._conversation&&(this._volumesDetector=new Po(this._transport),this.subscribe(this._volumesDetector,No.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Io(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,Fo.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new jo(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new zo(this._transport,this._volumesDetector,this._participants,this._debug,this._stats.logger))}_logDevices(){let e=E.getCameras().length,t=E.getMicrophones().length;this._debug.debug(`Cameras: `+e+(E.hasCameraPermission()?`✔`:`✖`)+`, Microphones: `+t+(E.hasMicrophonePermission()?`✔`:`✖`)),this._stats.logger.log(C.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){this._stats.logger.log(e,[t?.isAudioEnabled&&`audio`,t?.isVideoEnabled&&`video`].filter(Boolean).join(`_`))}async _removeParticipant(e,t){if(e.state===X.CALLED||e.state===X.ACCEPTED||this._state===`CLOSE`)return;e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null);let n=this._participants;if(n[e.id]){t===O.HUNGUP?this._setParticipantsStatus([e],P.HANGUP):this._setParticipantsStatus([e],P.ERROR,t),e.mediaSource?.disconnect(),this._displayLayoutRequester.cleanupParticipant(e.id),this._conversation&&this._conversation.pinnedParticipantIdByRoom.get(null)===e.id&&this._conversation.pinnedParticipantIdByRoom.delete(null),this._conversation&&this._conversation.roomId&&this._conversation.pinnedParticipantIdByRoom.get(this._conversation.roomId)===e.id&&this._conversation.pinnedParticipantIdByRoom.delete(this._conversation.roomId);for(let[t,n]of Object.entries(e.lastRequestedLayouts))this._streamIdByStreamDescription.delete(t),this._sequenceNumberByStreamDescription.delete(t),this._cooldownTimestampByStreamDescription.delete(t),this._streamWaitTimerByStreamDescription.has(t)&&(window.clearTimeout(this._streamWaitTimerByStreamDescription.get(t)),this._streamWaitTimerByStreamDescription.delete(t)),this._sendUpdateDisplayLayout({[t]:{stopStream:!0}},!1);this._api.unmapDecorativeId(e.id),delete n[e.id],R.onRemoteRemoved(e.externalId,e.markers,this.id)}}_cleanupListeners(){this.unsubscribe(),window.removeEventListener(`pagehide`,this._onUnload),window.removeEventListener(`pageshow`,this._onRestore)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{e.remoteStream?.getTracks().forEach(e=>e.stop()),e.remoteAudioTrack?.stop(),e.secondStream?.getTracks().forEach(e=>e.stop()),e.mediaSource?.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){this._debug.debug(`cleaning up participant-agnostic streams`),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(e=>{e.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)}_finishLifecycle(e){this._stopFirstMediaSentProbe(),this._stats.logHangup(e)}_getFirstMediaSentCallback(){let{lifecycle:e}=this._stats;return e.firstMediaSentReported||e.terminated?null:()=>e.markFirstMediaSent()}_stopFirstMediaSentProbe(){this._transport?.stopFirstMediaSentProbe?.()}_cleanupTransportForHold(){this._transport&&(this._transport.holdClose(),this._transport=null),this._debugInfo&&(this._debugInfo=null),this._cleanupSpeakerDetector(),this._cleanupSpecListener()}_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)}_disposeSignaling(e){if(!e){this._signaling.dispose();return}e.catch(e=>{e instanceof Dn||this._debug.warn(`[signaling] unable to send hangup`,e)}).finally(()=>this._signaling.dispose())}async _onAddParticipant(e,t,n){this._debug.debug(`Add new participant [${e}]`);let r=this._getParticipant(e);r&&this._updateParticipantExternalId(r,t);let i=!r;if(r&&(r.state===X.ACCEPTED||r.state===X.CALLED)){this._debug.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}if(!r){let n=M.composeDecorativeId(t);this._registerParticipant({id:e,externalId:Z.fromSignalingParticipant(t,!0,!0),mediaSettings:D(t.mediaSettings),state:t.state,roles:t.roles||[],connectionStatus:this._buildConnectionStatus(e,t.sessionState,this._transport?.getState(),t.onHold),isOnHold:!!t.onHold,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]},n),r=this._getParticipant(e)}this._setParticipantsStatus([r],P.WAITING),i&&this._emitParticipantEffectiveStatusIfSessionOverridesTransport(r),n?(r.state=X.HUNGUP,await this._removeParticipant(r,n)):this._transport&&(r.state=X.CALLED,this._allocateParticipantTransport(r.id,!0),this._stats.logger.log(C.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))}_onRemoveParticipant(e){this._debug.debug(`Remove participant [${e}]`);let t=[],n=this._participants;for(let r=0;r<=tc;r++){let i=n[M.compose(e,r)];i&&t.push(i)}if(!t.length){this._warnParticipantNotInConversation(e);return}for(let e of t)this._closeParticipantTransport(e.id);this._stats.logger.log(C.REMOVE_PARTICIPANT)}async changeDevice(e){return e===`audiooutput`?this._audioOutput.changeOutput():this._mediaSource?this._mediaSource.changeDevice(e):Promise.reject(x.UNKNOWN)}stopVideoTrack(){return this._mediaSource?.stopVideoTrack()}async toggleScreenCapturing(e){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(x.UNKNOWN)}async disableScreenCapturing(){return this._mediaSource?this._mediaSource.disableScreenCapturing():Promise.reject(x.UNKNOWN)}toggleAnimojiCapturing(e){this._mediaSource&&this._mediaSource.toggleAnimojiCapturing(e)}setAnimojiSvg(e,t=null,n=null){if(!this._transport||!this._conversation)return;let r=!t,i=t??this._conversation.compositeUserId;if(e instanceof ArrayBuffer){let t=n??this._conversation.externalId.id;this._transport.setAnimojiSvg(i,{svg:e,userId:t,isMe:r});return}this._transport.setAnimojiSvg(i,{svg:e,isMe:r})}setAnimojiFill(e){this._transport?.setAnimojiFill(e)}async setVideoStream(e,t=!1){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)}async setAudioStream(e){if(this._mediaSource)return this._mediaSource.setAudioStream(e)}toggleLocalVideo(e){return this._toggleLocalVideo(e)}toggleLocalAudio(e){return this._toggleLocalAudio(e)}async changePriorities(e){if(e.length<2||!this._signaling.ready)return;let t={},n={};for(let t of e){let e=typeof t.uid==`object`?t.uid:Z.fromId(t.uid),r=Z.toString(e);n[r]=t.priority}let r=this._participants;for(let e of Object.values(r)){let r=Z.toString(e.externalId);Object.hasOwn(n,r)&&(t[e.id]=n[r])}await this._signaling.changePriorities(t)}async changeParticipantState(e,t){for(let[t,n]of Object.entries(e))if(t.length>5||n.length>5)throw Error(`key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded`);t&&!this._isCallAdmin()&&(t=void 0),await this._signaling.changeParticipantState(e,t)}async hold(e,t){if(e){if(this._state===`HELD`)return;if(this._isWaitingForPromotion()){this._waitingHallHoldPending=!0,await this._holdLocally();return}await Promise.all([this._holdLocally(),this._signaling.hold(!0)]);return}if(this._isWaitingForPromotion()){this._waitingHallHoldPending=!1,await this._resumeLocalMedia(t,this._getWaitingForPromotionStatus()),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener();return}let n=wa.get();await this._signaling.hold(!1,n),this._restoreStateAfterHold();let r=null;if(this._state===`IDLE`&&this._participantState===X.ACCEPTED&&(r=Object.values(this._participants),r.some(e=>e.state===X.ACCEPTED)&&(this._state=`ACTIVE`,this._changeFeatureSet())),await this._resumeLocalMedia(t,P.WAITING),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._state===`ACTIVE`){let e=this._conversation?.direction===Ga.OUTGOING&&!this._conversation.concurrent;this._openTransport(r??Object.values(this._participants),e)}}async _holdLocally(){this._state!==`HELD`&&(this._previousState=this._state,this._state=`HELD`);let e=this._mediaSource?.stopLocalMedia();this._cleanupTransportForHold(),R.onLocalStatus(P.ONHOLD,this.id),await e}async _resumeLocalMedia(e,t){this._restoreStateAfterHold(),await this._mediaSource?.resumeLocalMedia(e),R.onLocalStatus(t,this.id),this._mediaSource&&R.onLocalStream(this._mediaSource?.getStream()??null,this._mediaSource.mediaSettings,this.id)}_restoreStateAfterHold(){this._state===`HELD`&&(this._state=this._previousState||`ACTIVE`,this._previousState=null)}_isWaitingForPromotion(){return!!this._conversation?.waitingHall||!!this._conversation?.waitForAdmin}_getWaitingForPromotionStatus(){return this._conversation?.waitForAdmin?P.WAIT_FOR_ADMIN:P.WAITING_HALL}async putHandsDown(){this._checkAdminRole(),await this._signaling.putHandsDown()}async requestKeyFrame(e){let t={};return t[Fn(e)]={keyFrameRequested:!0},this._signaling.updateDisplayLayout(t)}async requestTestMode(e,t){return this._signaling.requestTestMode(e,t)}async updateDisplayLayout(e){if(e.length<1||!this._signaling.ready)return;this._debug.log(`Update display layout request [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={},n=[],r=[],i=this._participants;for(let a of e){let e=typeof a.uid==`object`?a.uid:Z.fromId(a.uid),o=this._api.getCachedParticipantIdByExternalId(e);if(!o){let t=Z.toString(e);this._debug.log(`Unknown participant external ID ${t}`),r.push(e.id);continue}let s=Fn({participantId:o,mediaType:a.mediaType,streamName:a.streamName}),c=i[o];c?n.push(()=>{c.lastRequestedLayouts[s]=a}):this._isMe(o)&&n.push(()=>{this._myLastRequestedLayouts[s]=a}),An(a)?(this._isMe(o)&&n.push(()=>{delete this._myLastRequestedLayouts[s]}),this._streamIdByStreamDescription.has(s)&&!this._cooldownTimestampByStreamDescription.has(s)&&this._cooldownTimestampByStreamDescription.set(s,Date.now())):(this._cooldownTimestampByStreamDescription.delete(s),!this._streamIdByStreamDescription.has(s)&&N.videoTracksCount>0&&this._streamIdByStreamDescription.set(s,null),t[s]=a),a.mediaType===H.SCREEN&&!An(a)&&G.setMark(G.getMarkNameScreenshareFirstFrame(o))}if(r.length){this._reportMissingExternalIdsById(r,`updateDisplayLayout`);return}let a=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>N.videoTracksCount;){let e=a.next();if(e.done){this._debug.error(`Cannot accommodate all streaming requests: tracks available `+N.videoTracksCount+`; requested streams: `+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(e.value),t[e.value]={stopStream:!0}}if(this._transport?.getTopology()!==J.SERVER){n.forEach(e=>e());return}await this._sendUpdateDisplayLayout(t),n.forEach(e=>e())}async requestDisplayLayout(e){return this._displayLayoutRequester.request(e)}async 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)&&(this._debug.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 t=this._participants,n=In(e),r=t[n.participantId],i=this._conversation?.externalId,a=this._isMe(n.participantId);if(r||a){switch(n.mediaType){case H.STREAM:case H.MOVIE:if(n.streamName){let e={stream:null,streamName:n.streamName,mediaType:n.mediaType};a?R.onLocalLive(i,e,this.id):R.onRemoteLive(r.externalId,e,this.id)}break;case H.CAMERA:R.onRemoteStream(r.externalId,null,this.id);break;case H.SCREEN:R.onRemoteScreenStream(r.externalId,null,this.id);break}this._stats.logger.log(C.PAT_DEALLOCATED)}else this._debug.log(`Cannot find participant to stop streaming: ${n.participantId}`)}this._streamIdByStreamDescription.delete(e)}async _sendUpdateDisplayLayout(e,t=!0){if(Object.keys(e).length===0)return;this._debug.log(`Update display layout send [${this._signaling.getNextCommandSequenceNumber()}]`,e);let n;try{if(n=await this._signaling.updateDisplayLayout(e),!n)return}catch(n){if(this._debug.warn(`Failed to update display layout ${JSON.stringify(e)}. ${n}`),t)throw n;return}let r=[],i=this._participants;for(let[e,t]of Object.entries(n.errorCodeByParticipantId||{})){let n=In(e),a=i[n.participantId];if(a){let e;typeof t==`number`?e=to(t):(this._debug.warn(`Unexpected error code ${t} received for participant ${n.participantId}`),e=eo.UNKNOWN_ERROR),r.push({externalId:a.externalId,errorReason:e})}}if(r&&r.length&&(this._debug.warn(`Could not allocate one or more participants`,r),t))throw new rc(`Could not allocate one or more participants`,r)}async _cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let n=t.next();if(n.done)break;let r=n.value;if(r[1]+$s>Date.now())break;let i=r[0];await this._stopStreaming(i),e[i]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e,!1)}_onParticipantSourcesUpdate(e){if(this._conversation){let t=e.participantUpdateInfos;this._debug.log(`Received participant sources update notification`,t);for(let e of t)this._waitForStreamIfNeeded(e)}}async _onParticipantPromoted(e){this._conversation&&this._conversation.audienceMode?(this._debug.log(`Promoted in audience mode`,!e.demote),this._conversation.restricted=e.demote,this._processRecordInfos(e),!e.demote&&this._mediaSource&&this._changeMediaSettings(this._mediaSource.mediaSettings)):(this._debug.log(`Promoted in waiting hall`,!e.demote),e.demote?(this._debug.log(`Kicked from waiting hall`),this._close(new k(O.REMOVED))):(this._updateConversation(e),this._waitingHallHoldPending?(await this._signaling.hold(!0),await this._onJoinPart2(e,!1),this._waitingHallHoldPending=!1):B.getActive()&&N.hold?(await this._signaling.hold(!0),await this._onJoinPart2(e,!0,!0),this._waitingHallHoldPending=!1):await this._onJoinPart2(e))),R.onPromoted(e.demote,this.id)}_onChatRoomUpdated(e,t=0,n=[],r,i){this._debug.log(`Chat room updated: ${e}`);let a=[],o=[];n.length&&n.forEach(e=>{if(e.externalId){let t=Z.fromSignaling(e.externalId);a.push(t),this._api.cacheExternalId(e.id.id,t)}else{let t=this._getExternalIdByParticipantId(e.id.id);t?a.push(t):o.push(e.id.id)}});let{externalIds:s,missingIds:c}=this._getExternalIdsByParticipantIds(r??[]);o.push(...c);let{externalIds:l,missingIds:u}=this._getExternalIdsByParticipantIds(i??[]);o.push(...u),this._reportMissingExternalIds(o,`CHAT_ROOM_UPDATED`),R.onChatRoomUpdated(e,t,a,s,l,this.id)}_onSharedMovieUpdate(e){let t=this._conversation?.externalId;for(let n of e.data)if(this._isMe(n.participantId))R.onLocalLiveUpdate(t,n,this.id);else{let e=this._getExternalIdByParticipantId(n.participantId);e&&R.onRemoteLiveUpdate(e,n,this.id)}}_onSharedMovieInfoStarted(e){this._debug.log(`Shared movie started data received: ${e.notification}`),this._processSharedMovieInfo(e.movieShareInfo,e.roomId)}_processSharedMovieInfos(e,t=null){e&&e.forEach(e=>this._processSharedMovieInfo(e,t))}_processSharedMovieInfo(e,t=null){if(!e)return;let n=this._conversation?.externalId;if(this._isMe(e.initiatorId))R.onLocalSharedMovieInfo(n,e,t,this.id);else{let n=this._getExternalIdByParticipantId(e.initiatorId);n&&R.onRemoteSharedMovieInfo(n,e,t,this.id)}}_processConnectionSharedMovieInfo(e){let t=e.conversation.participants.find(e=>this._isMe(M.composeId(e)));this._processSharedMovieInfos(t?.movieShareInfos,e?.rooms?.roomId??null)}_processConnectionAsrInfo(e){let t=e?.conversation.asrInfo??this._conversation?.asrInfo;if(t&&this._conversation?.asrInfoByRoom.set(null,t),e?.rooms?.rooms)for(let t of e.rooms.rooms)t.asrInfo&&this._conversation?.asrInfoByRoom.set(t.id,t.asrInfo);let n=e?.rooms?.roomId??this._conversation?.roomId??null,r=this._conversation?.asrInfoByRoom.get(n);if(r){let e=this._getExternalIdByParticipantId(r.initiatorId);e&&R.onAsrSet({externalId:e,movieId:r.movieId},n,this.id)}else n&&R.onAsrSet(null,n,this.id)}_processConversationUrlSharingInfo(e){if(!this._conversation)return;e&&this._extractConnectionUrlSharingInfo(e);let{urlSharingInfoByRoom:t}=this._conversation,n=this._conversation.roomId,r=t.get(n);if(r&&!this._isMe(r.initiatorId)){let e=this._getExternalIdByParticipantId(r.initiatorId);e&&R.onRemoteSharedUrl(e,r.sharedUrl,n,this.id)}}_extractConnectionUrlSharingInfo(e){if(!this._conversation)return;let{urlSharingInfoByRoom:t}=this._conversation;if(e.conversation.urlSharingInfo?t.set(null,e.conversation.urlSharingInfo):t.delete(null),e.rooms?.rooms)for(let n of e.rooms.rooms)n.urlSharingInfo?t.set(n.id,n.urlSharingInfo):t.delete(n.id)}_onSharedMovieInfoStopped(e){this._debug.log(`Shared movie stopped data received: ${e.notification}`);let t=this._conversation?.externalId,{initiatorId:n,movieId:r,source:i,roomId:a=null}=e,o={initiatorId:n,movieId:r,source:i};if(this._isMe(n))R.onLocalSharedMovieStoppedInfo(t,o,a,this.id);else{let e=this._getExternalIdByParticipantId(n);if(e){let t=this._participants[n];t?.movieShareInfos&&(t.movieShareInfos=t.movieShareInfos.filter(e=>e&&e.movieId!==r)),R.onRemoteSharedMovieStoppedInfo(e,o,a,this.id)}}}_onUrlSharingInfoUpdated(e){if(this._debug.log(`Shared URL data received: ${e.notification}`),!this._conversation)return;let{urlSharingInfoByRoom:t,roomId:n}=this._conversation,{initiatorId:r,sharedUrl:i,roomId:a=null}=e;if(i?t.set(a,{sharedUrl:i,initiatorId:r}):t.delete(a),!(!i&&a!==n&&t.has(n))&&(!i||!this._isMe(r))){let e=this._getExternalIdByParticipantId(r);e&&R.onRemoteSharedUrl(e,i,a,this.id)}}_onFeaturesPerRoleChanged(e){this._debug.log(`Features per role changed: ${e.notification}`),this._conversation&&(this._conversation.featuresPerRole=e.featuresPerRole??{}),R.onFeaturesPerRoleChanged(e.featuresPerRole,this.id)}async _waitForStreamIfNeeded(e){if(e.fastScreenShare&&!e.participantStreamDescription){let t=this._getStreamDescriptionById(e.streamId);if(t){let e=In(t),n=this._getParticipant(e.participantId);R.onRemoteScreenStream(n.externalId,null,this.id);return}}let t=this._matchStreamDescription(e.participantStreamDescription);if(!t)return;let{mediaType:n,participantId:r}=t;if(n===H.ANIMOJI)return;let i=this._getParticipant(r);if(n===H.SCREEN&&!e.fastScreenShare){this._debug.log(`skipping participant-sources-update notification since screenshare will be received over datachannel`);return}let a=Fn(t),o=this._sequenceNumberByStreamDescription.get(a);if(o&&o>e.sequenceNumber){this._debug.warn(`Participant ${r} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${o}`),this._stats.logger.log(C.PAT_OUTDATED_RESPONSE);return}i&&e.suspend!==void 0&&n&&(this._debug.debug(`participant-sources-update: mediaType=${n}, suspend=${e.suspend}`),R.onRemoteStreamSuspended(i.externalId,n,e.suspend,this.id));let s=e.streamId,c=e.rtpTimestamp?this._getWaitingTime(s,e.rtpTimestamp):0;if(c<=0){this._streamWaitTimerByStreamDescription.delete(a);let t=this._conversation?.externalId,n=this._isMe(r);if(!i&&!n){this._stats.logger.log(C.PAT_ERROR,`participantMissing`),this._debug.error(`Could not find participant by ID: ${r}`);return}let o=n?t:i.externalId,c=this._streamByStreamId.get(s);if(!c){this._stats.logger.log(C.PAT_ERROR,`streamNotFound`),this._debug.error(`Could not find stream by ID: ${s}`);return}this._stats.logger.log(C.PAT_ALLOCATED),this._streamIdByStreamDescription.set(a,s);let l=e.participantStreamDescription?.mediaType;if(l===H.STREAM||l===H.MOVIE){if(e.participantStreamDescription?.streamName){let t={streamName:e.participantStreamDescription.streamName,stream:c,mediaType:l};n?R.onLocalLive(o,t,this.id):R.onRemoteLive(o,t,this.id)}}else l===H.SCREEN?R.onRemoteScreenStream(i.externalId,c,this.id):n||R.onRemoteStream(i.externalId,c,this.id)}else{this._debug.debug(`Waiting for ${c} until stream ${s} for ${a} is switched`);let t=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),c);this._streamWaitTimerByStreamDescription.set(a,t)}}_getStreamDescriptionById(e){for(let[t,n]of this._streamIdByStreamDescription.entries())if(n===e)return t;return null}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Fn(e)))return e;let t=e.participantId;if(e.mediaType){let e={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Fn(e)))return e}else{let e={participantId:t,mediaType:H.CAMERA};if(this._streamIdByStreamDescription.has(Fn(e)))return e;let n={participantId:t,mediaType:H.SCREEN};if(this._streamIdByStreamDescription.has(Fn(n)))return n}return this._debug.error(`Received unrequested allocation`,e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw Error(`transport is not initialized`)}_isCallAdmin(){return this._conversation?M.includesOneOf(this._conversation.roles,[no.ADMIN,no.CREATOR]):!1}_checkAdminRole(){if(this._conversation&&!M.includesOneOf(this._conversation.roles,[no.ADMIN,no.CREATOR]))throw Error(`You don't have the required permission`)}_isCalledState(){return this._participantState===X.CALLED}async grantRoles(e,t,n){this._checkAdminRole(),await this._signaling.grantRoles(e,t,n)}async startAsr(e){await this._signaling.startAsr(e)}async stopAsr(e){await this._signaling.stopAsr(e)}async requestAsr(e){this._isRealTimeAsrRequested=e,await this._signaling.requestAsr(e)}async muteParticipant(e=null,t,n=[],r=null){this._checkAdminRole(),await this._signaling.muteParticipant(e,t,n,r)}async enableFeatureForRoles(e,t){await this._signaling.enableFeatureForRoles(e,t)}async pinParticipant(e,t,n=null){this._checkAdminRole(),await this._signaling.pinParticipant(e,t,n),this._conversation?.pinnedParticipantIdByRoom.set(n,t?null:e)}async updateMediaModifiers(e){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,await this._signaling.updateMediaModifiers(e))}async enableVideoSuspend(e){this._signaling.ready&&this._conversation&&this._transport?.getTopology()===J.SERVER&&await this._signaling.enableVideoSuspend(e)}async enableVideoSuspendSuggest(e){this._signaling.ready&&this._conversation&&this._transport?.getTopology()===J.SERVER&&await this._signaling.enableVideoSuspendSuggest(e)}async changeOptions(e){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),await this._signaling.changeOptions(e);let t=Za(this._conversation.options,e);this._onOptionsChanged(t)}}async getWaitingHall(e,t,n){if(!this._signaling)return Promise.reject();let r=null;if(e&&(r=co(e),r)){let e=this._api.getDecorativeIdByInitialId(r.id);r.id=e??r.id}let i=await this._signaling.getWaitingHall(r,t,n);if(i.error)return Promise.reject(i.message);let a=i.participants||[],{externalIds:o}=this._resolveWaitingHallExternalIds(a,`getWaitingHall`),s=null;return a.length&&i.hasMore&&(s=so(a[a.length-1].id)),{participants:o,pageMarker:s,totalCount:i.totalCount||0}}_resolveWaitingHallExternalIds(e,t){let n=[],r=[],i=[];return e.length&&e.forEach(e=>{if(e.externalId){let t=Z.fromSignaling(e.externalId);n.push(e.id.addedTs),r.push(t),this._api.cacheExternalId(e.id.id,t)}else{let t=this._getExternalIdByParticipantId(e.id.id);t?(r.push(t),n.push(e.id.addedTs)):i.push(e.id.id)}}),this._reportMissingExternalIds(i,t),{externalIds:r,timestamps:n}}async getAudienceModeHands(){if(!this._signaling.ready)throw Error(`Signaling is not ready`);let e=await this._signaling.getHandQueue();if(e.error)return Promise.reject(e.message);let t=e.participants||[],{externalIds:n,timestamps:r}=this._resolveWaitingHallExternalIds(t,`getAudienceModeHands`);return{timestamps:r,participants:n,totalCount:e.totalCount||0}}async promoteParticipant(e,t){if(this._signaling&&this._conversation)try{if(!M.includesOneOf(this._conversation.options,[Ya.WAITING_HALL,Ya.AUDIENCE_MODE]))throw Error(`Unable to promote a participant in the conversation with current options`);if(this._checkAdminRole(),!e&&t)throw Error(`participantId is required`);await this._signaling.promoteParticipant(e,t)}catch(t){throw this._debug.warn(`Failed to promote participant ${e}. ${t}`),t}}async requestPromotion(e=!1){this._signaling.ready&&await this._signaling.requestPromotion(e)}async acceptPromotion(e=!1){this._signaling.ready&&await this._signaling.acceptPromotion(e)}async chatMessage(e,t=null){this._signaling.ready&&await this._signaling.chatMessage(e,t)}async chatHistory(e){if(this._signaling.ready){let t=await this._signaling.chatHistory(e);for(let e=t.messages.length-1;e>=0;e--){let n=t.messages[e];this._onChatMessage(n)}}}async customData(e,t=null){this._signaling.ready&&await this._signaling.customData(e,t)}async createJoinLink(){if(this._conversation){let e=(await this._api.createJoinLink(this._conversation.id)).join_link;if(e)return this._conversation.joinLink=e,e}return Promise.reject()}async removeJoinLink(){if(this._conversation&&(await this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()}async addMovie({movieId:e,gain:t,metadata:n,lang:r}){let i={movieId:e,lang:r};(t||t===0)&&(i.gain=t),n&&(i.metadata=n);let a=await this._signaling.addMovie(i);if(a.error)throw Error(a.error);return{movieId:a.movieId,streamType:a.streamType}}async updateMovie(e){let t=await this._signaling.updateMovie(e);if(t.error)throw Error(t.error)}async removeMovie(e){let t={movieId:e},n=await this._signaling.removeMovie(t);if(n.error)throw Error(n.error)}async startUrlSharing(e){let t=await this._signaling.startUrlSharing(e);if(t.error)throw Error(t.error)}async stopUrlSharing(){let e=await this._signaling.stopUrlSharing();if(e.error)throw Error(e.error)}async updateRooms(e,t){let n=await this._signaling.updateRooms(e,t);if(n.error)throw Error(n.error)}async activateRooms(e,t){let n=await this._signaling.activateRooms(e,t);if(n.error)throw Error(n.error)}async switchRoom(e,t){let n=await this._signaling.switchRoom(e,t);if(n.error)throw Error(n.error)}async removeRooms(e){let t=await this._signaling.removeRooms(e);if(t.error)throw Error(t.error)}async startStream(e=!1,t=null,n=null,r=`DIRECT_LINK`,i=null,a=null){let o={movieId:n,name:t,privacy:r,groupId:i,roomId:a,streamMovie:!e},s=await this._signaling.startStream(o);if(s.error)return Promise.reject(Error(s.message))}async stopStream(e=null,t){let n=await this._signaling.stopStream({roomId:e,...t&&{remove:t}});if(n.error)return Promise.reject(Error(n.message))}async publishStream(e=null){if((await this._signaling.publishStream({roomId:e})).error)return Promise.reject()}async getStreamInfo(){let e=await this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}}async setLocalResolution({video:e,effect:t}){if(e.width<N.videoMinWidth||e.height<N.videoMinHeight)throw Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(t){if(t.width<N.videoMinWidth||t.height<N.videoMinHeight)throw Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");N.videoEffectMaxHeight=t.height,N.videoEffectMaxWidth=t.width}N.videoMaxWidth=e.width,N.videoMaxHeight=e.height,this._debug.debug(`Set local video resolution:`,`video ${e.width}x${e.height}`+(t?`, effect ${t.width}x${t.height}`:``)),this._mediaSource&&(await this._mediaSource.setResolution({video:e,effect:t}),this._transport&&await this._transport.onCameraResolutionChanged())}async videoEffect(e){return this._mediaSource?.videoEffect(e)}async audioEffect(e,t){return this._mediaSource?.audioEffect(e?{effects:e,isPreset:t}:null)}_convertExternalIdsToServerExternalIds(e){return e.map(e=>({id:e.id,type:N.externalUserType}))}async getParticipants(e){let t=this._convertExternalIdsToServerExternalIds(e.externalIds),n=await this._signaling.getParticipants(t);if(n.error)throw Error(n.error);let r=n.participants,i=this._transport?.getState();return M.mapSharedParticipants(r.map(e=>{let t=M.composeId(e);return this._createParticipant({id:t,externalId:Z.fromSignalingParticipant(e,!0,!0),mediaSettings:D(e.mediaSettings),participantState:M.mapParticipantState(e),state:e.state,roles:e.roles||[],connectionStatus:this._buildConnectionStatus(t,e.sessionState,i,e.onHold),isOnHold:!!e.onHold,muteStates:e.muteStates||{},unmuteOptions:e.unmuteOptions||[],observedIds:e.observedIds||[],markers:this._denormalizeMarkers(t,e.markers)},M.composeDecorativeId(e))}))}async getParticipantListChunk(e){this._debug.log(`Request participant list chunk`,e);let t=await this._signaling.getParticipantListChunk(e);if(t.error)throw Error(t.error);let n=this._createParticipantListChunk(t.chunk),r=this._participants,i=n.participants.filter(e=>!r[M.composeId(e)]);await this._registerParticipants(i);let a=this._transport?.getState();return n.participants.forEach(e=>{let t=M.composeId(e),n=r[t];this._updateParticipantExternalId(n,e),this._setSessionState(n,this._remoteParticipantSessionState(t,e.sessionState)),n.isOnHold||this._setTransportStatus(n,ao.fromTransportState(a)??P.WAITING),n.movieShareInfos=e.movieShareInfos,Object.assign(n.mediaSettings,D(e.mediaSettings)),Object.assign(n.muteStates,e.muteStates),n.unmuteOptions=e.unmuteOptions??n.unmuteOptions,this._openTransport([n],!0)}),this._participantListChunkToExternalChunk(n)}async _getInitialParticiapntListChunk(){let e=N.participantListChunkInitIndex,t=N.participantListChunkInitCount,n=await this._signaling.getParticipantListChunk({listType:`GRID`,fromIdx:e,count:t});return this._debug.debug(`Get initial participant list chunk`,n.chunk),n.chunk}_onLocalMediaStreamChanged(e){if(!this._conversation||!this._mediaSource)return;let t=this._mediaSource.mediaSettings;this._debug.debug(`Local media stream changed`,t),e.kind===A.audio&&this._mediaSource&&(this._audioFix=new bo(this._mediaSource,this._debug,this._stats.logger)),R.onLocalStreamUpdate(t,e.kind,this.id),!this._conversation?.waitingHall&&!this._conversation?.observer&&!this._isAudienceModeListener()&&this._changeMediaSettings(t)}_onScreenSharingStatus(e){let t=this.mediaSettings;this._debug.log(`Screen sharing changed`,e.track,t);let n=e.track?new MediaStream([e.track]):null;R.onScreenStream(n,t,this.id)}_changeRemoteMediaSettings(e,t){this._debug.debug(`Remote media settings changed [${e}]`,t);let n=this._conversation?.externalId;if(this._isMe(e)&&n){R.onLocalMediaSettings(n,t,this.id);return}let r=this._getParticipant(e);if(!r){this._warnParticipantNotInConversation(e);return}r.mediaSettings=t,[`ACTIVE`,`HELD`].includes(this._state)&&(r.externalId?R.onRemoteMediaSettings(r.externalId,t,r.markers,this.id):this._reportMissingExternalIds([e],`REMOTE_MEDIA_SETTINGS`)),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t)}_extractLocalParticipantFromConnection(e){let t=this._api.getUserId();return(e.conversation.participants||[]).find(n=>n.id===t||M.comparePeerId(n.peerId,e.peerId))}_changeLocalParticipantState(e){this._debug.debug(`Local participant state force changed by admin`,e),[`ACTIVE`,`HELD`].includes(this._state)&&R.onLocalParticipantState(e,!1,this.id)}async _changeRemoteParticipantState(e,t){this._debug.debug(`Remote participant state changed [${e}]`,t);let n=this._getParticipant(e);if(!n){this._warnParticipantNotInConversation(e);return}n.participantState=t||{},[`ACTIVE`,`HELD`].includes(this._state)&&(n.externalId?R.onRemoteParticipantState(n.externalId,n.participantState,n.markers,this.id):this._reportMissingExternalIds([e],`REMOTE_PARTICIPANT_STATE`))}_changeMultipleParticipantState(e,t){this._debug.debug(`Multiple participants state changed`,e);let n=[],r,i=this._participants;e.forEach((e,t)=>{if(this._isMe(t))r=e;else{let r=i[t];if(!r){this._warnParticipantNotInConversation(t);return}r.participantState=e,n.push({externalId:r.externalId,participantState:{...e},markers:r.markers})}}),[`ACTIVE`,`HELD`].includes(this._state)&&(r&&R.onLocalParticipantState(r,!0,this.id),n.length&&R.onRemoteParticipantsState(n,t,this.id))}_invokeRolesChangedCallbackIfNeeded(e){this._state===`ACTIVE`&&e.roles&&e.roles.length&&(this._debug.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),R.onRolesChanged(e.externalId,e.roles,!0,this.id))}_onSignalingNotification(e){switch(e.notification){case K.ACCEPTED_CALL:return this._onAcceptedCall(e);case K.HUNGUP:return this._onHungup(e);case K.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case K.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case K.CLOSED_CONVERSATION:return this._onClosedConversation(e);case K.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case K.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case K.SESSION_STATE:return this._onSessionState(e);case K.PARTICIPANTS_STATE_CHANGED:return this._onParticipantsStateChanged(e);case K.RATE_CALL_DATA:return this._onNeedRate();case K.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case K.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case K.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case K.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case K.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case K.REGISTERED_PEER:return this._onPeerRegistered(e);case K.SWITCH_MICRO:return this._onMicSwitched(e);case K.CHAT_MESSAGE:return this._onChatMessage(e);case K.CUSTOM_DATA:return this._onCustomData(e);case K.RECORD_STARTED:return this._onRecordInfo(e.recordInfo,e.roomId);case K.RECORD_STOPPED:return this._onStopRecordInfo(e,e.roomId);case K.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case K.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case K.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin,e.markers,e.roomId);case K.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case K.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e);case K.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case K.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants,e.addedParticipantIds,e.removedParticipantIds);case K.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e);case K.FEEDBACK:return this._onFeedback(e);case K.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e);case K.MOVIE_SHARE_STARTED:return this._onSharedMovieInfoStarted(e);case K.MOVIE_SHARE_STOPPED:return this._onSharedMovieInfoStopped(e);case K.URL_SHARING_INFO_UPDATED:return this._onUrlSharingInfoUpdated(e);case K.ROOMS_UPDATED:return this._onRoomsUpdated(e);case K.ROOM_UPDATED:return this._onRoomUpdated(e);case K.ROOM_PARTICIPANTS_UPDATED:return this._onRoomParticipantsUpdated(e);case K.FEATURES_PER_ROLE_CHANGED:return this._onFeaturesPerRoleChanged(e);case K.PARTICIPANT_ANIMOJI_CHANGED:return this._onParticipantAnimojiChanged(e);case K.ASR_STARTED:return this._onAsrStart(e);case K.ASR_STOPPED:return this._onAsrStop(e);case K.PROMOTION_APPROVED:return this._onPromotionApproved(e);case K.DECORATIVE_PARTICIPANT_ID_CHANGED:return this._onDecorativeParticipantIdChanged(e);case K.VIDEO_SUSPEND_SUGGEST:return this._onVideoSuspendSuggest(e);case K.HOLD:return this._onParticipantHold(e);case K.TOPOLOGY_CHANGED:return this._onSignalingTopologyChanged(e)}}_onSignalingTopologyChanged(e){this._conversation&&e.topology!==this._conversation.topology&&(this._debug.log(`Signaling topology changed while transport is down: ${this._conversation.topology} -> ${e.topology}`),this._conversation.topology=e.topology)}_onPromotionApproved(e){let t=this._getExternalIdByParticipantId(e.adminId);if(!t){this._warnParticipantNotInConversation(e.adminId);return}R.onPromotionApproved(t,this.id)}async _onSignalingReconnect(e){if(!this._conversation)return;e.conversationParams?.serverTime&&(this._serverTimeOffset=e.conversationParams.serverTime-Date.now()),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(),this._changeFeaturesPerRole()),this._processPinnedParticipants(e),e.conversation.state;let t=null;if(e.conversation.participants){let n=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let e=M.composeId(n),i=n.roles||[];if(this._isMe(e)){ro(this._conversation.roles,i)||this._onRolesChanged(e,i),t=()=>{this._registerParticipantLocalMuteState({muteStates:mo(n),unmuteOptions:n.unmuteOptions})};continue}r.push(e);let a=this._getParticipant(e);if(!a)await this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{this._updateParticipantSessionState(a,e,n.sessionState);let t=D(n.mediaSettings);Gt(t,a.mediaSettings)||this._changeRemoteMediaSettings(e,t);let r=M.mapParticipantState(n),o=a.participantState;M.isEqualParticipantState(r,o)||await this._changeRemoteParticipantState(e,r),ro(i,a.roles)||this._onRolesChanged(a.id,i),!!n.onHold!=!!a.isOnHold&&(a.isOnHold=!!n.onHold,this._setParticipantsStatus([a],n.onHold?P.ONHOLD:P.CONNECTED))}}let i=this._participants;for(let e of n)r.indexOf(e)<0&&i[e]&&this._removeParticipant(i[e],O.HUNGUP)}let n=[...e.participants?.participants??[],...e.rooms?.rooms.flatMap(e=>e.participants?.participants??[])??[]];await this._reconcileParticipantSessionStates(n);let r=e.rooms?.roomId??null;if(!this._conversation){this._debug.warn(`Conversation is empty, but should be filled`);return}this._conversation.roomId===r?this._processMuteStates(e,!0):await this._onRoomSwitched(r),t?.(),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options)}_onSignalingFailed(e){this._debug.error(`Signaling failed`,e),this._close(e)}async _onAcceptedCall(e){let t=M.composeMessageId(e),n=M.getPeerIdString(e.peerId);if(this._debug.debug(`Participant accepted call [${t}]`),this._statFirstMediaReceived.markAcceptedCall(this._transport?.getTopology()),this._conversation&&this._isMe(t)){if(this._conversation.concurrent)return;this._close(new k(O.MISSED),{errorText:`Call accepted on other device`});return}this._conversation?.direction===Ga.OUTGOING&&!this._conversation.concurrent&&this._stats.lifecycle.markOutgoingAccepted();let r=this._getParticipant(t);if(!r){let n=this._api.getDecorativeIdByInitialId(t);r=this._registerParticipantInCache(this._createParticipant({id:t,externalId:e.externalId?Z.fromSignaling(e.externalId,e.deviceIdx):void 0,mediaSettings:D(e.mediaSettings)},n))}else if(e.externalId){let t=Z.fromSignaling(e.externalId,e.deviceIdx);r.externalId=t,this._api.cacheExternalId(r.id,t)}r.state=X.ACCEPTED,r.mediaSettings=D(e.mediaSettings),this._logWithMediaSettings(C.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Ga.OUTGOING&&(this._state===`IDLE`||this._state===`PROCESSING`)&&(this._state=`ACTIVE`,this._changeFeatureSet()),this._state===`ACTIVE`&&this._transport&&this._transport.open([r.id],n),this._changeRemoteMediaSettings(t,r.mediaSettings),await this._changeRemoteParticipantState(t);let i=Object.keys(r.muteStates);if(i.length&&this._onMuteParticipant({muteStates:r.muteStates,mediaOptions:i,stateUpdated:!0,participantId:t}),[`ACTIVE`,`HELD`].includes(this._state)){if(!r.externalId){this._reportMissingExternalIds([t],`ACCEPTED_CALL`);return}R.onAcceptedCall(r.externalId,Ea.parseCapabilities(e.capabilities),this.id)}}async _onHungup(e){this._debug.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=M.composeMessageId(e);if(this._conversation&&this._isMe(t)){let t={remote:!0,callError:e.callError,message:void 0};e.reason===O.OBSOLETE_CLIENT&&e.errorCode&&(t.message=e.errorCode),this._close(new k(e.reason,t));return}this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers);let n=this._getParticipant(t);if(!n){this._warnParticipantNotInConversation(t);return}if(this._closeParticipantTransport(t),n.state=e.reason===O.REJECTED?X.REJECTED:X.HUNGUP,this._state!==`CLOSE`){let t=e.reason===O.OBSOLETE_CLIENT?O.OBSOLETE_CLIENT:O.HUNGUP;this._removeParticipant(n,t)}}_onSessionState(e){if(!N.enableSessionStateUpdates)return;let t=M.composeMessageId(e);if(this._isMe(t))return;this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers);let n=this._getParticipant(t);if(!n){this._warnParticipantNotInConversation(t);return}if(e.connected){let e=ao.fromTransportState(this._transport?.getState());e&&this._setTransportStatus(n,e)}this._setSessionState(n,{connected:e.connected})}async _reconcileParticipantSessionStates(e){if(!N.enableSessionStateUpdates||!e.length)return;let t=this._participants;for(let n of e){let e=M.composeId(n),r=t[e];r&&!this._isMe(e)&&(this._updateParticipantExternalId(r,n),this._updateParticipantSessionState(r,e,n.sessionState))}}_updateParticipantExternalId(e,t){let n=Z.fromSignalingParticipant(t)??Z.fromSignalingParticipant(t,!1);n&&(e.externalId=n,this._api.cacheExternalId(e.id,n))}_updateParticipantSessionState(e,t,n){return this._setSessionState(e,this._remoteParticipantSessionState(t,n))}_emitParticipantEffectiveStatusIfSessionOverridesTransport(e){e.connectionStatus.sessionState?.connected!==!1||e.connectionStatus.lastEffective===e.connectionStatus.transport||R.onRemoteStatus([e.externalId],e.connectionStatus.lastEffective,null,this.id)}async _onAddedParticipant(e){this._debug.debug(`Participant added [${e.participantId}]`);let t=M.composeMessageId(e),n=this._getParticipant(t);n&&this._updateParticipantExternalId(n,e.participant);let r=!n;if(n&&n.state!==X.HUNGUP&&n.state!==X.REJECTED){this._debug.debug(`Participant [${t}] is already in conversation and is active`);return}if(!n){let{participant:r}=e,i=M.composeDecorativeId(r);this._registerParticipant({id:t,externalId:Z.fromSignalingParticipant(r,!0,!0),mediaSettings:D(r.mediaSettings),state:r.state,participantState:M.mapParticipantState(r),roles:r.roles||[],connectionStatus:this._buildConnectionStatus(t,r.sessionState,this._transport?.getState(),r.onHold),isOnHold:!!r.onHold,muteStates:r.muteStates||{},unmuteOptions:r.unmuteOptions||[],observedIds:r.observedIds||[]},i),n=this._getParticipant(t)}n.state=X.CALLED,n.mediaSettings=D(e.participant?.mediaSettings),n.participantState=M.mapParticipantState(e.participant),n.roles=e.participant?.roles||[],this._updateParticipantSessionState(n,t,e.participant.sessionState),this._setParticipantsStatus([n],P.WAITING),r&&this._emitParticipantEffectiveStatusIfSessionOverridesTransport(n),this._state!==`IDLE`&&this._transport&&this._allocateParticipantTransport(n.id,!0),R.onParticipantAdded(n.externalId,n.markers,this.id),this._changeRemoteMediaSettings(t,n.mediaSettings),await this._changeRemoteParticipantState(t,n.participantState),this._invokeRolesChangedCallbackIfNeeded(n)}async _onJoinedParticipant(e){this._debug.debug(`Participant joined [${e.participantId}]`),this._statFirstMediaReceived.markOnJoin(this._transport?.getTopology());let t=M.composeMessageId(e),n=this._getParticipant(t);n&&this._updateParticipantExternalId(n,e.participant);let r=!n;if(n&&n.state===X.ACCEPTED){this._debug.warn(`Participant [${t}] is already in conversation and is active`);return}if(!n){let{participant:r}=e,i=M.composeDecorativeId(r);this._registerParticipant({id:t,externalId:Z.fromSignalingParticipant(r,!0,!0),mediaSettings:D(r.mediaSettings),state:r.state,participantState:M.mapParticipantState(r),roles:r.roles||[],muteStates:r.muteStates||{},movieShareInfos:r.movieShareInfos,unmuteOptions:r.unmuteOptions||[],observedIds:r.observedIds||[],connectionStatus:this._buildConnectionStatus(t,r.sessionState,this._transport?.getState(),r.onHold),markers:this._denormalizeMarkers(t,r.markers),isOnHold:!!r.onHold},i),n=this._getParticipant(t)}this._conversation&&this._conversation.direction===Ga.OUTGOING&&(this._state===`IDLE`||this._state===`PROCESSING`)&&(this._state=`ACTIVE`,this._changeFeatureSet()),n.state=X.ACCEPTED,n.mediaSettings=D(e.mediaSettings),n.participantState=M.mapParticipantState(e.participant),n.roles=e.participant.roles||[],this._updateParticipantSessionState(n,t,e.participant.sessionState),e.participant.onHold?(n.isOnHold=!0,this._setParticipantsStatus([n],P.ONHOLD)):this._transport?.isAllocated(n.id)?this._setParticipantsStatus([n],P.CONNECTED):this._setParticipantsStatus([n],P.WAITING),r&&this._emitParticipantEffectiveStatusIfSessionOverridesTransport(n),this._state!==`IDLE`&&this._transport&&(this._transport.isAllocated(n.id)||this._allocateParticipantTransport(n.id,!0),this._transport.open([n.id],null,!!this._conversation?.observer)),R.onParticipantJoined(n.externalId,n.markers,this.id),this._changeRemoteMediaSettings(t,n.mediaSettings),await this._changeRemoteParticipantState(t,n.participantState),this._invokeRolesChangedCallbackIfNeeded(n);let i=Object.keys(n.muteStates);i.length&&this._onMuteParticipant({muteStates:n.muteStates,mediaOptions:i,stateUpdated:!0,participantId:t}),this._processSharedMovieInfos(n.movieShareInfos)}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new k(e.reason,{remote:!0,callError:e.callError}))}_onMediaSettingsChanged(e){let t=M.composeMessageId(e);this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,D(e.mediaSettings))}async _onParticipantStateChanged(e){let t=M.composeMessageId(e),n=M.mapParticipantState(e);this._isMe(t)?this._changeLocalParticipantState(n):(this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),await this._changeRemoteParticipantState(t,n))}_onParticipantsStateChanged(e){let{participants:t,roomId:n}=e;t.map(({id:e,markers:t})=>this._registerParticipantAndSetMarkersIfChunkEnabled(e,t));let r=new Map,i=t.map(({id:e,participantState:t})=>[e,this._getExternalIdByParticipantId(e)?M.mapParticipantState({participantState:t}):void 0]);try{i.forEach(([e,t])=>{t&&r.set(e,t)}),this._changeMultipleParticipantState(r,n)}catch(e){this._debug.warn(`_onParticipantsStateChanged: Failed to get external ids. ${e}`)}}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),R.onMultipartyChatCreated(this._conversation))}async _onForceMediaSettingsChange(e){if(!this._mediaSource||this._state===`HELD`)return;let t=this._mediaSource.mediaSettings,n=D(e.mediaSettings);t.isAudioEnabled!==n.isAudioEnabled&&await this._mediaSource.toggleAudio(n.isAudioEnabled),t.isVideoEnabled!==n.isVideoEnabled&&await this._mediaSource.toggleVideo(n.isVideoEnabled),t.isScreenSharingEnabled!==n.isScreenSharingEnabled&&await this._mediaSource.toggleScreenCapturing({captureScreen:n.isScreenSharingEnabled,fastScreenSharing:n.isFastScreenSharingEnabled,captureAudio:n.isAudioSharingEnabled})}_onSettingsUpdate(e){this._debug.debug(`Got settings update notification`,e);let t={camera:e.camera,screenSharing:e.screenSharing,fastScreenSharing:e.fastScreenSharing};this._serverSettings=Mr(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){this._debug.debug(`Got video quality update notification`,e);let t={maxBitrateK:Math.round(e.quality.maxBitrate/1024),maxDimension:e.quality.maxDimension},n;n=e.mediaType&&e.mediaType===H.SCREEN?{camera:null,screenSharing:null,fastScreenSharing:Object.assign({},this._serverSettings.fastScreenSharing,t)}:{camera:Object.assign({},this._serverSettings.camera,t),screenSharing:null,fastScreenSharing:null},this._serverSettings=Mr(this._serverSettings,n),this._transport&&this._transport.updateSettings(this._serverSettings)}async _onPeerRegistered(e){this._registeredPeerReceived=!0,this._clearCalleeUnavailableWatchdog();let t=M.composeMessageId(e),n=this._getParticipant(t);n&&(n.clientType=e.clientType,n.platform=e.platform,R.onPeerRegistered(this.id,[n.externalId]))}async _onMicSwitched(e){R.onDeviceSwitched(S.AUDIO,!e.mute,this.id),await this.toggleLocalAudio(!e.mute)}_onChatMessage(e){let t=M.composeMessageId(e),n=this._getExternalIdByParticipantId(t);if(!n){this._warnParticipantNotInConversation(t);return}R.onChatMessage(e.message,n,e.direct,this.id)}_onCustomData(e){if(Object.hasOwn(e.data,`sdk`))return;let t=M.composeMessageId(e),n=this._getExternalIdByParticipantId(t);if(!n){this._warnParticipantNotInConversation(t);return}R.onCustomData(e.data,n,e.direct,this.id)}_onRecordInfo(e,t=null){if(!this._conversation||!e)return;let n=this._conversation.recordsInfoByRoom.get(t);if(n?.recordMovieId!==e?.recordMovieId||n?.recordStartTime!==e?.recordStartTime){this._conversation.recordsInfoByRoom.set(t,e);let n=this._getExternalIdByParticipantId(e.initiator);n?R.onRecordStarted(n,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId,t,this.id):this._warnParticipantNotInConversation(e.initiator)}}_onStopRecordInfo({participant:e,recordMovieId:t},n=null){if(!this._conversation)return;let r=this._conversation.recordsInfoByRoom.get(n);if(!(!r||r.recordMovieId!==t))if(this._conversation.recordsInfoByRoom.set(n,null),e){let t=this._getExternalIdByParticipantId(e);R.onRecordStopped(n,t??null,this.id)}else R.onRecordStopped(n,null,this.id)}_changePinnedParticipantForRoom(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.pinnedParticipantIdByRoom.get(e);if(t&&!this._isMe(t)){let n=this._getExternalIdByParticipantId(t);n&&R.onPinnedParticipant(n,!1,null,e,this.id)}}_changeRecordInfoForRoom(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.recordsInfoByRoom.get(e);if(t){let n=this._getExternalIdByParticipantId(t.initiator);n?R.onRecordStarted(n,t.recordMovieId,t.recordStartTime,t.recordType,t.recordExternalMovieId,t.recordExternalOwnerId,e,this.id):this._warnParticipantNotInConversation(t.initiator)}else R.onRecordStopped(e,null,this.id)}_changeAsrInfoForRoom(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.asrInfoByRoom.get(e);if(t){let n=this._getExternalIdByParticipantId(t.initiatorId);n&&R.onAsrSet({externalId:n,movieId:t.movieId},e,this.id)}else R.onAsrSet(null,e,this.id)}_changeUrlSharingInfoForRoom(){if(!this._conversation)return;let{roomId:e}=this._conversation,{urlSharingInfoByRoom:t}=this._conversation,n=t.get(e);if(n){let t=this._getExternalIdByParticipantId(n.initiatorId);t&&R.onRemoteSharedUrl(t,n.sharedUrl,e,this.id)}}_onParticipantAnimojiChanged(e){if(this._conversation){let t=this._getExternalIdByParticipantId(e.participantId);if(!t){this._warnParticipantNotInConversation(e.participantId);return}R.onParticipantVmojiUpdate(t,this.id)}}_onAsrStart(e){if(!this._conversation)return;let t=e.asrInfo,n=e.roomId||null;this._conversation.asrInfoByRoom.set(n,t);let r=this._getExternalIdByParticipantId(t.initiatorId);if(!r){this._warnParticipantNotInConversation(t.initiatorId);return}R.onAsrStarted(r,t.movieId,n,this.id)}_onAsrStop(e){if(!this._conversation)return;let t=e.roomId||null;t===null&&(this._conversation.asrInfo=null),this._conversation.asrInfoByRoom.delete(t),R.onAsrStopped(t,this.id)}_onAsrTranscription(e){if(!this._conversation)return;let t=this._getExternalIdByParticipantId(e.participantId);if(!t){this._warnParticipantNotInConversation(e.participantId);return}R.onAsrTranscription(t,e.text,e.timestamp,e.duration,this.id)}async _onRolesChanged(e,t){if(this._conversation&&this._isMe(e)&&!ro(this._conversation.roles,t)){this._debug.debug(`Local roles changed: ${t}`),this._conversation.roles=t,R.onLocalRolesChanged(t,!1,this.id),this._processMuteState({mediaOptions:lo(this._getMuteStatesForCurrentRoom(),Qa.MUTE_PERMANENT),stateUpdated:!0}),M.includesOneOf(t,[no.ADMIN,no.CREATOR])?this._refreshRooms(!0):t.length||this._onRoomSwitched(null);return}let n=this._getParticipant(e);n&&!ro(n.roles,t)&&(this._debug.debug(`Roles for participant [${e}] changed: ${t}`),n.roles=t,R.onRolesChanged(n.externalId,t,!1,this.id))}async _onMuteParticipant(e,t=!1){if(!this._conversation)return;let{muteAll:n,muteStates:r={},unmuteOptions:i=[],mediaOptions:a=[],roomId:o=null}=e;if(e.participantId&&!this._isMe(e.participantId)){if(!this._isCallAdmin()){this._debug.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let t=this._getParticipant(e.participantId);if(t){this._debug.debug(`Mute states for participant [${e.participantId}] changed`,r);let o=e.adminId?this._getExternalIdByParticipantId(e.adminId):null;R.onMuteStates(r,i,a,n,e.unmute,t.externalId,o,e.stateUpdated,e.requestedMedia,e.roomId,this.id)}return}if(e.requestedMedia?.length||(n&&!t?this._setMuteStatesForRoomId(r,o):n||(this._conversation.muteStatesPersonal=r)),e.adminId&&this._isMe(e.adminId)){n&&R.onMuteStates(r,i,a,n,e.unmute,null,this._conversation.externalId,e.stateUpdated,e.requestedMedia,e.roomId,this.id);return}await this._processMuteState({mediaOptions:a,muteAll:n,unmute:e.unmute,adminId:e.adminId,stateUpdated:e.stateUpdated,requestedMedia:e.requestedMedia,roomId:e.roomId,unmuteOptions:i,muteStates:r})}_changeMuteStatesForRoom(e,t){if(!this._conversation)return;let n=this._getMuteStatesForRoomId(t),r=this._getMuteStatesForRoomId(e),i=Object.keys(n),a=Object.keys(r);this._processMuteState({mediaOptions:Array.from(new Set([...i,...a])),roomId:e,muteAll:!0,stateUpdated:!0})}async _processMuteState(e){if(!this._conversation||!this._mediaSource||this._participantState!==X.ACCEPTED)return;let{mediaOptions:t=[],muteAll:n,unmute:r,stateUpdated:i,requestedMedia:a,roomId:o=null,unmuteOptions:s=[]}=e,c=e.adminId?this._getExternalIdByParticipantId(e.adminId):null,l=Object.assign({},e.muteStates??this._getMuteStatesForRoomId(o)),u=this._mediaSource.mediaSettings,d=Object.entries(l);for(let[e,i]of d){let a=this._isCallAdmin()&&n;if(!(i!==Qa.MUTE&&i!==Qa.MUTE_PERMANENT||a)&&(this._isCallAdmin()&&i===Qa.MUTE_PERMANENT&&!n&&(l[e]=Qa.MUTE),!(!t.includes(e)||r)))switch(e){case S.VIDEO:u.isVideoEnabled&&(R.onDeviceSwitched(S.VIDEO,!1,this.id),await this.toggleLocalVideo(!1));break;case S.AUDIO:u.isAudioEnabled&&(R.onDeviceSwitched(S.AUDIO,!1,this.id),await this.toggleLocalAudio(!1));break;case S.SCREEN_SHARING:u.isScreenSharingEnabled&&(R.onDeviceSwitched(S.SCREEN_SHARING,!1,this.id),await this.disableScreenCapturing());break;case S.AUDIO_SHARING:u.isAudioSharingEnabled&&(R.onDeviceSwitched(S.AUDIO_SHARING,!1,this.id),await this.toggleScreenCapturing({captureScreen:u.isScreenSharingEnabled,fastScreenSharing:u.isFastScreenSharingEnabled,captureAudio:!1}));break}}R.onMuteStates(l,s,t,n,r,null,c,i,a,o,this.id)}_onPinParticipant(e,t=!1,n,r=null){if(!this._conversation)return;let i=this._conversation.pinnedParticipantIdByRoom.get(r);if(i&&i!==e)if(this._isMe(i))R.onLocalPin(!0,r,this.id);else{let t=this._getExternalIdByParticipantId(i);t&&R.onPinnedParticipant(t,!0,this._denormalizeMarkers(e,n),r,this.id)}if(this._isMe(e))R.onLocalPin(t,r,this.id);else{let i=this._getExternalIdByParticipantId(e);i&&R.onPinnedParticipant(i,t,this._denormalizeMarkers(e,n),r,this.id)}this._conversation.pinnedParticipantIdByRoom.set(r,t?null:e)}_onOptionsChanged(e){this._conversation&&!Xa(this._conversation.options,e)&&(this._conversation.options=e,R.onOptionsChanged(e,this.id),e.includes(Ya.ADMIN_IS_HERE)?this._conversation.restricted&&this._conversation.waitingHall&&R.onLocalStatus(P.WAITING_HALL,this.id):e.includes(Ya.WAIT_FOR_ADMIN)&&this._conversation.restricted&&R.onLocalStatus(P.WAIT_FOR_ADMIN,this.id))}async _onNetworkStatus(e){if(this._conversation){let t=[],n=this._participants;for(let[r,i]of Object.entries(e)){let e;if(this._isMe(r)||r===``)e=this._conversation.networkRating;else if(n[r])e=n[r].networkRating;else continue;if(e!==i)if(this._isMe(r)||r===``)this._conversation.networkRating=i,ti.getInstance().value=i,R.onLocalNetworkStatusChanged(i,this.id);else{let e=n[r];e.networkRating=i,t.push({uid:e.externalId,rating:i})}}if(t.length===0)return;this._debug.log(`Received network status update: `,e),R.onNetworkStatusChanged(t,this.id)}}async _emitHeldParticipantsStatus(){let e=Object.values(this._participants).filter(e=>e.isOnHold).map(e=>e.externalId);e.length&&R.onRemoteStatus(e,P.ONHOLD,null,this.id)}async _onRemoteStreamSecond(e,t){let n=this._getParticipant(e);n&&R.onRemoteScreenStream(n.externalId,t,this.id)}async _onAnimojiStream(e,t){if(this._isMe(e)&&this._mediaSource){R.onVmojiStream(t,this._mediaSource.mediaSettings,this.id);return}let n=this._getParticipant(e);n&&R.onRemoteVmojiStream(n.externalId,t,this.id)}_onAnimojiError(e){try{let t=this._getExternalIdByParticipantId(e.participantId);t&&(delete e.participantId,R.onVmojiError({...e,externalId:t},this.id))}catch(e){this._debug.warn(`_onAnimojiError failed`,e)}}_onPeerConnectionClosed(e){this._state!==`HELD`&&(e===J.SERVER&&this._cleanupParticipantAgnosticStreams(),this._audioOutput.destroy())}_changeFeatureSet(){if(this._conversation){let e=this._state===`ACTIVE`,t=this._conversation.features.includes(Ja.ADD_PARTICIPANT);R.onCallState(e,t,this._conversation,this.id)}}_changeFeaturesPerRole(){this._conversation&&R.onFeaturesPerRoleChanged(this._conversation.featuresPerRole??{},this.id)}_changeNeedRate(){this._conversation&&this._conversation.needRate&&R.onRateNeeded(this.id)}async _onVolumesDetected(e){let t=[];for(let[n,r]of Object.entries(e)){let e=this._getParticipant(n);e&&e.externalId&&t.push({uid:e.externalId,volume:r.real})}R.onVolumesDetected(t,this.id)}async _onSpeakerChanged(e){let t=this._activeSpeakerId;if(this._activeSpeakerId=e,t&&t!==e){let e=this._getParticipant(t);if(e?.connectionStatus.sessionStateConnectedBySpeaker){e.connectionStatus.sessionStateConnectedBySpeaker=!1;let t=this._setTransportStatus(e,e.connectionStatus.transport);this._emitParticipantTransition(e,t)}}let n=this._getParticipant(e);if(n){if(n.connectionStatus.sessionStateApplicable&&n.connectionStatus.sessionState?.connected===!1){let e=ao.fromTransportState(this._transport?.getState());e&&this._setTransportStatus(n,e),n.connectionStatus.sessionStateConnectedBySpeaker=!0;let t=this._setTransportStatus(n,n.connectionStatus.transport);this._emitParticipantTransition(n,t)}this._lastSignalledActiveSpeakerId!==e&&(R.onSpeakerChanged(n.externalId,this.id),this._lastSignalledActiveSpeakerId=e)}}async _onTransportStateChanged(e,t){this._debug.debug(`Transport state has changed: ${t}`,e);let n=ao.fromTransportState(t);if(!n)return;let r=this._participants,i=[],a=e.reduce((e,n)=>{if(n in r){let a=r[n];e.push(a),t===q.CONNECTED&&(a.remoteStream||(a.mediaSettings&&this._changeRemoteMediaSettings(n,a.mediaSettings),this._changeRemoteParticipantState(n,a.participantState)),i.push(...Object.values(a.lastRequestedLayouts)))}else this._warnParticipantNotInConversation(n);return e},[]);a.length&&(this._updateDisplayLayoutFromCache(i),this._setParticipantsStatus(a,n))}async _onTransportLocalStateChanged(e){if(this._debug.debug(`Local transport state has changed: ${e}`),e===q.CONNECTED&&(E.releaseFirefoxMicrophonePermissionWarmup(),R.onLocalStatus(P.CONNECTED,this.id),this._transport?.getTopology()===J.SERVER)){let e=Object.values(this._myLastRequestedLayouts);await this.updateDisplayLayout(e),this._displayLayoutRequester.resend()}this._state!==`HELD`&&((e===q.CONNECTING||e===q.RECONNECTING)&&this._areTransportParticipantsOnHold()||(e===q.CONNECTING&&R.onLocalStatus(P.CONNECTING,this.id),e===q.RECONNECTING&&R.onLocalStatus(P.RECONNECT,this.id),e===q.FAILED&&this._transport&&this._transport.allocated().length===0&&this._close(new k(O.FAILED,{callError:{scope:`network`,source:`rtc`,code:`connection-failed`,description:`transport-failed`}}),{errorText:`Transport failed`,signalingReason:O.FAILED})))}_areTransportParticipantsOnHold(){if(!N.hold||!this._transport)return!1;let e=this._transport.opened().length?this._transport.opened():this._transport.allocated();if(!e.length)return!1;let t=this._participants;return e.every(e=>t[e]?.isOnHold)}_onRemoteTrackAdded(e,t,n){if(e.endsWith(Zr.AUDIO_MIX))this._debug.debug(`Remote audio mix track added`),this._audioOutput.add(e,n),R.onRemoteMixedAudioStream(t,this.id);else if(e.startsWith(Zr.TRANSPARENT_AUDIO_TRACK_PREFIX))this._debug.debug(`Remote transparent audio track added: ${e}`),this._audioOutput.add(e,n);else if(e.startsWith(Zr.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))this._debug.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{this._debug.debug(`Remote track added on the participant [${e}]`,{kind:n.kind});let r=this._getParticipant(e);if(!r){let t=this._api.getDecorativeIdByInitialId(e);this._debug.warn(`Conversation: track added before participant [id: ${e}, decorativeId: ${t}]`),this._registerParticipant({id:e},t),r=this._getParticipant(e),this._setParticipantsStatus([r],P.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(R.onSpeakerChanged(r.externalId,this.id),this._lastSignalledActiveSpeakerId=e)}if(this._transport&&!this._transport.isAllocated(r.id)&&this._allocateParticipantTransport(r.id,!1),n.kind===A.audio&&(this._audioOutput.add(e,n),N.preserveAudioTracks||(r.remoteAudioTrack=n,t.removeTrack(n))),r.remoteStream!==t&&t.getTracks().length){if(r.remoteStream=t,r.secondStream)return;R.onRemoteStream(r.externalId,t,this.id)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings)}}_onRemoteTrackRemoved(e,t,n){switch(this._debug.debug(`[${e}] remote track (removed)`,{track:n}),n.kind){case A.audio:this._removeAudioTrack(e,t,n);break;case A.video:case A.screen:this._removeVideoTrack(e,t,n);break}}async _removeAudioTrack(e,t,n){if(e!==Zr.AUDIO_MIX){let n=this._getParticipant(e);if(!n||n.remoteStream&&n.remoteStream!==t)return}this._audioOutput.remove(e,n)}_removeVideoTrack(e,t,n){}_onTopologyChanged(e){if(this._state===`HELD`){this._conversation&&(this._conversation.topology=e);return}if(this._statFirstMediaReceived.markTopologyChanged(e),e===J.DIRECT&&(this._onRemoteSignalledStall([]),this._onAudioMixStall(!1)),this._conversation){this._conversation.topology=e;for(let e of Object.values(this._participants)){let t=ao.setSessionStateApplicable(e.connectionStatus,this._isParticipantSessionStateApplicable(e.id));this._emitParticipantTransition(e,t)}this._changeFeatureSet(),this._forceOpenTransportForAloneInCall()}this._audioOutput.destroy()}_onAudioMixStall(e){this._audioMixStalled!==e&&!this.isCallHeld&&(this._audioMixStalled=e,this._debug.debug(`Audio mix stalled:`,e),R.onLocalStatus(e?P.RECONNECT:P.CONNECTED,this.id))}_onRemoteSignalledStall(e){let t={},n=[],r=[];this._debug.debug(`Participants stalled:`,e);let i=this._participants;for(let r of e){t[r]=!0;let e=i[r];e&&n.push(e),delete this._lastStalled[r]}for(let e of Object.keys(this._lastStalled)){let t=i[e];t&&r.push(t)}n.length&&this._setParticipantsStalled(n,!0),r.length&&this._setParticipantsStalled(r,!1),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps),this._fixVideoDevice(e.outbound.rtps)}_fixAudioDevice(e){!E.hasMicrophone()||!this._audioFix||!this.mediaSettings?.isAudioEnabled||this._audioFix.fix(e)}_fixVideoDevice(e){!E.hasCamera()||!this._audioFix||!this.mediaSettings?.isVideoEnabled||this._audioFix.fixVideo(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!==`CLOSE`||!1;e&&(this._debug.debug(`Toggle join availability`,{available:t,chatId:e}),R.onJoinStatus(t,e,this.id))}async _updateDisplayLayoutFromCache(e){if(this._transport?.getTopology()===J.SERVER&&e.length)try{await this.updateDisplayLayout(e)}catch(e){this._debug.warn(`_updateDisplayLayoutFromCache failed: ${e}`)}}_setParticipantsStatus(e,t,n=null){this._updateParticipantsStatus(e,e=>e.isOnHold&&![P.ONHOLD,P.HANGUP,P.ERROR].includes(t)?null:this._setTransportStatus(e,t),n)}_setParticipantsStalled(e,t){this._updateParticipantsStatus(e,e=>ao.setStalled(e.connectionStatus,t))}_updateParticipantsStatus(e,t,n=null){let r=e.reduce((e,n)=>{let r=t(n);if(r?.shouldNotify){var i;(e[i=r.status]??(e[i]=[])).push(n.externalId)}return e},{});for(let[e,t]of Object.entries(r))R.onRemoteStatus(t,e,n,this.id)}_onJoinLinkChanged(e){this._conversation&&e.joinLink&&(this._conversation.joinLink=e.joinLink),R.onJoinLinkChanged(e.joinLink,this.id)}_onRoomsUpdated(e){if(this._isCalledState())return;let t={},n=[],r=[];for(let i of Object.keys($a)){let a=e.updates[i];a&&(a?.rooms?.forEach(e=>{let{room:t,missingParticipantIds:i}=this._convertRoomToExternal(e);t&&n.push(t),r.push(...i)}),t[i]={rooms:n,roomIds:a?.roomIds,deactivated:a?.deactivated})}this._reportMissingExternalIds(r,`ROOMS_UPDATED`),R.onRoomsUpdated(t,this.id)}_onRoomUpdated(e){let{room:t,missingParticipantIds:n}=this._convertRoomToExternal(e.room||null);e.events.some(e=>e===$a.UPDATE)&&(e.muteStates!==void 0&&this._setMuteStatesForRoomId(e.muteStates,e.roomId),e.recordInfo!==void 0&&this._conversation?.recordsInfoByRoom.set(e.roomId,e.recordInfo),e.asrInfo!==void 0&&this._conversation?.asrInfoByRoom.set(e.roomId,e.asrInfo)),this._isCalledState()||(this._reportMissingExternalIds(n,`ROOM_UPDATED`),R.onRoomUpdated(e.events,e.roomId,t,e.deactivate||null,this.id))}_convertRoomToExternal(e){if(!e)return{room:null,missingParticipantIds:[]};let t=[],{externalIds:n,missingIds:r}=this._getExternalIdsByParticipantIds(e.participantIds??[]),{externalIds:i,missingIds:a}=this._getExternalIdsByParticipantIds(e.addParticipantIds??[]),{externalIds:o,missingIds:s}=this._getExternalIdsByParticipantIds(e.removeParticipantIds??[]);t.push(...r,...a,...s);let c;if(e.pinnedParticipantId){let n=this._getExternalIdByParticipantId(e.pinnedParticipantId);n?c=n:t.push(e.pinnedParticipantId)}return{room:{id:e.id,name:e.name,participantCount:e.participantCount,participantIds:n,addParticipantIds:i,removeParticipantIds:o,participants:e.participants?.participants?this._participantListChunkToExternalChunk(e.participants):void 0,active:e.active,muteStates:e.muteStates,pinnedParticipantId:c,countdownSec:e.countdownSec,timeoutMs:e.timeoutMs},missingParticipantIds:t}}async _onRoomParticipantsUpdated(e){let t=this._transport?.getState(),n=e.roomId??null,r=[],{externalIds:i,missingIds:a}=this._getExternalIdsByParticipantIds(e.addedParticipantIds??[]);r.push(...a);let o=e.addedParticipants;if(i.length&&o?.length!==i.length&&!this._isCalledState()){let e=this._convertExternalIdsToServerExternalIds(i);o=(await this._signaling.getParticipants(e)).participants}let s=o?.map(e=>{let r=M.composeId(e);return this._createParticipant({id:r,externalId:Z.fromSignalingParticipant(e,!0,!0),mediaSettings:D(e.mediaSettings),participantState:M.mapParticipantState(e),state:e.state,roles:e.roles||[],connectionStatus:this._buildConnectionStatus(r,e.sessionState,t,e.onHold),isOnHold:!!e.onHold,muteStates:e.muteStates||{},unmuteOptions:e.unmuteOptions||[],observedIds:e.observedIds||[],markers:this._denormalizeMarkers(r,e.markers),isInRoom:n!==null},M.composeDecorativeId(e))})||[],c=!1;for(let e of s)e.id===this._conversation?.compositeUserId&&(c=!0),this._registerParticipantInCache(e);this._transport?.getState()===q.IDLE&&!this._isCalledState()&&this._openTransport(s,!0);let l=[];if(e?.removedParticipantMarkers){for(let t of e.removedParticipantMarkers)if(t.GRID?.id){let e=this._getExternalIdByParticipantId(t.GRID.id);e?l.push(e):r.push(t.GRID.id)}}if(this._reportMissingExternalIds(r,`ROOM_PARTICIPANTS_UPDATED`),c&&await this._onRoomSwitched(n),l){let e=this._conversation?.pinnedParticipantIdByRoom.get(n);if(e){let t=this._getExternalIdByParticipantId(e);if(t){for(let e of l)if(Z.compare(t,e)){this._conversation?.pinnedParticipantIdByRoom.delete(n);break}}}}let u={roomId:n,participantCount:e.participantCount,addedParticipantIds:i,addedParticipants:M.mapSharedParticipants(s),removedParticipantMarkers:e?.removedParticipantMarkers,removedParticipantIds:l};this._isCalledState()||R.onRoomParticipantsUpdated(u,this.id)}async _onRoomSwitched(e,t=!1){if(!this._conversation||this._conversation.roomId===e)return;let n=this._conversation.roomId;if(this._conversation.roomId=e,t&&!this._isCalledState()){R.onRoomStart(e,this.id);return}this._isCalledState()||R.onRoomSwitched(e,this.id),e!==null&&!this._isCallAdmin()&&await this._refreshRooms(!1),this._changePinnedParticipantForRoom(),this._changeRecordInfoForRoom(),this._changeMuteStatesForRoom(e,n),this._changeAsrInfoForRoom(),this._changeUrlSharingInfoForRoom()}async _refreshRooms(e){let t;this._isCalledState()||(t=await this._signaling.getRooms(e));let n=t?.rooms?.rooms??[],r=[];for(let t of n){let n=t.id??null;if(this._setMuteStatesForRoomId(t.muteStates,n),this._conversation?.recordsInfoByRoom.set(n,t.recordInfo??null),this._conversation?.pinnedParticipantIdByRoom.set(n,t.pinnedParticipantId??null),t.asrInfo&&this._conversation?.asrInfoByRoom.set(n,t.asrInfo),t.urlSharingInfo?this._conversation?.urlSharingInfoByRoom.set(n,t.urlSharingInfo):this._conversation?.urlSharingInfoByRoom.delete(n),e){let e=this._participants;await this._registerParticipants(t?.participants?.participants?.filter(t=>!e[M.composeId(t)])||[],!0);let{room:n}=this._convertRoomToExternal(t);n&&r.push(n)}}r.length&&!this._isCalledState()&&R.onRoomsUpdated({[$a.UPDATE]:{rooms:r}},this.id)}_onFeedback(e){let t=[];for(let n of e.feedback){let e={...n,items:[]};for(let t of n.items){let n=this._getExternalIdByParticipantId(t.participantId);n?e.items.push({...t,participantId:n}):this._warnParticipantNotInConversation(t.participantId)}t.push(e)}R.onFeedback(t,e.roomId,this.id)}_onDecorativeParticipantIdChanged(e){if(!this._conversation||!e.decorativeParticipantId||!e.decorativeExternalParticipantId)return;let{participantId:t,decorativeParticipantId:n,decorativeExternalParticipantId:r}=e,i=this._isMe(t);this._debug.debug(`Decorative participant id changed [${t}]`,e);let a=this._getExternalIdByParticipantId(t);if(!a){this._warnParticipantNotInConversation(t);return}let o=Z.fromSignaling(r,a.deviceIdx);R.onParticipantIdChanged(a,o,this.id);let s=M.compose(n,a.deviceIdx),c=M.compose(t,a.deviceIdx);if(this._api.cacheExternalId(s,o),this._api.mapDecorativeId(s,c),i)this._conversation.externalId=o;else{let e=this._participants;e[t].externalId=o}}_onVideoSuspendSuggest(e){!this._conversation||this._conversation.topology!==J.SERVER||(this._debug.debug(`Video suspend suggested`,e),R.onVideoSuspendSuggest(e.bandwidth,this.id))}async _onParticipantHold(e){this._debug.debug(`Participant hold suggested`,e);let t=this._getParticipant(e.participantId);if(!t){this._warnParticipantNotInConversation(e.participantId);return}if(t.isOnHold=e.hold,this._specListener?.onParticipantHoldChanged(),this._transport?.setRemoteHold(e.hold),e.hold)this._setParticipantsStatus([t],P.ONHOLD);else{let e=this._transport?.getTopology()===J.DIRECT?P.CONNECTING:P.CONNECTED;this._setParticipantsStatus([t],e)}}_isMe(e){return e===this._conversation?.compositeUserId}_getMuteStatesForRoomId(e=null){return this._conversation?.muteStates.get(e)??{}}_getMuteStatesForCurrentRoom(){return this._getMuteStatesForRoomId(this._conversation?.roomId)}_setMuteStatesForRoomId(e={},t=null){this._conversation?.muteStates.set(t,e)}_forceOpenTransportForAloneInCall(){this._transport?.getTopology()===J.SERVER&&this._transport?.getState()===q.IDLE&&!this._isCalledState()&&this._transport.open(this._transport.allocated(),null,!!this._conversation?.observer,!0)}_registerParticipant(e,t){let n=this._createParticipant(e,t);this._registerParticipantInCache(n)}_getParticipant(e){return this._participants[e]}},nc=null,rc=class e extends Error{constructor(t,n){super(t),h(this,`participantErrors`,void 0),Object.setPrototypeOf(this,e.prototype),this.participantErrors=n}},ic=class{constructor(){h(this,`_abortSignal`,void 0)}setAbortSignal(e){this._abortSignal=e}async createJoinLink(e){return{join_link:`nop`}}async removeJoinLink(e){return{success:!0}}async getAnonymTokenByLink(e,t){return``}log(e){}logClientStats(e){return Promise.resolve()}logClientStatsWith(e,t){return Promise.resolve()}getCachedParticipantIdByExternalId(e){return null}getCachedExternalIdByParticipantId(e){return null}cacheExternalId(e,t){}mapDecorativeId(e,t){}unmapDecorativeId(e){}getDecorativeIdByInitialId(e){}hangupConversation(e,t=O.HUNGUP,n){}async removeHistoryRecords(e){}async getServerTime(){return Date.now()}cleanup(){}async getInbounds(){return[]}},ac=class e{constructor(){h(this,`_participantIdToExternalId`,new Map),h(this,`_externalIdToParticipantId`,new Map),h(this,`_decorativeIdToInitialId`,new Map),h(this,`_initialIdToDecorativeId`,new Map)}static _normalizeType(e){return e.type===oo.GROUP?{...e,type:oo.USER}:e}getExternalId(e){let t=this._initialIdToDecorativeId.get(e)??e,n=this._participantIdToExternalId.get(t);return n==null?null:Z.fromString(n)}getParticipantId(t){let n=Z.toString(e._normalizeType(t)),r=this._externalIdToParticipantId.get(n);return r==null?null:this._decorativeIdToInitialId.get(r)??r}cache(t,n){let r=e._normalizeType(n),i=Z.toString(r);this._participantIdToExternalId.set(t,i),this._externalIdToParticipantId.set(i,t)}mapDecorativeId(e,t){this._decorativeIdToInitialId.set(e,t),this._initialIdToDecorativeId.set(t,e)}unmapDecorativeId(e){let t=this._initialIdToDecorativeId.get(e);t&&this._decorativeIdToInitialId.delete(t),this._initialIdToDecorativeId.delete(e)}getDecorativeIdByInitialId(e){return this._initialIdToDecorativeId.get(e)}clear(){this._participantIdToExternalId.clear(),this._externalIdToParticipantId.clear(),this._decorativeIdToInitialId.clear(),this._initialIdToDecorativeId.clear()}},oc=`anonymLogin:`,sc=700,cc=3e3;function lc(e){let t=e.error_code;switch(t){case 2:return uc(O.SERVICE_UNAVAILABLE,t,`service-unavailable`);case 4:return e.error_msg.includes(`participants.limit.exceeded`)?uc(O.PARTICIPANT_LIMIT_REACHED,t,`participants-limit-exceeded`):uc(x.API,t,`request-error`);case 300:return uc(O.NOT_FOUND,t,`not-found`);case 1101:return uc(O.SERVICE_DISABLED,t,`vchat-service-disabled`);case 1102:return uc(O.CALLEE_IS_OFFLINE,t,`target-user-unavailable`);case 1103:return uc(O.NOT_FRIENDS,t,`friendship-required`);case 1104:return dc(t,`youla-api-error`);case 1106:return dc(t,`vk-api-error`);case 1113:return uc(O.CALLER_IS_REJECTED,t,`caller-is-rejected`);case 1114:{let n=e.custom_error?.vchat_detailed_api_error?.code,r=n?.startsWith(`obsolete_client`);return uc(r?O.OBSOLETE_CLIENT:O.VCHAT_DETAILED_ERROR,t,n??`detailed-error`,r?n:void 0)}default:return uc(x.API,t,`api-error`)}}function uc(e,t,n,r){return{type:e,callError:{scope:`server`,source:`api`,code:t,description:n},message:r}}function dc(e,t){return{type:O.EXTERNAL_API_ERROR,callError:{scope:`external`,source:`api`,code:e,description:t}}}var fc=class extends ic{constructor(...e){super(...e),h(this,`_uuid`,void 0),h(this,`_idCache`,new ac)}async _callUnsafe(e,t={},n=!1){let r=async i=>{try{return await as(e,t,n)}catch(t){if(!t||typeof t!=`object`||!Object.hasOwn(t,`error_msg`)){i++;let n=t&&(typeof t==`object`||typeof t==`function`)?Object.getOwnPropertyNames(t).map(e=>`${e}: ${JSON.stringify(t[e])}`):[String(t)];if(z.debug(`${e} network error, attempt ${i}: ${n.join(`
|
|
14
|
-
`)}`),this._abortSignal?.aborted&&(z.debug(`${e} aborted`),this._abortSignal.throwIfAborted()),i<N.apiMaxAttempt)return await M.delay(Math.min(i*sc,cc),{signal:this._abortSignal}),r(i)}throw z.warn(e,`error`,t),t}};return r(0)}async _call(e,t={},n=!1,r=!0){try{return await this._callUnsafe(e,t,n)}catch(i){if(z.warn(`Api call error`,i),i instanceof k)throw i;if(Vo(i?.error_code)&&r)return await this._reauthorize(),this._call(e,t,n,!1);let a={message:i?.error_msg,code:i?.error_code};if(i.custom_error&&(a.custom_error=i.custom_error),pc(i)){let e=lc(i);throw a.callError=e.callError,a.message=e.message??a.message,new k(e.type,a)}throw new k(x.API,a)}}userId(e){if(y.isEmpty()){let{compositeUserId:t}=M.decomposeParticipantId(e),{id:n}=M.decomposeId(t);return Z.fromId(String(n))}return this._idCache.getExternalId(e)}async authorize(){if(this._ensureUuid(),!N.apiKey)throw new k(x.API,{message:`Required argument apiAppKey not passed`,callError:{scope:`internal`,code:`configuration`,description:`api-key-missing`}});let e=this._getCachedAnonymLogin();if(e){this._applyAnonymLogin(e);return}return this._anonymLogin(N.authToken).then(e=>{this._applyAnonymLogin(e),this._setCachedAnonymLogin(e)}).catch(e=>{throw e instanceof k?e:(e?.error_code===Bo.AUTH_LOGIN&&(this._removeCachedAnonymLogin(),R.onTokenExpired()),new k(x.AUTH,{message:e?.error_msg,code:e?.error_code,callError:{scope:`server`,source:`api`,code:e?.error_code??`authentication`,description:`authentication-failed`}}))})}_anonymLogin(e){let t={session_data:{version:2,device_id:this._uuid,client_version:N.apiClientVersion,client_type:`SDK_JS`}};return e&&(t.session_data.auth_token=e,t.session_data.version=3),this._callUnsafe(`auth.anonymLogin`,t,!0)}_getAnonymLoginCacheKey(){return N.authToken?`${oc}${N.authToken}`:null}_getCachedAnonymLogin(){let e=this._getAnonymLoginCacheKey();if(!e)return null;let t=w.get(e);return mc(t)?t:(t&&w.remove(e),null)}_setCachedAnonymLogin(e){let t=this._getAnonymLoginCacheKey();!t||!mc(e)||w.set(t,{session_key:e.session_key,session_secret_key:e.session_secret_key,uid:e.uid})}_removeCachedAnonymLogin(){let e=this._getAnonymLoginCacheKey();e&&w.remove(e)}_reauthorize(){return this._removeCachedAnonymLogin(),y.reauthorize(()=>this.authorize())}_applyAnonymLogin(e){e.uid&&(y.userId=Number(e.uid)),y.sessionKey=e.session_key,y.sessionSecretKey=e.session_secret_key,N.statQueueEnabled&&e.uid&&ps.remember(Number(e.uid),{sessionKey:e.session_key,endpoint:ps.currentEndpoint()})}_buildClientStatsData(e){let t={app_version:N.appVersion,sdk_type:`WEB`,sdk_version:N.sdkVersion,version:1,items:e};return N.clientStatsPlatform&&(t.platform=N.clientStatsPlatform),{data:JSON.stringify(t)}}_reportClientStatsItemErrors(e){e?.items_responses?.forEach(e=>{e.errors&&z.error(`[vchat.clientStats]`,e)})}async _sendClientStatsWith(e,t){let n=await as(`vchat.clientStats`,{...t,session_key:e},!0);this._reportClientStatsItemErrors(n)}async _sendClientStats(e,t,n=!0){try{let n=t?await os(`vchat.clientStats`,e):await as(`vchat.clientStats`,e);this._reportClientStatsItemErrors(n)}catch(r){if(!n||!Vo(r?.error_code))throw r;await this._reauthorize(),await this._sendClientStats(e,t,!1)}}async logClientStats(e){let t=this._buildClientStatsData(e);if(!N.statQueueEnabled){this._sendClientStats(t,!0).catch(e=>z.error(`[vchat.clientStats]`,e));return}await this._sendClientStats(t,!1)}async logClientStatsWith(e,t){await this._sendClientStatsWith(e,this._buildClientStatsData(t))}async uploadDebugLogs(e,t,n,r){let i={conversationId:e,webrtcPlatform:N.platform,startTime:t,endTime:n},a=await this._callUnsafe(`vchat.getLogUploadUrl`,i),o=new FormData,s=new Blob([r],{type:`application/json`});o.append(`file`,s,`log.json`);let c=new URL(a.upload_url);return c.searchParams.append(`size`,s.size.toString()),ls(c.toString(),o)}async joinConversation(e,t=!1,n){let r={conversationId:e,isVideo:t,protocolVersion:N.protocolVersion,capabilities:Ea.getFlags()};return n&&(r.chatId=n),this._call(`vchat.joinConversation`,r)}async createConversation(e,t=``,n=!1,{onlyAdminCanShareMovie:r,audienceMode:i,audioOnly:a,waitForAdmin:o,closedConversation:s}={},c){let l=this._preareStartConversationData({conversationId:e,isVideo:!1,joiningAllowed:!0,payload:t,requireAuthToJoin:n,onlyAdminCanShareMovie:r,waitForAdmin:o,closedConversation:s,audienceMode:i,audioOnly:a,externalIds:c});return this._startConversation(l)}async startConversation(e,t,n,r=!1,i=``,a=!1,o=!1,{onlyAdminCanShareMovie:s,waitForAdmin:c}={},l){let u=this._preareStartConversationData({conversationId:e,isVideo:r,joiningAllowed:a,payload:i,requireAuthToJoin:o,onlyAdminCanShareMovie:s,waitForAdmin:c,externalIds:l});if(t&&t.length)switch(n){case Ka.USER:u.uids=t.join(`,`);break;case Ka.GROUP:u.gid=t[0];break;case Ka.CHAT:u.chatId=t[0];break}return this._startConversation(u)}_ensureUuid(){if(!this._uuid){let e=w.get(`uuid`);e||(e=M.uuid(),w.set(`uuid`,e)),this._uuid=String(e)}}deviceId(){return this._ensureUuid(),this._uuid}_preareStartConversationData({conversationId:e,isVideo:t,payload:n=``,joiningAllowed:r=!1,requireAuthToJoin:i=!1,onlyAdminCanShareMovie:a,waitForAdmin:o,audienceMode:s=!1,audioOnly:c=!1,closedConversation:l=!1,externalIds:u}){let d={conversationId:e,isVideo:t,protocolVersion:N.protocolVersion};return r&&(d.createJoinLink=!0),n&&(d.payload=n),N.domain&&(d.domainId=N.domain),N.externalDomain&&(d.externalDomain=N.externalDomain),i&&(d.requireAuthToJoin=!0),a!==void 0&&(d.onlyAdminCanShareMovie=a),o!==void 0&&(d.waitForAdmin=o),s&&(d.audienceMode=s),c&&(d.audioOnly=c),l&&(d.closed=l),u&&(d.externalIds=u.map(Z.toSignaling).join(`,`)),d}async _startConversation(e){return this._call(`vchat.startConversation`,e)}async createJoinLink(e){return this._call(`vchat.createJoinLink`,{conversationId:e})}async removeJoinLink(e){return this._call(`vchat.removeJoinLink`,{conversationId:e})}async getAnonymTokenByLink(e,t){let n={joinLink:e};t&&(n.anonymName=t);let r=await this._call(`vchat.getAnonymTokenByLink`,n);return y.userId=Number(r.uid),r.token}async joinConversationByLink(e,t=!1,n,r){let i={joinLink:e,isVideo:t,protocolVersion:N.protocolVersion,capabilities:Ea.getFlags()};return n?.length&&(i.observedIds=n.join(`,`)),N.anonymToken&&(i.anonymToken=N.anonymToken),r&&(i.payload=r),this._call(`vchat.joinConversationByLink`,i)}getCachedParticipantIdByExternalId(e){return this._idCache.getParticipantId(e)}getCachedExternalIdByParticipantId(e){return this._idCache.getExternalId(e)}cacheExternalId(e,t){this._idCache.cache(e,t)}mapDecorativeId(e,t){this._idCache.mapDecorativeId(e,t)}unmapDecorativeId(e){this._idCache.unmapDecorativeId(e)}getDecorativeIdByInitialId(e){return this._idCache.getDecorativeIdByInitialId(e)}async getConversationParams(e){let t={};return N.anonymToken&&(t.anonymToken=N.anonymToken),e&&(t.conversationId=e),this._call(`vchat.getConversationParams`,t)}getUserId(){return y.userId}setUserId(e){y.userId=e,N.statQueueEnabled&&y.sessionKey&&ps.remember(Number(e),{sessionKey:y.sessionKey,endpoint:ps.currentEndpoint()})}hangupConversation(e,t=O.HUNGUP,n){let r={conversationId:e,reason:t};N.anonymToken&&(r.anonymToken=N.anonymToken),n?.peerId&&(r.peerId=n.peerId),is(`vchat.hangupConversation`,r)}async removeHistoryRecords(e){await this._call(`vchat.removeHistoryRecords`,{recordIds:e.join(`,`)})}cleanup(){this._idCache.clear()}async getServerTime(){return(N.statQueueEnabled?await this._call(`system.getInfo`,{},!1,!1):await this._call(`system.getInfo`)).serverTime}async getInbounds(){let e=await this._call(`vchat.getInbounds`);return Array.isArray(e?.inbounds)?e.inbounds:[]}};function pc(e){return typeof e==`object`&&!!e&&`error_code`in e&&`error_msg`in e}function mc(e){return typeof e==`object`&&!!e&&`session_key`in e&&`session_secret_key`in e&&typeof e.session_key==`string`&&e.session_key.length>0&&typeof e.session_secret_key==`string`&&e.session_secret_key.length>0}var hc=function(e){return e.KING=`KING`,e.PAWN=`PAWN`,e}(hc||{}),gc=function(e){return e.OFF=`0`,e.ON=`1`,e}({}),_c=class{constructor(e){h(this,`_queue`,void 0),h(this,`_readCursor`,void 0),h(this,`_writeCursor`,void 0),h(this,`_moveReadCursor`,void 0),h(this,`_left`,void 0),this._queue=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),e}},vc=class{constructor(e,t,n,r=null){h(this,`_uuid`,void 0),h(this,`_apiKey`,void 0),h(this,`_callToken`,void 0),h(this,`_apiEnv`,void 0),h(this,`_baseApiUrl`,void 0),h(this,`_sessionKey`,void 0),this._uuid=M.uuid(),this._apiKey=t,this._callToken=n,this._apiEnv=e,this._baseApiUrl=r}async authorize(){let e=await as(`auth.anonymLogin`,{session_data:{device_id:this._uuid,client_version:N.apiClientVersion,client_type:`SDK_JS`,auth_token:this._callToken,version:3},application_key:this._apiKey},!0,await ns(this._baseApiUrl,this._apiEnv));return M.isObject(e)&&!(`error_msg`in e)?(this._sessionKey=e.session_key,!0):!1}async hangupConversation(e,t){let n={conversationId:e,reason:O.HUNGUP,application_key:this._apiKey,session_key:this._sessionKey};t?.peerId&&(n.peerId=t.peerId),await as(`vchat.hangupConversation`,n,!0,await ns(this._baseApiUrl,this._apiEnv))}},yc,bc=null,xc=!1,Sc={getCameras:E.getCameras,getMicrophones:E.getMicrophones,getOutput:E.getOutput,getVideoFacingMode:E.getVideoFacingMode,hasCamera:E.hasCamera,hasMicrophone:E.hasMicrophone,getSavedCamera:E.getSavedCamera,getSavedMicrophone:E.getSavedMicrophone,getSavedOutput:E.getSavedOutput,hasCameraPermission:E.hasCameraPermission,hasMicrophonePermission:E.hasMicrophonePermission,hasPermissions:E.hasPermissions,getUserMedia:E.getUserMedia,getUserVideo:E.getUserVideo,getUserAudio:E.getUserAudio,setResolution:E.setResolution,isBrowserSupported:E.isBrowserSupported,isScreenCapturingSupported:E.isScreenCapturingSupported,os:E.os,isMobile:E.isMobile,browserName:E.browserName,browserVersion:E.browserVersion,baseChromeVersion:E.baseChromeVersion,getAudioContext:E.getAudioContext,isAudioShareSupported:E.isAudioShareSupported},Cc={participantMarkerCompare:M.participantMarkerCompare};function wc(e){bc=e}function Tc(e){N.videoEffects=e}function Ec(e){N.audioEffects=e}function Dc(e,t={}){N.vad=e,N.vadOptions=t}function Oc(e,t=null,n={},r=1){N.vmoji=e,N.vmojiOptions={protocolVersion:r,renderingOptions:n},t&&e.setSDK(t)}async function kc(e){N.set(e),yc||(yc=new fc),N.statQueueEnabled&&(hs.setApi(yc),N.autoStartStats&&Ic()),c.default.disableLog(!N.debug),z.toggle(N.debug),z.log(`Calls SDK ${N.sdkVersion}`,e),await E.init();let t=E.getBrowserSupportFailure();if(t)throw new k(x.UNSUPPORTED,{callError:{scope:`internal`,code:`environment`,description:t}});z.log(`UserAgent:`,navigator.userAgent),z.log(`Screen resolution:`,`${window.screen.width}x${window.screen.height}`),z.log(`Permissions:`,`Camera: ${E.hasCameraPermission()}, Mic: ${E.hasMicrophonePermission()}`),z.log(`Simulcast:`,`${e.simulcast} => ${N.simulcast}`)}async function Ac(e,t=[S.AUDIO],n=``,r=!1,i=!1,a,o,s){let c=[];return Array.isArray(e)?c=e.length?e:[]:e&&(c=[e]),Mc([],Ka.USER,t,n,r,i,a,c,o,s)}function jc(e,t=[]){let n=e.getIncomingCallerExternalId();return n?t.length===1&&t[0].id===n.id&&t[0].type===n.type:!1}async function Mc(e,t=Ka.USER,n,r=``,i=!1,a=!1,o,s,c,l){if(!N.hold&&B.getActive())throw z.error(`There is already active call`),new k(O.HAS_ACTIVE_CALL);let u=B.getAll().find(e=>e.isIncomingRinging);if(!N.hold&&u&&!jc(u,s))throw z.error(`There is already incoming call`),new k(O.HAS_ACTIVE_CALL);return new $(new fc,bc).onStart({opponentIds:e,opponentType:t,mediaOptions:n,payload:r,joiningAllowed:i,requireAuthToJoin:a,onlyAdminCanShareMovie:o,externalIds:s,onFastStart:c,conversationId:l})}async function Nc(e,t){return Pc(e,j.USER,void 0,t)}async function Pc(e,t=j.USER,n,r,i,a){if(e===$.id())throw Error(`Push has already been processed`);return new $(new fc,bc).onPush(e,t,n,r,i,a)}async function Fc(){return yc.getInbounds()}function Ic(){if(N.statQueueEnabled){if(!yc){z.error(`[CallsSDK] startStats() called before init()`);return}xc||(xc=!0,Ts.start(yc))}}async function Lc(e,t){return e&&(N.authToken=e),t!==void 0&&N.apiBaseUrl!==t&&(N.apiBaseUrl=t,es()),yc.authorize()}async function Rc(e=[S.AUDIO],t){return lu(t).accept(e)}async function zc(e){let t=ou(e?.conversationId);if(t)return t.decline(e)}async function Bc(e,t=[S.AUDIO]){return Vc(e,t)}async function Vc(e,t,n){if(!N.hold&&B.callsLength>0)throw z.error(`There is already active call`),new k(O.HAS_ACTIVE_CALL);return new $(new fc,bc).onJoin({conversationId:e,mediaOptions:t,chatId:n})}async function Hc(e,t=[S.AUDIO],n,r,i,a){if(!N.hold&&B.callsLength>0)throw z.error(`There is already active call`),new k(O.HAS_ACTIVE_CALL);return n&&(N.anonymToken=n),new $(new fc,bc).onJoin({joinLink:e,mediaOptions:t,observedIds:r,payload:i,onFastJoin:a,anonymous:!!N.anonymToken})}function Uc(e){let t=ou(e?.conversationId);return t?t.hangup(e):($.hangupAfterInit(e?.onFastHangup),Promise.resolve())}async function Wc(e,t){let n=Array.isArray(e)?e:[e],r=$.current();r&&await r.addParticipant(n,t)}async function Gc(e,t){let n=$.current();if(n){let r=e.map(e=>M.composeUserId(e));await n.addParticipantLegacy(r,t)}}async function Kc(e,t=!1){let n=uu(e,`removeParticipant`);if(n)try{await n.conversation.removeParticipant(M.decomposeParticipantId(n.participantId).compositeUserId,t)}catch(e){z.warn(`Failed to remove participant ${n.participantId}. Perhaps he is no longer on the call. ${e}`)}}async function qc(e,t=!1){let n=$.current();if(n)try{await n.removeParticipant(M.composeUserId(e),t)}catch(t){z.warn(`Failed to remove participant ${e}. Perhaps he is no longer on the call. ${t}`)}}async function Jc(e,t){let n=$.current();if(e===`videoinput`&&Mt.contains(t))return N.videoFacingMode=t,n?(E.isMobile()&&n.stopVideoTrack(),n.changeDevice(e)):void 0;if(!await E._saveDeviceId(e,t))throw Error(`Device not found: ${t}`);if(n)return n.changeDevice(e)}async function Yc(e,t){let n=typeof e==`object`?{...e,fastScreenSharing:e.captureScreen&&e.fastScreenSharing,captureAudio:e.captureScreen&&e.captureAudio&&N.audioShare}:{captureScreen:e,fastScreenSharing:!1,captureAudio:!1},r=ou(t);return r?r.toggleScreenCapturing(n):Promise.reject()}function Xc(e){let t=$.current();t&&t.toggleAnimojiCapturing(e)}async function Zc(e,t=!1){let n=$.current();n&&await n.setVideoStream(e,t)}async function Qc(e,t){let n=ou(t);n&&await n.toggleLocalVideo(e)}async function $c(e,t){let n=ou(t);n&&await n.toggleLocalAudio(e)}async function el(e){let t=$.current();if(t)return t.setLocalResolution(e)}async function tl(e){let t=$.current();t&&await t.changePriorities(e)}async function nl(e,t){let n=$.current();if(n){if(t){let r=n.getCachedParticipantIdByExternalId(t);if(!r){su(t,`changeParticipantState`,n);return}await n.changeParticipantState(e,r);return}await n.changeParticipantState(e)}}async function rl(){let e=$.current();e&&await e.putHandsDown()}async function il(e){let t=$.current();t&&await t.updateDisplayLayout(e)}async function al(e){let t=$.current();t&&await t.requestDisplayLayout(e)}async function ol(e,t,n=!1){let r=uu(e,`grantRoles`);r&&await r.conversation.grantRoles(r.participantId,t,n)}async function sl(e,t,n,r=!1){let i=$.current();i&&await i.grantRoles(M.composeParticipantId(e,j.USER,t),n,r)}async function cl({externalId:e=null,muteStates:t,requestedMedia:n=[],roomId:r=null}){if(e){let i=uu(e,`muteParticipant`);return i?i.conversation.muteParticipant(i.participantId,t,n,r):void 0}let i=$.current();i&&await i.muteParticipant(null,t,n,r)}async function ll({uid:e=null,muteStates:t,requestedMedia:n=[],deviceIdx:r=0,roomId:i=null}){let a=$.current();if(a){let o=e?M.composeParticipantId(e,j.USER,r):null;await a.muteParticipant(o,t,n,i)}}async function ul(e,t=!1,n=null){let r=uu(e,`pinParticipant`);r&&await r.conversation.pinParticipant(r.participantId,t,n)}async function dl(e,t=!1,n=0,r=null){let i=$.current();i&&await i.pinParticipant(M.composeParticipantId(e,j.USER,n),t,r)}async function fl(e){let t=$.current();t&&await t.updateMediaModifiers(e)}async function pl(e){let t=$.current();t&&await t.enableVideoSuspend(e)}async function ml(e){let t=$.current();t&&await t.enableVideoSuspendSuggest(e)}async function hl(e){let t=$.current();t&&await t.changeOptions(e)}async function gl(e,t=null){if(t){let n=uu(t,`chatMessage`);return n?n.conversation.chatMessage(e,M.decomposeParticipantId(n.participantId).compositeUserId):void 0}let n=$.current();n&&await n.chatMessage(e,null)}async function _l(e,t=null){let n=$.current();if(n){let r=t?M.composeUserId(t):null;await n.chatMessage(e,r)}}async function vl(e=10){let t=$.current();if(t)return t.chatHistory(e)}async function yl(e,t=null){if(t){let n=uu(t,`customData`);return n?n.conversation.customData(e,n.participantId):void 0}let n=$.current();n&&await n.customData(e,null)}async function bl(e,t=null,n=0){let r=$.current();if(r){let i=t?M.composeParticipantId(t,j.USER,n):null;await r.customData(e,i)}}async function xl(e=``,t=!1,{onlyAdminCanShareMovie:n=!1,waitForAdmin:r=!1,closedConversation:i=!1}={},a){return(await yc.createConversation(a??M.uuid(),e,t,{onlyAdminCanShareMovie:n,waitForAdmin:r,closedConversation:i})).join_link}async function Sl(e=``,t=!1,{onlyAdminCanShareMovie:n=!1,audioOnly:r=!1}={},i){let a=i.map(e=>Z.fromId(e));return(await yc.createConversation(M.uuid(),e,t,{onlyAdminCanShareMovie:n,audienceMode:!0,audioOnly:r},a)).join_link}async function Cl(){let e=$.current();return e?e.createJoinLink():Promise.reject()}async function wl(){let e=$.current();return e?e.removeJoinLink():Promise.reject()}async function Tl(e,t){return yc.getAnonymTokenByLink(e,t)}function El(e){let t=$.current();t&&t.setVolume(e)}function Dl(e){N.forceRelayPolicy=e}async function Ol(e=!1,t=null,n=null,r=`DIRECT_LINK`,i=null,a=null){let o=$.current();return o?o.startStream(e,t,n,r,i,a):Promise.reject()}async function kl(e=null,t){let n=$.current();return n?n.stopStream(e,t):Promise.reject()}async function Al(e=null){let t=$.current();return t?t.publishStream(e):Promise.reject()}async function jl(){let e=$.current();return e?e.getStreamInfo():Promise.reject()}async function Ml(e){let t=$.current();return t?t.addMovie(e):Promise.reject()}async function Nl(e){let t=$.current();return t?t.updateMovie(e):Promise.reject()}async function Pl(e){let t=$.current();return t?t.removeMovie(e):Promise.reject()}async function Fl(e,t){let n=$.current();if(n){let r=[],i=[];for(let t of e){let e,a;t.addParticipantIds&&(e=[],t.addParticipantIds.forEach(t=>{let r=n.getCachedParticipantIdByExternalId(t);r?e.push(M.decomposeParticipantId(r).compositeUserId):i.push(t.id)})),t.removeParticipantIds&&(a=[],t.removeParticipantIds.forEach(e=>{let t=n.getCachedParticipantIdByExternalId(e);t?a.push(M.decomposeParticipantId(t).compositeUserId):i.push(e.id)})),r.push({id:t.id,name:t.name,participantCount:t.participantCount,addParticipantIds:e,removeParticipantIds:a,countdownSec:t.countdownSec})}if(i.length){cu(i,`updateRooms`,n);return}return n.updateRooms(r,t)}return Promise.reject()}async function Il(e,t){let n=$.current();return n?n.activateRooms(e,t):Promise.reject()}async function Ll(e=null,t=null){let n=$.current();if(!n)return Promise.reject();let r;if(t&&(r=n.getCachedParticipantIdByExternalId(t)??void 0,!r)){su(t,`switchRoom`,n);return}return n.switchRoom(e,r)}async function Rl(e){let t=$.current();return t?t.removeRooms(e):Promise.reject()}function zl(e){N.statisticsInterval=e;let t=$.current();if(t)return t.updateStatisticsInterval()}function Bl(e){c.default.disableLog(!e),z.toggle(e)}function Vl(e,...t){N.debugLog&&($.debugMessage(e,`[external]`,...t)||z.send(e,`[external]`,...t))}function Hl(e,t,...n){N.debugLog&&($.debugMessageWithContext(e,t,`[external]`,...n)||z.send(e,`[external]`,...n))}var Ul={list:Fe,get:Ie,getJson:Le,download:Re,clear:ze,stats:Be};function Wl(){let e=[[`Calls SDK ${N.sdkVersion}`,N.toJSON()],[`UserAgent:`,navigator.userAgent],[`Screen resolution:`,`${window.screen.width}x${window.screen.height}`],[`Permissions:`,`Camera: ${E.hasCameraPermission()}, Mic: ${E.hasMicrophonePermission()}`]],t=new Date,n=t.getTime(),r=t.toLocaleString(`ru-RU`,{dateStyle:`short`,timeStyle:`long`});return e.map(e=>({h:r,t:n,l:Tn.LOG,d:e}))}async function Gl(){let e=$.id(),t=$.debugSessionId();if(!t||!e)throw z.error(`[uploadDebugLogs]`,`No conversation id found`),Error(`No conversation id found`);let n=await Ie({sessionId:t});if(n.length===0)throw z.error(`[uploadDebugLogs]`,`No logs found`),Error(`No logs found`);let r=n[0].t,i=n[n.length-1].t;try{return yc?.uploadDebugLogs(e,r,i,JSON.stringify([...Wl(),...n]))}catch(e){throw z.error(`[uploadDebugLogs]`,`Error while uploading logs`,e),Error(`Error while uploading logs`,{cause:e})}}async function Kl(e){let t=$.current();if(t)return t.videoEffect(e)}async function ql(e,t){let n=$.current();if(n)return n.audioEffect(e.length>0?e:null,t)}async function Jl(e){let t=$.current();t&&await t.setAudioStream(e)}async function Yl(e,t=null,n=null){let r=$.current();if(!r)return;let i=n??t?.id,a=null;if(t&&(a=r.getCachedParticipantIdByExternalId(t),!a)){su(t,`setVmojiSvg`,r);return}r.setAnimojiSvg(e,a,i)}function Xl(e){let t=$.current();t&&t.setAnimojiFill(e)}async function Zl(e=null,t,n=!1){return lu().getWaitingHall(e,t,n)}async function Ql(){return lu().getAudienceModeHands()}async function $l(e,t=!1){let n=lu(),r;if(e){let t=n.getCachedParticipantIdByExternalId(e);if(!t){su(e,`promoteParticipant`,n);return}r=M.decomposeParticipantId(t).compositeUserId}return n.promoteParticipant(r,t)}async function eu(e=!1){return lu().requestPromotion(e)}async function tu(e=!1){return lu().acceptPromotion(e)}async function nu(e){return lu().getParticipantListChunk(e)}async function ru(e){return lu().getParticipants(e)}async function iu(e){return lu().feedback(e)}async function au(e,t,n){return lu(n).enableFeatureForRoles(e,t)}function ou(e){return e?B.get(e)??null:$.current()??B.getFirst()}function su(e,t,n){R.onNonFatalError(Error(`Participant ID mapping not found for external ID "${e.id}" while handling ${t}`),n.id)}function cu(e,t,n){let r=Array.from(new Set(e));R.onNonFatalError(Error(`Participant ID mapping not found for external IDs "${r.join(`", "`)}" while handling ${t}`),n.id)}function lu(e){let t=ou(e);if(!t)throw Error(`Conversation not found`);return t}function uu(e,t){let n=$.current();if(!n)return null;let r=n.getCachedParticipantIdByExternalId(e);return r?{conversation:n,participantId:r}:(su(e,t,n),null)}async function du(e){await yc.removeHistoryRecords(e)}async function fu(e){let t=$.current()??B.getFirst();t&&await t.startAsr(e)}async function pu(e){let t=$.current()??B.getFirst();t&&await t.stopAsr(e)}async function mu(e){let t=$.current()??B.getFirst();t&&await t.requestAsr(e)}async function hu(e){let t=$.current();return t?t.startUrlSharing(e):Promise.reject()}async function gu(){let e=$.current();return e?e.stopUrlSharing():Promise.reject()}async function _u(e){await B.switchCall(e)}function vu(){return B.getActiveId()}function yu(){return $.getSyncedTime()}function bu(){return N.sdkVersion}typeof window<`u`&&(window.__CALLS_SDK=Sn),exports.Api=fc,exports.ApiExternal=vc,exports.ArrayDequeue=_c,exports.AuthData=y,exports.BaseLogger=m,exports.CallDirection=Ga,exports.CallType=Ka,exports.ChatRoomEventType=qa,exports.ConversationFeature=Ja,exports.ConversationOption=Ya,exports.DebugMessageType=Tn,exports.ExternalIdType=oo,Object.defineProperty(exports,"FacingMode",{enumerable:!0,get:function(){return Mt}}),exports.FatalError=x,exports.HangupReason=k,exports.HangupType=O,exports.MediaOption=S,exports.MediaTrackKind=A,exports.MediaType=H,exports.MuteState=Qa,exports.ParticipantState=X,exports.ParticipantStateDataValue=gc,exports.ParticipantStatus=P,exports.RecordRole=hc,exports.RoomsEventType=$a,exports.Signaling=Wa,exports.SignalingCommandType=V,exports.SignalingConnectionType=xr,exports.SignalingNotification=K,exports.TransportTopology=J,exports.UserRole=no,exports.UserType=j,exports.VolumeDetector=Ao,exports.acceptCall=Rc,exports.acceptPromotion=tu,exports.activateRooms=Il,exports.addMovie=Ml,exports.addParticipant=Wc,exports.addParticipantInternal=Gc,exports.authorize=Lc,exports.browser=Sc,exports.callInternal=Mc,exports.callTo=Ac,exports.captureScreen=Yc,exports.captureVmoji=Xc,exports.changeAudioEffect=ql,exports.changeConversationOptions=hl,exports.changeDevice=Jc,exports.changeParticipantState=nl,exports.changePriorities=tl,exports.changeVideoEffect=Kl,exports.chatHistory=vl,exports.chatMessage=gl,exports.chatMessageInternal=_l,exports.createJoinLink=Cl,exports.customData=yl,exports.customDataInternal=bl,exports.debug=Bl,exports.debugLogs=Ul,exports.debugMessage=Vl,exports.debugMessageWithContext=Hl,exports.declineCall=zc,exports.enableFeatureForRoles=au,exports.enableVideoSuspend=pl,exports.enableVideoSuspendSuggest=ml,exports.feedback=iu,exports.forceRelayPolicy=Dl,exports.getActiveCallId=vu,exports.getAnonymTokenByLink=Tl,exports.getAudienceModeHands=Ql,exports.getInbounds=Fc,exports.getParticipantListChunk=nu,exports.getParticipants=ru,exports.getStreamInfo=jl,exports.getSyncedTime=yu,exports.getWaitingHall=Zl,exports.grantRoles=ol,exports.grantRolesInternal=sl,exports.hangup=Uc,exports.init=kc,exports.joinCall=Bc,exports.joinCallByLink=Hc,exports.joinCallInternal=Vc,exports.muteParticipant=cl,exports.muteParticipantInternal=ll,exports.pinParticipant=ul,exports.pinParticipantInternal=dl,exports.processPush=Nc,exports.processPushInternal=Pc,exports.promoteParticipant=$l,exports.publishStream=Al,exports.putHandsDown=rl,exports.removeHistoryRecords=du,exports.removeJoinLink=wl,exports.removeMovie=Pl,exports.removeParticipant=Kc,exports.removeParticipantInternal=qc,exports.removeRooms=Rl,exports.requestAsr=mu,exports.requestDisplayLayout=al,exports.requestPromotion=eu,exports.setAudioEffects=Ec,exports.setAudioStream=Jl,exports.setLocalResolution=el,exports.setLogger=wc,exports.setMediaModifiers=fl,exports.setStatisticsInterval=zl,exports.setVad=Dc,exports.setVideoEffects=Tc,exports.setVideoStream=Zc,exports.setVmoji=Oc,exports.setVmojiFill=Xl,exports.setVmojiSvg=Yl,exports.setVolume=El,exports.startAsr=fu,exports.startAudienceConversation=Sl,exports.startConversation=xl,exports.startStats=Ic,exports.startStream=Ol,exports.startUrlSharing=hu,exports.stopAsr=pu,exports.stopStream=kl,exports.stopUrlSharing=gu,exports.switchCall=_u,exports.switchRoom=Ll,exports.toggleLocalAudio=$c,exports.toggleLocalVideo=Qc,exports.updateDisplayLayout=il,exports.updateMovie=Nl,exports.updateRooms=Fl,exports.uploadDebugLogs=Gl,exports.utils=Cc,exports.version=bu;
|
|
13
|
+
`)}})}_startMonitorRtpShareInterval(){let e=5e3;if(this._monitorRtpShareInterval)return;let t=()=>{if(!this._pc){this._stopMonitorRtpShareInterval();return}this._monitorRtpShare(),this._monitorRtpShareInterval=window.setTimeout(t,e)};this._monitorRtpShareInterval=window.setTimeout(t,e)}_stopMonitorRtpShareInterval(){this._monitorRtpShareInterval&&(window.clearTimeout(this._monitorRtpShareInterval),this._monitorRtpShareInterval=null)}},Y=function(e){return e.REMOTE_TRACK_ADDED=`REMOTE_TRACK_ADDED`,e.REMOTE_TRACK_REMOVED=`REMOTE_TRACK_REMOVED`,e.REMOTE_STREAM_SECOND=`REMOTE_STREAM_SECOND`,e.AUDIO_MIX_STALL=`AUDIO_MIX_STALL`,e.REMOTE_DATA_STATS=`REMOTE_DATA_STATS`,e.STATE_CHANGED=`STATE_CHANGED`,e.LOCAL_STATE_CHANGED=`LOCAL_STATE_CHANGED`,e.SIGNALLED_ACTIVE_PARTICIPANTS=`SIGNALLED_ACTIVE_PARTICIPANTS`,e.SIGNALLED_SPEAKER_CHANGED=`SIGNALLED_SPEAKER_CHANGED`,e.SIGNALLED_STALLED_PARTICIPANTS=`SIGNALLED_STALLED_PARTICIPANTS`,e.TOPOLOGY_CHANGED=`TOPOLOGY_CHANGED`,e.NETWORK_STATUS=`NETWORK_STATUS`,e.PEER_CONNECTION_CLOSED=`PEER_CONNECTION_CLOSED`,e.ASR_TRANSCRIPTION=`ASR_TRANSCRIPTION`,e.ANIMOJI_STREAM=`ANIMOJI_STREAM`,e.ANIMOJI_ERROR=`ANIMOJI_ERROR`,e.SCREEN_SHARING_STAT=`SCREEN_SHARING_STAT`,e}({}),fa=class extends b{constructor(e,t,n,r,i=R,a=null,o=null,s=null,c=null){super(),h(this,`_signaling`,void 0),h(this,`_mediaSource`,void 0),h(this,`_topology`,void 0),h(this,`_allocated`,[]),h(this,`_opened`,[]),h(this,`_directTransport`,null),h(this,`_serverTransport`,null),h(this,`_serverSettings`,void 0),h(this,`_dtListeners`,[]),h(this,`_stListeners`,[]),h(this,`_states`,{}),h(this,`_localState`,q.IDLE),h(this,`_animojiReceiver`,null),h(this,`_animojiSender`,null),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_statAggregator`,void 0),h(this,`_codecStatsAggregator`,void 0),h(this,`_onFirstMediaSent`,void 0),h(this,`_firstMediaSentProbeStopped`,!1),h(this,`_vadController`,null),h(this,`_updateVadTrack`,()=>{this._vadController?.setSendTrack(this._mediaSource.getSendAudioTrack())}),this._signaling=t,this._mediaSource=n,this._topology=e,this._serverSettings=r,this._debug=i,this._logger=a,this._statAggregator=o,this._codecStatsAggregator=s,this._onFirstMediaSent=c,this.subscribe(this._signaling,G.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Yt.ANIMOJI_STATUS,this._onAnimojiStatus.bind(this)),this.subscribe(this._mediaSource,Yt.SOURCE_CHANGED,this._onSourceChanged.bind(this)),this.subscribe(this._mediaSource,Yt.SOURCE_READY,this._updateVadTrack),this._createVad(),this._createAnimojiTransport(),e===J.SERVER&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._debug.log(`Update transport settings`,e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._debug.log(`Trying allocate participant [${e}]`),this._allocated.indexOf(e)!==-1){this._debug.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology===J.DIRECT&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology===J.SERVER&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,n=!1,r=!1){this._debug.log(`Trying open participant`,{participantIds:e});let i=r;for(let t of e){if(this._opened.indexOf(t)!==-1){this._debug.warn(`The participant [${t}] has already had opened transport`);continue}if(this._allocated.indexOf(t)===-1){this._debug.warn(`The participant [${t}] has no allocated transport`);continue}this._opened.push(t),i=!0}i&&(this._topology===J.DIRECT&&this._directTransport&&this._directTransport.open(t),this._topology===J.SERVER&&this._serverTransport&&(this._serverTransport.open(n),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),this._debug.debug(`The transport has been opened`,e))}close(e){let t=this._allocated.indexOf(e),n=this._opened.indexOf(e);t<0&&this._debug.warn(`The participant [${e}] transport has already deallocated`),this._topology===J.DIRECT&&this._directTransport&&n>=0&&this._releaseDirectTransport(),this._topology===J.SERVER&&(this._serverTransport?.removeParticipant(e),this._setStates([e],q.CLOSED)),n>=0&&this._opened.splice(n,1),t>=0&&this._allocated.splice(t,1),delete this._states[e]}destroy(){this.stopFirstMediaSentProbe(),this.unsubscribe();for(let e of this._dtListeners)e.dispose();for(let e of this._stListeners)e.dispose();this._removeAnimojiTransport(),M.audioEffects?.destroy(),this._vadController?.destroy(),this._vadController=null,this._directTransport?.close(),this._directTransport=null,this._serverTransport?.close(),this._serverTransport=null,this._allocated=[],this._opened=[]}stopFirstMediaSentProbe(){this._firstMediaSentProbeStopped||(this._firstMediaSentProbeStopped=!0,this._directTransport?.stopFirstMediaSentProbe(),this._serverTransport?.stopFirstMediaSentProbe())}holdClose(){this.unsubscribe();for(let e of this._dtListeners)e.dispose();for(let e of this._stListeners)e.dispose();this._vadController?.destroy(),this._vadController=null,this._directTransport?.close(),this._directTransport=null,this._serverTransport?.close(),this._serverTransport=null,this._allocated=[],this._opened=[]}setRemoteHold(e){this._directTransport?.setRemoteHold(e)}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}getState(){return this._topology===J.SERVER?this._serverTransport?.getState():this._directTransport?.getState()}getStates(){return this._states}setAnimojiSvg(e,t){M.vmoji&&t.isMe&&M.vmoji.AnimojiPreviewGenerator?.setSvgData(t),(!(t.svg instanceof ArrayBuffer)||t.svg.byteLength!==0)&&this._animojiReceiver?.setParticipantSvg(e,t)}setAnimojiFill(e){this._animojiSender?.setFill(e)}async onCameraResolutionChanged(){this._topology===J.SERVER&&this._serverTransport&&await this._serverTransport.onCameraResolutionChanged()}_setStates(e,t){let n=e.filter(e=>this._states[e]===t?!1:(this._states[e]=t,!0));n.length&&this._triggerEvent(`STATE_CHANGED`,n,t)}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent(`LOCAL_STATE_CHANGED`,e))}_onSignalingNotification(e){if(e.notification===K.TOPOLOGY_CHANGED)return this._onTopologyChanged(e)}_handleFirstMediaSent(){this._firstMediaSentProbeStopped||(this.stopFirstMediaSentProbe(),this._onFirstMediaSent?.())}_getFirstMediaSentCallback(){return!this._onFirstMediaSent||this._firstMediaSentProbeStopped?null:this._handleFirstMediaSent.bind(this)}_onTopologyChanged(e){if(e.topology!==this._topology){if(this._debug.log(`Topology changed ${this._topology} -> ${e.topology}`),this._logger?.log(C.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology===J.SERVER&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&(this._directTransport?.preventRestart(),this._serverTransport.open()))),this._topology===J.DIRECT){let t=e.offerTo||[],n=e.offerToTypes||[],r=e.offerToDeviceIdxs||[],i=t.length&&n.length?j.composeParticipantId(t[0],n[0],r[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){this._debug.error(`Topology changed to DIRECT, but the list of allocated participants is empty`);return}this._allocated.length>1&&this._debug.warn(`Topology changed to DIRECT, but the allocated participants count more then one`);let a=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let e=i===a;this._directTransport=this._createDirectTransport(a,e)}this._opened.indexOf(a)>=0&&this._directTransport.open()}this._triggerEvent(`TOPOLOGY_CHANGED`,this._topology)}}_createDirectTransport(e,t=!1){let n=new Jr(e,t,this._signaling,this._mediaSource,this._serverSettings,this._debug,this._logger,this._statAggregator,this._codecStatsAggregator,this._getFirstMediaSentCallback());return this._dtListeners.length>0&&this._debug.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(n.addEventListener(`REMOTE_TRACK_ADDED`,this._onRemoteTrackAdded.bind(this,e)),n.addEventListener(`REMOTE_TRACK_REMOVED`,this._onRemoteTrackRemoved.bind(this,e)),n.addEventListener(`REMOTE_DATA_STATS`,this._onRemoteDataStats.bind(this)),n.addEventListener(`STATE_CHANGED`,this._onDirectTransportChanged.bind(this)),n.addEventListener(`NETWORK_STATUS`,this._onTransportNetworkStatus.bind(this)),n.addEventListener(`PEER_CONNECTION_CLOSED`,this._onPeerConnectionClosed.bind(this,J.DIRECT))),this._animojiReceiver&&this._animojiSender&&n.setAnimojiTransport(this._animojiReceiver,this._animojiSender),n}_createServerTransport(){let e=new da(this._signaling,this._mediaSource,this._serverSettings,this._debug,this._logger,this._statAggregator,this._codecStatsAggregator,this._getFirstMediaSentCallback());return this._stListeners.length>0&&this._debug.warn(`The list of server transport listeners is not empty`),this._stListeners=[],this._stListeners.push(e.addEventListener(`REMOTE_TRACK_ADDED`,this._onRemoteTrackAdded.bind(this)),e.addEventListener(`REMOTE_TRACK_REMOVED`,this._onRemoteTrackRemoved.bind(this)),e.addEventListener(`AUDIO_MIX_STALL`,this._onServerAudioMixStall.bind(this)),e.addEventListener(`REMOTE_DATA_STATS`,this._onRemoteDataStats.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,J.SERVER)),e.addEventListener(`ASR_TRANSCRIPTION`,this._onAsrTranscription.bind(this))),this._animojiReceiver&&this._animojiSender&&e.setAnimojiTransport(this._animojiReceiver,this._animojiSender),e}_releaseDirectTransport(){this._directTransport?.close(),this._directTransport=null;for(let e of this._dtListeners)e.dispose();this._dtListeners=[]}_releaseServerTransport(){this._serverTransport?.close(),this._serverTransport=null;for(let e of this._stListeners)e.dispose();this._stListeners=[]}_onDirectTransportChanged(e){let t=this._directTransport?.participantId;if(e===q.CONNECTED&&this._topology===J.DIRECT&&this._releaseServerTransport(),(e===q.CLOSED||e===q.FAILED)&&(this._releaseDirectTransport(),this._topology===J.DIRECT)){let e=this._opened.indexOf(t);e>=0&&this._opened.splice(e,1);let n=this._allocated.indexOf(t);n>=0&&this._allocated.splice(n,1)}this._topology===J.DIRECT&&t&&(this._setStates([t],e),this._setLocalState(e))}_onServerTransportChanged(e){let t=this._opened.slice();e===q.CONNECTED&&this._topology===J.SERVER&&this._releaseDirectTransport(),(e===q.CLOSED||e===q.FAILED)&&(this._releaseServerTransport(),this._topology===J.SERVER&&(this._allocated=[],this._opened=[])),this._topology===J.SERVER&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology===J.SERVER&&this._triggerEvent(`SIGNALLED_ACTIVE_PARTICIPANTS`,e)}_onTransportStalledParticipants(e){this._topology===J.SERVER&&this._triggerEvent(`SIGNALLED_STALLED_PARTICIPANTS`,e)}_onTransportSpeakerChanged(e){this._topology===J.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)}_onServerAudioMixStall(e){this._topology===J.SERVER&&this._triggerEvent(`AUDIO_MIX_STALL`,e)}_onRemoteDataStats(e){this._triggerEvent(`REMOTE_DATA_STATS`,e)}_onRemoteTrackAdded(e,t,n){this._triggerEvent(`REMOTE_TRACK_ADDED`,e,t,n)}_onRemoteTrackRemoved(e,t,n){this._triggerEvent(`REMOTE_TRACK_REMOVED`,e,t,n)}_onAsrTranscription(e){this._triggerEvent(`ASR_TRANSCRIPTION`,e)}_onSourceChanged(e){let t=this._mediaSource.getStream();t&&this._animojiSender?.setStream(t),(!e||e.kind===k.audio)&&this._updateVadTrack()}_onAnimojiStream(e,t){this._triggerEvent(`ANIMOJI_STREAM`,e,t)}_onAnimojiStatus(e){e?this._animojiSender?.resume():this._animojiSender?.pause(),this._mediaSource.onAnimojiSender(e)}_createVad(){M.vad&&(this._vadController=new M.vad.VadController(this._mediaSource.getSendAudioTrack(),M.vadOptions),this._vadController.setLogger((e,...t)=>R.send(e,...t),`VAD`),this._vadController.init().catch(e=>{R.warn(`[Transport] VAD init failed, continuing without VAD`,e),this._vadController?.destroy(),this._vadController=null}))}_createAnimojiTransport(){if(!M.vmoji)return;this._animojiReceiver=new M.vmoji.AnimojiReceiver((e,t)=>this._onAnimojiStream(e,t),e=>this._onAnimojiStream(e,null),e=>{this._triggerEvent(`ANIMOJI_ERROR`,e)},M.vmojiOptions.renderingOptions);let e=this._mediaSource.getStream();this._animojiSender=new M.vmoji.AnimojiSender(e,this._signaling.getPeerId(),M.vmojiOptions.protocolVersion,{requested:this._mediaSource.isAnimojiRequested,useAI:M.vmojiOptions.renderingOptions.useAI}),this._animojiSender.onLocalData=e=>this._animojiReceiver?.receive(e)}_removeAnimojiTransport(){this._animojiSender?.destroy(),this._animojiSender=null,this._animojiReceiver?.destroy(),this._animojiReceiver=null}getStreamWaitingTimeMs(e,t){return this._topology===J.SERVER?this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(this._logger?.log(C.PAT_WAITING_TIME_ERROR,`noTransport`),this._debug.error(`Cannot get stream waiting time, server transport is not initialized`),0):(this._logger?.log(C.PAT_WAITING_TIME_ERROR,`wrongTopology`),this._debug.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0)}},pa=`videochat-epi`,ma=5e3,ha=500,ga=class extends b{constructor(e,t,n=null,r=!1,i=R){super(),h(this,`_previousPerfStatReportTimestamp`,0),h(this,`_previousNetworkStatReportTimestamp`,Date.now()),h(this,`_previousCallStatReportTimestamp`,Date.now()),h(this,`_previousCallStatReport`,null),h(this,`_previousRemoteInboundRtps`,new Map),h(this,`_screenShareStats`,[]),h(this,`_signaling`,void 0),h(this,`_directTopology`,void 0),h(this,`_debug`,void 0),h(this,`_statAggregator`,void 0),h(this,`_handleScreenSharingStat`,e=>{this._screenShareStats.push(e)}),h(this,`_handleTransportStateChanged`,e=>{(this._directTopology&&e===q.CONNECTED||!this._directTopology&&e===q.OPENED)&&(this._previousNetworkStatReportTimestamp=Date.now(),this._previousCallStatReportTimestamp=Date.now(),this._previousRemoteInboundRtps.clear())}),this._signaling=t,this._directTopology=r,this._debug=i,this._statAggregator=n,this.subscribe(e,Y.REMOTE_DATA_STATS,this._handleStats.bind(this)),this.subscribe(e,Y.SCREEN_SHARING_STAT,this._handleScreenSharingStat.bind(this)),this.subscribe(e,Y.STATE_CHANGED,this._handleTransportStateChanged.bind(this))}destroy(){this._previousRemoteInboundRtps.clear(),this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(pa)||``,10);return isNaN(e)?0:e}catch{return 0}}async _handleStats(e){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&M.perfStatReportEnabled&&this._previousPerfStatReportTimestamp+ma<=t&&(await this.reportPerfStats(e),this._previousPerfStatReportTimestamp=t);let n=e.outbound.transport.local?.protocol===`tcp`;!this._directTopology&&n&&this._previousNetworkStatReportTimestamp+ha<=t&&(await this.reportNetworkStats(e),this._previousNetworkStatReportTimestamp=t),M.callStatReportEnabled&&this._previousCallStatReportTimestamp+M.statisticsInterval<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)}async reportPerfStats(e){let t=e.inbound.rtps.reduce((e,t)=>(t.kind===`video`&&(e.framesDecoded+=t.framesDecoded||0,e.framesReceived+=t.framesReceived||0),e),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let e=await this._signaling.reportPerfStat(t);localStorage.setItem(pa,e.estimatedPerformanceIndex)}catch{}}async reportNetworkStats(e){let t={timestamp:e.outbound.transport.timestamp,sendBitrate:e.outbound.rtps.reduce((e,t)=>e+(t.bandwidth??0)*8,0)};if(t.timestamp)try{await this._signaling.reportNetworkStat(t)}catch{}}_reportCallStats(e){let t={call_topology:this._directTopology?`D`:`S`,stat_time_delta:0,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,freeze_count:0,total_freezes_duration:0,rtt:Math.round(e.inbound.transport.currentRoundTripTime*1e3),ss_freeze_count:0,ss_total_freezes_duration:0,local_address:va(e.inbound.transport.local),local_connection_type:e.inbound.transport.local?.type,network_type:e.inbound.transport.local?.networkType,transport:e.inbound.transport.local?.protocol,remote_address:va(e.inbound.transport.remote),remote_connection_type:e.inbound.transport.remote?.type};this._previousCallStatReport||(this._previousCallStatReport=Object.assign({},t));let n=!1,r=!1;for(e.inbound.rtps.reduce((e,t)=>(t.kind===`video`?(n=!0,t.framesReceived&&(e.jitter_video=e.jitter_video*e.inbound_video_count/(e.inbound_video_count+1)+t.jitter*1e3/(e.inbound_video_count+1),e.interframe_delay_variance=e.interframe_delay_variance*e.inbound_video_count/(e.inbound_video_count+1)+(t.interframeDelayVariance||0)*1e6/(e.inbound_video_count+1),e.inbound_video_count++),e.frames_dropped+=t.framesDropped||0,e.nack_sent+=t.nackCount,e.pli_sent+=t.pliCount,e.fir_sent+=t.firCount,e.freeze_count+=t.freezeCountDelta||0,e.total_freezes_duration+=t.totalFreezesDurationDelta||0):(r=!0,t.totalSamplesReceived&&(e.jitter_audio=e.jitter_audio*e.inbound_audio_count/(e.inbound_audio_count+1)+t.jitter*1e3/(e.inbound_audio_count+1),e.total_audio_energy=e.total_audio_energy*e.inbound_audio_count/(e.inbound_audio_count+1)+(t.totalAudioEnergy||0)/(e.inbound_audio_count+1),e.inbound_audio_count++),e.total_audio_samples_received+=t.totalSamplesReceived||0,e.inserted_audio_samples_for_deceleration+=t.insertedSamplesForDeceleration||0,e.removed_audio_samples_for_acceleration+=t.removedSamplesForAcceleration||0,e.concealed_audio_samples+=t.concealedSamples||0,e.silent_concealed_audio_samples+=t.silentConcealedSamples||0,e.audio_concealment_events+=t.concealmentEvents||0),e),t),e.outbound.rtps.reduce((e,t)=>(t.kind===`video`&&(e.nack_received+=t.nackCount,e.pli_received+=t.pliCount,e.fir_received+=t.firCount),e),t);this._screenShareStats.length;){let e=this._screenShareStats.pop();e?.freeze_duration&&(t.ss_freeze_count+=1,t.ss_total_freezes_duration+=e.freeze_duration)}let i={call_topology:t.call_topology,stat_time_delta:Math.max(0,Date.now()-this._previousCallStatReportTimestamp),nack_sent:Math.max(0,t.nack_sent-this._previousCallStatReport.nack_sent),nack_received:Math.max(0,t.nack_received-this._previousCallStatReport.nack_received),pli_sent:Math.max(0,t.pli_sent-this._previousCallStatReport.pli_sent),pli_received:Math.max(0,t.pli_received-this._previousCallStatReport.pli_received),fir_sent:Math.max(0,t.fir_sent-this._previousCallStatReport.fir_sent),fir_received:Math.max(0,t.fir_received-this._previousCallStatReport.fir_received),frames_dropped:Math.max(0,t.frames_dropped-this._previousCallStatReport.frames_dropped),rtt:Math.max(0,t.rtt)};if(M.simulcast&&(i.is_simulcast=!0),navigator.hardwareConcurrency&&(i.cpu_hardware_concurrency=navigator.hardwareConcurrency),n&&!ya(t.jitter_video)&&(i.jitter_video=Math.round(t.jitter_video)),r&&!ya(t.jitter_audio)&&(i.jitter_audio=Math.round(t.jitter_audio)),n&&!ya(t.interframe_delay_variance)&&(i.interframe_delay_variance=t.interframe_delay_variance),t.freeze_count&&t.total_freezes_duration&&(i.freeze_count=t.freeze_count,i.total_freezes_duration=Math.round(t.total_freezes_duration*1e3)),t.ss_freeze_count&&t.ss_total_freezes_duration&&(i.ss_freeze_count=t.ss_freeze_count,i.ss_total_freezes_duration=t.ss_total_freezes_duration),r&&!ya(t.total_audio_samples_received)){let e=Math.max(0,t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received),n=Math.max(0,t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration),r=Math.max(0,t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration),a=Math.max(0,t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples),o=Math.max(0,t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples),s=Math.max(0,t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events);i.inserted_audio_samples_for_deceleration=ba(n/e*1e3),i.removed_audio_samples_for_acceleration=ba(r/e*1e3),i.concealed_audio_samples=ba(a/e*1e3),i.concealed_silent_audio_samples=ba(o/e*1e3),i.concealment_audio_avg_size=ba(a/s),i.total_audio_energy=t.total_audio_energy}_a(t,`local_address`,`local_connection_type`,`network_type`,`transport`)&&(i.local_address=t.local_address,i.local_connection_type=t.local_connection_type,i.network_type=t.network_type,i.transport=t.transport),_a(t,`remote_address`,`remote_connection_type`)&&(i.remote_address=t.remote_address,i.remote_connection_type=t.remote_connection_type);let a=this._calculatePacketLoss(e.remoteInbound.rtps);a.video!==void 0&&(i.video_loss=a.video),a.audio!==void 0&&(i.audio_loss=a.audio),this._statAggregator?.logCallStat(i),M.enableLogPerfStatReport&&this._debug.log(`Sent call stats`,i),this._previousCallStatReport=t}_calculatePacketLoss(e){let t=new Map,n={audio:{lost:0,received:0},video:{lost:0,received:0}};for(let r of e){if(r.kind!==`audio`&&r.kind!==`video`)continue;let e=`${r.kind}:${r.ssrc}`,i={packetsLost:r.packetsLost,packetsReceived:r.packetsReceived},a=this._previousRemoteInboundRtps.get(e);t.set(e,i),a&&(n[r.kind].lost+=Math.max(0,i.packetsLost-a.packetsLost),n[r.kind].received+=Math.max(0,i.packetsReceived-a.packetsReceived))}this._previousRemoteInboundRtps=t;let r={};for(let e of[`audio`,`video`]){let{lost:t,received:i}=n[e];t+i>0&&(r[e]=t/(t+i)*100)}return r}};function _a(e,...t){for(let n of t)if(!Object.hasOwn(e,n)||e[n]===void 0)return!1;return!0}function va(e,t=!1){if(e?.address)return e.address+(t?`:${e.port}`:``)}function ya(e){return e===void 0}function ba(e){return Number.isNaN(e)?0:e}var xa;(function(e){function t(){return{estimatedPerformanceIndex:ga.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:8,producerCommandDataChannelVersion:3,consumerScreenDataChannelVersion:1,producerScreenDataChannelVersion:1,asrDataChannelVersion:+!!M.asrDataChannel,animojiDataChannelVersion:M.vmoji?M.vmojiOptions.protocolVersion:1,animojiBackendRender:!M.vmojiOptions.renderingOptions.useFullClientRendering,onDemandTracks:!0,unifiedPlan:!0,singleSession:!0,videoTracksCount:M.videoTracksCount,red:!0,audioShare:M.audioShare,fastScreenShare:M.fastScreenShare,videoSuspend:M.videoSuspend,simulcast:M.simulcast,simulcastNativeOrder:!0,consumerFastScreenShare:M.consumerFastScreenShare,consumerFastScreenShareQualityOnDemand:M.consumerFastScreenShareQualityOnDemand,transparentAudio:M.transparentAudio}}e.get=t})(xa||(xa={}));var Sa=xa,Ca={producerScreenTrack:()=>!0,videoTracksCount:()=>M.videoTracksCount>0,waitingHall:()=>!0,filteredMessages:()=>!0,consumerScreenTrack:()=>!0,muteNotificationForAdmins:()=>!0,movieShare:()=>M.movieShare,useParticipantListChunk:()=>M.useParticipantListChunk,useRooms:()=>M.useRooms,vmoji:()=>!!M.vmoji,useCallsToContacts:()=>M.useCallsToContacts,useChatRooms:()=>M.useChatRooms,audienceModeHandUpTimestamps:()=>!1,animojiBackendRender:()=>!M.vmojiOptions.renderingOptions.useFullClientRendering,sessionStateUpdates:()=>M.enableSessionStateUpdates,addParticipant:()=>M.addParticipant,p2pRelay:()=>!1,waitForAdmin:()=>M.waitForAdminInGroupCalls,hold:()=>M.hold},wa=class{static getFlags(){let e=Object.values(Ca),t=0;for(let n=0;n<e.length;n++)e[n]()&&(t|=1<<n);return t.toString(16).toUpperCase()}static parseCapabilities(e){let t=parseInt(e||`0`,16);return Object.keys(Ca).reduce((e,n,r)=>(e[n]=!!(t&1<<r),e),{})}},Ta=63n,Ea=16383n,Da=1073741823,Oa=4611686018427387903n,ka=class{encode(e){let t=typeof e==`number`?BigInt(e):e;if(t<=Ta)return new Uint8Array([Number(t)]);if(t<=Ea)return new Uint8Array([64|Number(t>>8n),Number(t&255n)]);if(t<=BigInt(Da))return new Uint8Array([128|Number(t>>24n),Number(t>>16n&255n),Number(t>>8n&255n),Number(t&255n)]);if(t<=Oa)return new Uint8Array([192|Number(t>>56n),Number(t>>48n&255n),Number(t>>40n&255n),Number(t>>32n&255n),Number(t>>24n&255n),Number(t>>16n&255n),Number(t>>8n&255n),Number(t&255n)]);throw RangeError(`Number is too large to encode using varint`)}},Aa=class{decode(e){let t=this.getNumBytesForLengthInteger(e);if(t<0)throw Error(`Invalid length prefix`);if(e.length<t)return null;let n=BigInt(0);switch(t){case 1:n=BigInt(e[0]&63);break;case 2:n=BigInt(e[0]&63)<<8n|BigInt(e[1]);break;case 4:n=BigInt(e[0]&63)<<24n|BigInt(e[1])<<16n|BigInt(e[2])<<8n|BigInt(e[3]);break;case 8:n=BigInt(e[0]&63)<<56n|BigInt(e[1])<<48n|BigInt(e[2])<<40n|BigInt(e[3])<<32n|BigInt(e[4])<<24n|BigInt(e[5])<<16n|BigInt(e[6])<<8n|BigInt(e[7]);break}return n}getNumBytesForLengthInteger(e){let t=e[0]&192;return t===0?1:t===64?2:t===128?4:t===192?8:-1}},ja=class{constructor(e){h(this,`encoder`,void 0),h(this,`compression`,void 0),h(this,`lengthEncoder`,void 0),this.encoder=new TextEncoder,this.lengthEncoder=new ka,this.compression=e??null}encode(e){let t=this.encoder.encode(e);t=this.compress(t);let n=this.lengthEncoder.encode(t.length),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),r}compress(e){if(!this.compression)return e;switch(this.compression){case`gzip`:return p.gzipSync(e);case`deflate`:return p.zlibSync(e);case`deflate-raw`:return p.deflateSync(e);default:return e}}},Ma=class{constructor(e){h(this,`decoder`,void 0),h(this,`compression`,void 0),h(this,`lengthDecoder`,void 0),h(this,`buffer`,void 0),h(this,`expectedLength`,void 0),h(this,`offset`,void 0),h(this,`lengthPrefixLength`,void 0),this.decoder=new TextDecoder,this.lengthDecoder=new Aa,this.compression=e??null,this.buffer=new Uint8Array,this.expectedLength=null,this.offset=0}decode(e){let t=[];for(this.buffer=new Uint8Array([...this.buffer,...e]);this.buffer.length>0;){if(this.expectedLength===null){if(this.expectedLength=this.readLength(this.buffer),this.expectedLength===null)return t;this.offset=this.lengthPrefixLength}if(this.buffer.length-this.offset<this.expectedLength)return t;let e=this.buffer.subarray(this.offset,this.offset+this.expectedLength);e=this.decompress(e),t.push(this.decoder.decode(e)),this.buffer=this.buffer.subarray(this.offset+this.expectedLength),this.expectedLength=null,this.offset=0}return t}readLength(e){if(e.length===0)return 0;if(this.lengthPrefixLength=this.lengthDecoder.getNumBytesForLengthInteger(e),this.lengthPrefixLength<0)throw Error(`Invalid length prefix`);let t=this.lengthDecoder.decode(e.subarray(0,this.lengthPrefixLength));return t===null?null:Number(t)}decompress(e){if(!this.compression)return e;switch(this.compression){case`gzip`:return p.gunzipSync(e);case`deflate`:return p.unzlibSync(e);case`deflate-raw`:return p.inflateSync(e);default:return e}}},Na=class{static isBrowserSupported(){return!(!(`WebTransport`in window&&typeof WebTransport==`function`)||T.browserName()===`Safari`)}constructor(e,t={},n=R){h(this,`onopen`,null),h(this,`onmessage`,null),h(this,`onerror`,null),h(this,`onclose`,null),h(this,`readyState`,WebSocket.CONNECTING),h(this,`webTransport`,null),h(this,`writer`,null),h(this,`url`,void 0),h(this,`options`,void 0),h(this,`compression`,void 0),h(this,`encoder`,void 0),h(this,`decoder`,void 0),h(this,`_debug`,void 0),this._debug=n,this.url=e,this.options=t,this.compression=this.getCompressionTypeFromUrl(e),this.encoder=new ja(this.compression),this.decoder=new Ma(this.compression),this.connect()}async send(e){if(this.readyState!==WebSocket.OPEN){this._debug.warn(`[WebTransport] Attempt to send data before webtransport is open`);return}let t=this.writer;if(!t){this._debug.warn(`[WebTransport] Attempt to send data before stream is ready`);return}try{await t.ready;let n=this.encoder.encode(e);await t.write(n)}catch(e){this.handleStreamError(`send`,e)}}close(e=1e3,t=``){this.readyState===WebSocket.CLOSING||this.readyState===WebSocket.CLOSED||(this.readyState=WebSocket.CLOSING,this.requestNativeClose(e,t))}getCompressionTypeFromUrl(e){try{let t=new URL(e).searchParams.get(`compression`);switch(t){case`gzip`:case`deflate`:case`deflate-raw`:return t;default:return null}}catch(e){return this._debug.log(`[WebTransport] Exception while parsing compression`,e),null}}async connect(){try{let e=new WebTransport(this.url,{...this.options});if(this.webTransport=e,this.observeClosed(e),await e.ready,this.readyState!==WebSocket.CONNECTING)return;this._debug.debug(`[WebTransport] WebTransport connected to `+this.url);let t=await e.createBidirectionalStream();if(this.readyState!==WebSocket.CONNECTING)return;this.writer=t.writable.getWriter(),this.readyState=WebSocket.OPEN,this.emitEvent(`open`,this.onopen,new Event(`open`)),this.readyState===WebSocket.OPEN&&this.readLoop(t.readable)}catch(e){if(!this.webTransport){queueMicrotask(()=>this.fail(`connect`,e));return}this.fail(`connect`,e)}}observeClosed(e){e.closed.then(({closeCode:e,reason:t})=>{this.finishClose(e,t)},e=>{let t=this.readyState===WebSocket.CONNECTING?`connect`:`session`;this.fail(t,e),this.finishClose(1006,``)}).catch(e=>{this._debug.error(`[WebTransport] Failed to process native close`,e)})}async readLoop(e){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e){this.close(1e3,`Stream Closed`);return}if(n)for(let e of this.decoder.decode(n))this.emitEvent(`message`,this.onmessage,new MessageEvent(`message`,{data:e}))}}catch(e){this.handleStreamError(`read`,e)}finally{t.releaseLock()}}fail(e,t){this.readyState===WebSocket.CLOSING||this.readyState===WebSocket.CLOSED||(this.readyState=WebSocket.CLOSING,this._debug.error(`[WebTransport] ${e} failed`,t),this.emitEvent(`error`,this.onerror,this.createErrorEvent(t,e)),this.requestNativeClose(1006,`${e} failed`))}handleStreamError(e,t){let n=typeof t==`object`&&t&&`source`in t?t.source:void 0;if(n===`session`)return;let r=n===void 0&&t instanceof Error&&t.name===`WebTransportError`&&t.message.startsWith(`Session closed`);this.fail(r?`session`:e,t)}requestNativeClose(e,t){if(!this.webTransport){this.finishClose(1006,`Connection Failed`);return}try{this.webTransport.close({closeCode:e,reason:t})}catch(e){this._debug.warn(`[WebTransport] Native close failed synchronously`,e),this.finishClose(1006,`Close Failed`)}}finishClose(e,t){this.readyState!==WebSocket.CLOSED&&(this.writer=null,this.readyState=WebSocket.CLOSED,this.emitEvent(`close`,this.onclose,new CloseEvent(`close`,{code:e,reason:t})))}emitEvent(e,t,n){try{t?.call(this,n)}catch(t){this._debug.error(`[WebTransport] ${e} handler failed`,t)}}createErrorEvent(e,t){let n=new Event(`error`),r=e instanceof Error?e:null;return n.error=e,n.errorInfo={phase:t,name:r?.name,message:r?.message||String(e),stack:r?.stack,readyState:this.readyState,compression:this.compression},n}},Pa=function(e){return e.EMPTY_ENDPOINT=`EMPTY_ENDPOINT`,e.NETWORK_ERROR=`NETWORK_ERROR`,e.ABORTED=`ABORTED`,e}({}),Fa=class{constructor(e=R,t){h(this,`handlers`,void 0),h(this,`socket`,null),h(this,`endpoint`,``),h(this,`wtEndpoint`,null),h(this,`peerId`,null),h(this,`lastStamp`,0),h(this,`connectionType`,void 0),h(this,`reconnectCount`,0),h(this,`reconnectTimer`,0),h(this,`doctorTimer`,0),h(this,`forceWebSocket`,!1),h(this,`abortSignal`,void 0),h(this,`manualClose`,!1),h(this,`currentType`,xr.WEBSOCKET),h(this,`_debug`,void 0),this.handlers=t,this._debug=e}get readyState(){return this.socket?.readyState??null}get type(){return this.currentType}setEndpoint(e){this.endpoint=e}setWebTransportEndpoint(e){this.wtEndpoint=e||null}setPeerId(e){this.peerId=e}setLastStamp(e){this.lastStamp=e}setAbortSignal(e){this.abortSignal=e}resetReconnectCount(){this.reconnectCount=0}connect(e){this.socket&&this.socket.readyState<WebSocket.CLOSING||(e!==br.RETRY&&(this.forceWebSocket=!1,this.reconnectCount=0),this.manualClose=!1,this.connectionType=e,this._connect())}close(e){this.manualClose=!0,this._disconnect(e),window.clearTimeout(this.reconnectTimer),this.reconnectTimer=0,this.lastStamp=0}async send(e){await this.socket?.send(e)}_connect(){if(this._canUseWebTransport()){this._connectWebTransport();return}this._connectWebSocket()}_connectWebTransport(){if(!this.wtEndpoint){this._connectWebSocket();return}let e=this._buildUrl(this.wtEndpoint,!0);this.currentType=xr.WEBTRANSPORT,this.socket=new Na(e,{congestionControl:`low-latency`},this._debug),this._setSocketHandlers()}_connectWebSocket(){if(!this.endpoint){this.handlers.onFailed({failure:`EMPTY_ENDPOINT`,message:`Unable to connect to the signaling: endpoint is not set`,source:xr.WEBSOCKET,remote:!0});return}let e=this._buildUrl(this.endpoint,!1);this.currentType=xr.WEBSOCKET,this.socket=new WebSocket(e),this._setSocketHandlers()}_setSocketHandlers(){this.socket&&(this.handlers.onConnecting({connectionType:this.connectionType,source:this.currentType}),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())}_buildUrl(e,t){let n=new URL(e),r=n.searchParams;return r.set(`platform`,M.platform),r.set(`appVersion`,M.appVersion),r.set(`version`,String(M.protocolVersion)),r.set(`device`,M.device),r.set(`capabilities`,wa.getFlags()),r.set(`clientType`,M.clientType),this.connectionType&&r.set(`tgt`,this.connectionType),this.connectionType===br.RETRY&&this.lastStamp&&r.set(`recoverTs`,String(this.lastStamp)),M.useParticipantListChunk&&(r.set(`partIdx`,String(M.participantListChunkInitIndex)),M.participantListChunkInitCount!==null&&r.set(`partCount`,String(M.participantListChunkInitCount))),t&&(r.set(`compression`,`deflate-raw`),r.set(`ua`,navigator.userAgent)),this.peerId!==null&&r.set(`peerId`,String(this.peerId)),n.toString()}_canUseWebTransport(){return!this.forceWebSocket&&Na.isBrowserSupported()&&this.wtEndpoint!==null&&M.webtransport}_onOpen(){this._startDoctor(),this.handlers.onOpen()}_onMessage(e){this._startDoctor(),this.handlers.onMessage(e)}_onError(e){this.handlers.onError(e)}_onClose(e){if(this._stopDoctor(),this.handlers.onClose(e),!this.manualClose){if(this.abortSignal?.aborted){this.handlers.onFailed({failure:`ABORTED`,message:`Signaling connection aborted`,source:this.currentType});return}this.forceWebSocket=!0,this._scheduleReconnect(this.currentType===xr.WEBTRANSPORT?0:void 0)}}_disconnect(e){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(e)),this.socket=null,this._stopDoctor()}_scheduleReconnect(e=this._getReconnectDelay()){if(this.reconnectCount>=M.signalingReconnectMaxCount){this.handlers.onFailed({failure:`NETWORK_ERROR`,message:`Unable to connect to the signaling: reconnect attempts exhausted`,source:this.currentType});return}this.reconnectCount++,this.handlers.onReconnectScheduled({count:this.reconnectCount,delay:e}),this.reconnectTimer=window.setTimeout(()=>{this.connectionType=br.RETRY,this._connect()},e)}_getReconnectDelay(){return Math.min(M.signalingReconnectMaxDelay,M.signalingReconnectDelay*2**this.reconnectCount)}_startDoctor(){this._stopDoctor(),!(this.reconnectCount>=M.signalingReconnectMaxCount)&&(this.doctorTimer=window.setTimeout(()=>{this.handlers.onConnectionDead(),this.forceWebSocket=!0,this._disconnect(4e3),this._scheduleReconnect(0)},M.waitMessageDelay))}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Ia=`open`,La=300,Ra=10,za={CONVERSATION_ENDED:`conversation-ended`,OBSOLETE_CLIENT:`gen.obsoleteClient`,INVALID_TOKEN:`invalid-token`,PARTICIPANT_NOT_FOUND:`participant-not-found`,ILLEGAL_PARTICIPANT_STATE:`illegal-participant-state`,SERVICE_UNAVAILABLE:`service-unavailable`},Ba={[za.CONVERSATION_ENDED]:`conversation-ended`,[za.OBSOLETE_CLIENT]:`obsolete-client`,[za.INVALID_TOKEN]:`invalid-token`,[za.PARTICIPANT_NOT_FOUND]:`participant-not-found`,[za.ILLEGAL_PARTICIPANT_STATE]:`illegal-participant-state`,[za.SERVICE_UNAVAILABLE]:`service-unavailable`};function Va(e,t){return e.errorMessage??e.message??e.error??t}var Ha=new Set([D.CALLER_IS_BLOCKED,D.ENDED,D.NOT_FOUND,D.PARTICIPANT_LIMIT_REACHED,D.SERVICE_UNAVAILABLE]),Ua=class e extends On{static get WAIT_CONNECTION_DELAY(){return M.waitConnectionDelay}static get WAIT_RESPONSE_DELAY(){return M.waitResponseDelay}get ready(){return!this.disposed&&this.transport.readyState!==null}constructor(e=R,t=null,n=null,r=null,i=null){super(),h(this,`transport`,void 0),h(this,`sequence`,1),h(this,`lastStamp`,0),h(this,`websocketCommandsQueue`,[]),h(this,`datachannelCommandsQueue`,[]),h(this,`incomingCache`,[]),h(this,`responseHandlers`,{}),h(this,`disposed`,!1),h(this,`connectionType`,void 0),h(this,`conversationResolve`,null),h(this,`conversationReject`,null),h(this,`connected`,!1),h(this,`listenersReady`,!1),h(this,`peerId`,null),h(this,`reconnectStartedAt`,null),h(this,`connectionMessageWaitTimer`,0),h(this,`participantIdRegistry`,null),h(this,`producerNotificationDataChannel`,null),h(this,`producerCommandDataChannel`,null),h(this,`producerCommandDataChannelEnabled`,!1),h(this,`producerCommandSerializationService`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_statAggregator`,void 0),h(this,`_statPings`,void 0),h(this,`_statSignalingCommands`,void 0),this._debug=e,this._logger=t,this._statAggregator=n,this._statPings=r,this._statSignalingCommands=i,this.producerCommandSerializationService=new tr(e),this.transport=new Fa(e,{onConnecting:this._onTransportConnecting.bind(this),onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onError:this._onError.bind(this),onClose:this._onClose.bind(this),onFailed:this._onTransportFailed.bind(this),onReconnectScheduled:this._onTransportReconnectScheduled.bind(this),onConnectionDead:this._onTransportConnectionDead.bind(this)})}setAbortSignal(e){super.setAbortSignal(e),this.transport.setAbortSignal(e)}setEndpoint(e){this.transport.setEndpoint(e)}setWebTransportEndpoint(e){this.transport.setWebTransportEndpoint(e)}setParticipantIdRegistry(e){this.participantIdRegistry=e,this.producerCommandSerializationService.setParticipantIdRegistry(e)}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{if(this.producerNotificationDataChannel!==e)return;let n=this.participantIdRegistry?.handleMessage(t.data);n&&this._handleMessage(n)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=t=>{this.producerCommandSerializationService.deserializeCommandResponse(t.data).then(t=>{this.producerCommandDataChannel===e&&t&&this._handleMessage(t)}).catch(e=>{this._debug.warn(`[signaling] cannot parse message at producerCommandDataChannel`,e)})},this._handleCommandsQueue(this.datachannelCommandsQueue)}useCommandDataChannel(e){this.producerCommandDataChannelEnabled=e}resetProducerConnection(e=new Dn){this.producerCommandDataChannelEnabled=!1,this.producerNotificationDataChannel&&(this.producerNotificationDataChannel.onmessage=null,this.producerNotificationDataChannel=null),this.producerCommandDataChannel&&(this.producerCommandDataChannel.onmessage=null,this.producerCommandDataChannel=null);let t=[...this.datachannelCommandsQueue];this.datachannelCommandsQueue=[];for(let e of Object.values(this.responseHandlers))e.route===`producer`&&(t.push(e),delete this.responseHandlers[e.sequence]);t.forEach(t=>{window.clearTimeout(t.responseTimer),t.reject(e instanceof Dn?new Dn(t.name):e,!0)})}async connect(e){return new Promise((t,n)=>{if(this.transport.readyState!==null&&this.transport.readyState<WebSocket.CLOSING){this._logger?.log(C.SOCKET_ACTION,`already_opened`),n(Error(`Socket already opened`));return}this.conversationResolve=e=>{t(e),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=e=>{n(e),this.conversationResolve=null,this.conversationReject=null},this.connectionType=e,this.transport.connect(e)})}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return this._send(B.HANGUP,{reason:e},!1)}async sendCandidate(e,t){return this._send(B.TRANSMIT_DATA,{participantId:e,data:{candidate:t}},!1)}async requestTestMode(e,t){return this._send(B.REQUEST_TEST_MODE,{consumer:e,producer:t})}async sendSdp(e,t,n){let r=Object.assign({sdp:t},n);return this._send(B.TRANSMIT_DATA,{participantId:e,data:r},!0,Ra)}async acceptCall(e){return this._send(B.ACCEPT_CALL,{mediaSettings:e})}async changeMediaSettings(e){return this._send(B.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},!0,Ra)}async changeParticipantState(e,t){let n={participantState:{state:e}};return t&&(n.participantId=t),this._sendRaw(B.CHANGE_PARTICIPANT_STATE,n)}async hold(e){let t=Sa.get();return this._send(B.HOLD,{hold:e,capabilities:e?void 0:t})}async putHandsDown(){return this._send(B.PUT_HANDS_DOWN)}async addParticipant(e,t){return this._send(B.ADD_PARTICIPANT,{externalIds:e,...t})}async addParticipantLegacy(e,t){return this._send(B.ADD_PARTICIPANT,{participantIds:e,...t})}async removeParticipant(e,t=!1){return this._send(B.REMOVE_PARTICIPANT,{participantId:e,ban:t})}async allocateConsumer(e,t){let n={capabilities:t};return e&&(n.description=e.sdp),this._send(B.ALLOCATE_CONSUMER,n)}async acceptProducer(e,t,n){let r={description:e.sdp,sessionId:n};return t.length&&(r.ssrcs=t),this._send(B.ACCEPT_PRODUCER,r)}async changePriorities(e){return this._send(B.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})}async updateDisplayLayout(e){return this._send(B.UPDATE_DISPLAY_LAYOUT,e)}async addMovie(e){return this._send(B.ADD_MOVIE,e)}async updateMovie(e){return this._send(B.UPDATE_MOVIE,e)}async removeMovie(e){return this._send(B.REMOVE_MOVIE,e)}startUrlSharing(e){return this._send(B.START_URL_SHARING,{sharedUrl:e})}stopUrlSharing(){return this._send(B.STOP_URL_SHARING)}async updateRooms(e,t){return this._send(B.UPDATE_ROOMS,{rooms:e,assignRandomly:t})}async activateRooms(e,t){return this._send(B.ACTIVATE_ROOMS,{roomIds:e,deactivate:t})}async switchRoom(e,t){return this._sendRaw(B.SWITCH_ROOM,{toRoomId:e,participantId:t})}async getRooms(e){return this._sendRaw(B.GET_ROOMS,{withParticipants:e})}async removeRooms(e){return this._send(B.REMOVE_ROOMS,{roomIds:e})}async startStream(e){return this._send(B.RECORD_START,e)}async stopStream(e={roomId:null}){return this._send(B.RECORD_STOP,e)}async publishStream(e={roomId:null}){return this._send(B.RECORD_PUBLISH,e)}async getRecordStatus(){return this._send(B.RECORD_GET_STATUS)}async switchTopology(e,t=!1){return this._send(B.SWITCH_TOPOLOGY,{topology:e,force:t})}async requestRealloc(){return this._send(B.REQUEST_REALLOC)}async reportPerfStat(e){return this._send(B.REPORT_PERF_STAT,e)}async reportSharingStat(e){return this._send(B.REPORT_SHARING_STAT,e,!1)}async reportNetworkStat(e){return this._send(B.REPORT_NETWORK_STAT,e,!1)}async chatMessage(e,t=null){return this._send(B.CHAT_MESSAGE,{message:e,participantId:t})}async chatHistory(e){return this._send(B.CHAT_HISTORY,{count:e})}async customData(e,t){return this._send(B.CUSTOM_DATA,{data:e,participantId:t})}async grantRoles(e,t,n){let r={participantId:e,roles:t};return n&&(r.revoke=!0),this._sendRaw(B.GRANT_ROLES,r)}async muteParticipant(e,t,n,r=null){return this._sendRaw(B.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:n,roomId:r})}async enableFeatureForRoles(e,t){return this._sendRaw(B.ENABLE_FEATURE_FOR_ROLES,{feature:e,roles:t})}async pinParticipant(e,t,n){let r={participantId:e,roomId:n};return t&&(r.unpin=!0),this._sendRaw(B.PIN_PARTICIPANT,r)}async updateMediaModifiers(e){return this._send(B.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})}async enableVideoSuspend(e){return this._send(B.ENABLE_VIDEO_SUSPEND,{enabled:e},!1)}async enableVideoSuspendSuggest(e){return this._send(B.ENABLE_VIDEO_SUSPEND_SUGGEST,{enabled:e},!1)}async changeSimulcast(e){return this._send(B.CHANGE_SIMULCAST,e,!1)}async changeOptions(e){return this._send(B.CHANGE_OPTIONS,{options:e})}async getWaitingHall(e=null,t,n=!1){let r={};return e&&(r.fromId=e),t&&(r.count=t),n&&(r.backward=n),this._send(B.GET_WAITING_HALL,r)}async promoteParticipant(e,t=!1){let n={};return e&&(n.participantId=e),t&&(n.demote=t),this._sendRaw(B.PROMOTE_PARTICIPANT,n)}async requestPromotion(e=!1){let t={};return e&&(t.unrequest=e),this._send(B.REQUEST_PROMOTION,t)}async acceptPromotion(e=!1){let t={};return e&&(t.reject=e),this._send(B.ACCEPT_PROMOTION,t)}async feedback(e){return this._sendRaw(B.FEEDBACK,{key:e})}async getHandQueue(){return this._send(B.GET_HAND_QUEUE)}dispose(e=new En){this._terminate(e)}readyToSend(e=!0){this.listenersReady=e,this._handleCachedMessages()}async getParticipantListChunk(e){return this._send(B.GET_PARTICIPANT_LIST_CHUNK,e)}async getParticipants(e){return this._send(B.GET_PARTICIPANTS,{externalIds:e})}getPeerId(){return this.peerId}async startAsr(e){return this._send(B.ASR_START,e)}async stopAsr(e){return this._send(B.ASR_STOP,e)}async requestAsr(e){return this._send(B.REQUEST_ASR,{request:e},!1)}async _send(e,t={},n=!0,r=0){if(t.participantId){let e=j.decomposeParticipantId(t.participantId),n=j.decomposeId(e.compositeUserId);t=Object.assign({},t,{participantId:n.id,participantType:n.type}),e.deviceIdx&&(t.deviceIdx=e.deviceIdx)}return this._sendRaw(e,t,n,r)}async _sendRaw(e,t={},n=!0,r=0){let i=t=>{if(this.disposed)throw new En(e);switch(t.route){case`producer`:this.datachannelCommandsQueue.push(t),this.producerCommandDataChannel?.readyState===Ia&&this._handleCommandsQueue(this.datachannelCommandsQueue);break;case`websocket`:if(this.transport.readyState===null){this._logger?.log(C.SOCKET_ACTION,`not_opened`),this._debug.warn(`[signaling] socket is not opened`),t.reject(Error(`Socket not opened [${e}]`),!0);return}this.transport.readyState>WebSocket.OPEN&&(this._logger?.log(C.SOCKET_ACTION,`invalid_state`),this._debug.warn(`[signaling] socket is not opened, state ${this.transport.readyState}`)),this.websocketCommandsQueue.push(t),this.transport.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((a,o)=>{let s=(t,n=!1)=>{!r||n?o(t):(this._debug.debug(`[signaling] resending a signaling message`,e,u.sequence),r--,i(u))},c=this.sequence++,l=`${e}_${c}`;W.setMark(l);let u={sequence:c,name:e,route:this._isDataChannelCommand(e)?`producer`:`websocket`,statMarkName:l,params:t,responseTimer:0,needResponse:n,resolve:a,reject:s};i(u)})}_isDataChannelCommand(e){return this.producerCommandDataChannelEnabled?e===B.UPDATE_DISPLAY_LAYOUT||e===B.REPORT_PERF_STAT||e===B.REPORT_SHARING_STAT||e===B.REQUEST_ASR||e===B.ENABLE_VIDEO_SUSPEND||e===B.ENABLE_VIDEO_SUSPEND_SUGGEST||e===B.REPORT_NETWORK_STAT||e===B.CHANGE_SIMULCAST:!1}_onOpen(){this._debug.debug(`[signaling] socket opened`),this._logger?.log(C.SOCKET_ACTION,`opened`),this._waitConnectionMessage(),this._logTransportStatSinceMark(this.connectionType===br.RETRY?Sr.RECONNECTED:Sr.CONNECTED)}_onMessage(e){if(e.data===`ping`){this._statPings?.mark(this._getSocketType()),this._markTransportStat(Sr.FAILED_PINGS),L.onSignalingMessage(e.data),this.transport.readyState===WebSocket.OPEN&&this.transport.send(`pong`).catch(e=>this._debug.warn(`[signaling] unable to send pong`,e));return}try{let t=JSON.parse(e.data);L.onSignalingMessage(t),this._handleMessage(t)}catch(t){this._logger?.log(C.SOCKET_ACTION,`parse_error`),this._debug.error(`[signaling] unable to parse message`,t,e.data)}}_handleMessage(e){switch(e.type){case`notification`:this._attachNotificationCallError(e),e.notification===`connection`?(this._debug.debug(`[signaling] signaling connected`,e),this.connected=!0,this.transport.resetReconnectCount(),this.transport.setEndpoint(e.endpoint),e.peerId&&this.peerId!==e.peerId.id&&(this.peerId=e.peerId.id,this.transport.setPeerId(e.peerId.id)),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(G.RECONNECT,e),e.conversation.topology&&this._triggerEvent(G.NOTIFICATION,{type:`notification`,notification:K.TOPOLOGY_CHANGED,topology:e.conversation.topology}),this._resolvePendingRecordCommands(e)),this.lastStamp&&this._handleCachedMessages(),e.recoverMessages?.forEach(e=>{e.notification===K.ACCEPTED_CALL&&e.peerId.id===this.peerId&&e.peerId.type===`WEB_TRANSPORT`||this._handleMessage(e)}),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(G.NOTIFICATION,e);break;case`response`:this._handleCommandResponse(!0,e);break;case`error`:this._handleErrorMessage(e);break;default:this._logger?.log(C.SOCKET_ACTION,`unknown_message`),this._debug.warn(`[signaling] unhandled message`,e)}e.stamp&&(this.lastStamp=e.stamp,this.transport.setLastStamp(e.stamp))}_handleErrorMessage(e){this._logger?.log(C.SOCKET_ACTION,`error-${e.error}`);let t=this._getSocketType(),n=e.error?this._createSignalingCallError(e.error,e.errorCode,t):void 0,r=Va(e,`Unknown signaling error`);switch(this._debug.debug(`[signaling] error message [${e.sequence}]`,e),e.sequence&&this.responseHandlers[e.sequence]&&this._handleCommandResponse(!1,e),e.error){case za.SERVICE_UNAVAILABLE:let i=new O(D.SERVICE_UNAVAILABLE,{callError:n,message:r,remote:!0});this.conversationReject?this.conversationReject(i):this._triggerEvent(G.NOTIFICATION,{notification:K.CLOSED_CONVERSATION,callError:n,reason:D.SERVICE_UNAVAILABLE});break;case za.CONVERSATION_ENDED:this.conversationReject?this.conversationReject(new O(e.reason||x.SIGNALING_FAILED,{callError:n,message:r,remote:!0})):this._triggerEvent(G.NOTIFICATION,{notification:K.CLOSED_CONVERSATION,callError:n,reason:e.reason});break;case za.ILLEGAL_PARTICIPANT_STATE:case za.PARTICIPANT_NOT_FOUND:this._throwError(new O(x.SIGNALING_FAILED,{callError:n,message:r,remote:!0}));break;case za.OBSOLETE_CLIENT:this.conversationReject?.(new O(e.reason||D.OBSOLETE_CLIENT,{callError:n,message:r,remote:!0}));break;case za.INVALID_TOKEN:default:if(e.sequence||t===xr.WEBTRANSPORT)break;if(this.connected)this._throwError(new O(e.reason||x.SIGNALING_FAILED,{callError:n??{scope:`unknown`,description:`signaling-unrecognized-error`},message:r,remote:!0}));else if(!e.sequence){let t=new O(e.reason||x.SIGNALING_FAILED,{callError:n??{scope:`unknown`,description:`signaling-unrecognized-error`},message:r,remote:!0});this.conversationReject?.(t),this.dispose(t)}}}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(G.FAILED,e)}_onError(e){this._logger?.log(C.SOCKET_ACTION,`error`),this._debug.error(`[signaling] signaling error`,e),this._logTransportStat(Sr.FAILED_EXCEPTIONS,{string_value:this._describeErrorEvent(e)})}_describeErrorEvent(e){let t=e,n=t.error instanceof Error?t.error:null,r=[n?.name||t.errorInfo?.name,n?.message||t.errorInfo?.message||t.message].filter(Boolean).join(`: `)||`Unknown error`,i=t.errorInfo?.phase;return(i?`${i}: ${r}`:r).slice(0,La)}_onClose(e){this._logger?.log(C.SOCKET_ACTION,`closed`),this._debug.debug(`[signaling] connection closed`,{code:e.code,reason:e.reason}),this.connected=!1}_terminate(e){if(this.disposed)return!1;this.disposed=!0,this.transport.close(),this._stopWaitConnectionMessage();let t=[...this.websocketCommandsQueue,...this.datachannelCommandsQueue,...Object.values(this.responseHandlers)],n=this.conversationReject;return this.websocketCommandsQueue=[],this.datachannelCommandsQueue=[],this.responseHandlers={},this.incomingCache=[],this.conversationResolve=null,this.conversationReject=null,this.connected=!1,this.listenersReady=!1,this.lastStamp=0,this.producerCommandDataChannelEnabled=!1,this.producerNotificationDataChannel&&(this.producerNotificationDataChannel.onmessage=null,this.producerNotificationDataChannel=null),this.producerCommandDataChannel&&(this.producerCommandDataChannel.onmessage=null,this.producerCommandDataChannel=null),super.setAbortSignal(void 0),this.transport.setAbortSignal(void 0),t.forEach(t=>{window.clearTimeout(t.responseTimer),t.reject(e instanceof En?new En(t.name):e,!0)}),n?.(e),!0}_fail(e){this._terminate(e)&&this._throwError(e)}_isRecordCommand(e){return e===B.RECORD_START||e===B.RECORD_STOP}_resolvePendingRecordCommands(e){if(!M.waitForRecordResponse)return;let t=Object.values(this.responseHandlers).filter(e=>this._isRecordCommand(e.name));if(t.length===0)return;let n=new Map;n.set(null,!!e.conversation?.recordInfo);for(let t of e.rooms?.rooms??[])t.id!==void 0&&n.set(t.id,!!t.recordInfo);for(let e of t){let t=e.params.roomId??null,r=n.get(t)??!1,i=e.name===B.RECORD_START;window.clearTimeout(e.responseTimer),delete this.responseHandlers[e.sequence],this._debug.debug(`[signaling] resolve pending record command [${e.sequence}] via reconnect state`),i===r?e.resolve({type:`response`,sequence:e.sequence,response:e.name}):e.reject(Error(`Recording state mismatch`),!0)}}_handleCommandResponse(t,n){if(!Object.hasOwn(this.responseHandlers,n.sequence)){if(n.participants)for(let e of n.participants)this._triggerEvent(G.NOTIFICATION,{...n,notification:K.PARTICIPANT_ADDED,type:`notification`,participant:e});return}let r=this.responseHandlers[n.sequence];window.clearTimeout(r.responseTimer);let i=W.measureMark(r.statMarkName);i!==null&&this._statSignalingCommands?.mark(r.name,i,this._getSocketType()),this._debug.debug(`[signaling] command response [${n.sequence}]`,n),t?(delete this.responseHandlers[n.sequence],r.resolve(n)):n.type===`error`?(delete this.responseHandlers[n.sequence],this._logger?.log(C.SOCKET_ACTION,`response-error`),r.reject(Error(Va(n,`Response error [${r.name}]`)),!0)):this.transport.readyState===WebSocket.OPEN?(delete this.responseHandlers[n.sequence],this._logger?.log(C.SOCKET_ACTION,`response-timeout`),r.reject(Error(Va(n,`Response timeout [${r.name}]`)))):r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(t,n),e.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){for(;e.length>0;){let t=e.shift();if(this._debug.debug(`[signaling] command send [${t.sequence}]`,`'${t.name}'`,t.params),t.route===`producer`){if(this.producerCommandDataChannel?.readyState!==Ia){t.reject(Error(`Invalid data channel state: ${this.producerCommandDataChannel?.readyState}`));return}t.needResponse?this._startResponseTimer(t):this._resolveCommandWithoutResponse(t);let e=this._serializeBinary(t);e!==null&&this.producerCommandDataChannel.send(e)}else{if(this.transport.readyState!==WebSocket.OPEN){t.reject(Error(`Invalid state or socket already closed`));continue}t.needResponse&&this._startResponseTimer(t),this.transport.send(this._serializeJson(t)).then(()=>{t.needResponse||this._resolveCommandWithoutResponse(t)},e=>{window.clearTimeout(t.responseTimer),delete this.responseHandlers[t.sequence],t.reject(e,!0)})}}}_startResponseTimer(t){t.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{response:t.name,sequence:t.sequence,type:`timeout`}),e.WAIT_RESPONSE_DELAY),this.responseHandlers[t.sequence]=t}_resolveCommandWithoutResponse(e){e.resolve({type:`response`,sequence:e.sequence,response:e.name})}_serializeBinary(e){switch(e.name){case B.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case B.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params);case B.REPORT_SHARING_STAT:return this.producerCommandSerializationService.serializeSharingStatReport(e.sequence,e.params);case B.REQUEST_ASR:return this.producerCommandSerializationService.serializeRequestAsr(e.sequence,e.params);case B.REPORT_NETWORK_STAT:return this.producerCommandSerializationService.serializeNetworkStatReport(e.sequence,e.params);case B.ENABLE_VIDEO_SUSPEND:return this.producerCommandSerializationService.serializeEnableVideoSuspend(e.sequence,e.params);case B.ENABLE_VIDEO_SUSPEND_SUGGEST:return this.producerCommandSerializationService.serializeEnableVideoSuspendSuggest(e.sequence,e.params);case B.CHANGE_SIMULCAST:return this.producerCommandSerializationService.serializeChangeSimulcast(e.sequence,e.params)}return this._debug.warn(`[signaling] cannot get binary data for data channel command: `+e.name),null}_serializeJson(e){let t;t=e.name===B.UPDATE_DISPLAY_LAYOUT?this._convertDisplayLayout(e.params):e.params;let n=Object.assign({command:e.name,sequence:e.sequence},t);return JSON.stringify(n)}_convertDisplayLayout(e){let t=e,n={};for(let e in t)Object.hasOwn(t,e)&&(n[e]=jn(t[e]));return{layouts:n}}_waitConnectionMessage(){let t=this._getSocketType();this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new O(x.SIGNALING_FAILED,{callError:{scope:`network`,source:t,code:`timeout`,description:`connection-timeout`},message:`Unable to connect to the signaling: connection timeout`,remote:!0}))},e.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_onTransportConnecting(e){let t=e.connectionType===br.RETRY?Sr.RECONNECTED:Sr.CONNECTED;this._markTransportStat(t,e.source)}_onTransportFailed(e){switch(e.failure){case Pa.EMPTY_ENDPOINT:this.conversationReject?.(new O(x.SIGNALING_FAILED,{callError:{scope:`internal`,code:`configuration`,description:`signaling-endpoint-missing`},message:e.message,remote:e.remote}));break;case Pa.NETWORK_ERROR:this._logReconnectTimeout(),this._fail(new O(D.NETWORK_ERROR,{callError:{scope:`network`,source:e.source,code:`reconnect-exhausted`,description:`connection-failed`}}));break;case Pa.ABORTED:this._debug.debug(`[signaling] aborted reconnect`),this._fail(new O(D.CANCELED));break}}_onTransportReconnectScheduled(e){this.connectionType=br.RETRY,this._debug.log(`[signaling] reconnect signaling after ${e.delay}ms (${e.count})`),this._logger?.log(C.SOCKET_ACTION,`reconnect`),e.count===1&&(this.reconnectStartedAt=performance.now())}_logReconnectTimeout(){this.reconnectStartedAt!==null&&(this._logTransportStat(Sr.TIMEOUT,{value:Math.round(performance.now()-this.reconnectStartedAt)}),this.reconnectStartedAt=null)}_onTransportConnectionDead(){this._debug.warn(`[signaling] socket is dead, trying to reconnect`),this._logTransportStatSinceMark(Sr.FAILED_PINGS)}_attachNotificationCallError(e){e.callError||!e.reason||e.reason===D.FAILED||e.reason===D.UNKNOWN_ERROR||!Ha.has(e.reason)&&!e.errorCode||(e.callError={scope:`server`,source:this._getSocketType(),code:e.errorCode||`protocol`,description:String(e.reason)})}_createSignalingCallError(e,t,n){let r=Ba[e];if(r)return{scope:`server`,source:n,code:t??`protocol`,description:r}}_getSocketType(){return this.transport.type}_markTransportStat(e,t=this._getSocketType()){let n=Cr[e][t];W.setMark(n)}_logTransportStat(e,t){let n=this._getSocketType(),r=Cr[e][n];this._statAggregator?.logEventualStat({name:r,...t})}_logTransportStatSinceMark(e){let t=this._getSocketType(),n=Cr[e][t];this._statAggregator?.logEventualStatSinceMark({name:n})}},Wa=function(e){return e.INCOMING=`INCOMING`,e.OUTGOING=`OUTGOING`,e.JOINING=`JOINING`,e}(Wa||{}),Ga=function(e){return e.USER=`USER`,e.GROUP=`GROUP`,e.CHAT=`CHAT`,e}(Ga||{}),Ka=function(e){return e.ATTENDEE=`ATTENDEE`,e.HAND_UP=`HAND_UP`,e}(Ka||{}),qa=function(e){return e.ADD_PARTICIPANT=`ADD_PARTICIPANT`,e.RECORD=`RECORD`,e.MOVIE_SHARE=`MOVIE_SHARE`,e}(qa||{}),Ja=function(e){return e.REQUIRE_AUTH_TO_JOIN=`REQUIRE_AUTH_TO_JOIN`,e.AUDIENCE_MODE=`AUDIENCE_MODE`,e.WAITING_HALL=`WAITING_HALL`,e.WAIT_FOR_ADMIN=`WAIT_FOR_ADMIN`,e.ADMIN_IS_HERE=`ADMIN_IS_HERE`,e.ASR=`ASR`,e.FEEDBACK=`FEEDBACK`,e.RECURRING=`RECURRING`,e}(Ja||{});function Ya(e,t){if(e.length!==t.length)return!1;for(let n of e)if(!t.includes(n))return!1;return!0}function Xa(e,t){let n=new Set(e);for(let[e,r]of Object.entries(t))r?n.add(e):n.delete(e);return Array.from(n)}var Za=function(e){return e.UNMUTE=`UNMUTE`,e.MUTE=`MUTE`,e.MUTE_PERMANENT=`MUTE_PERMANENT`,e}(Za||{}),X=function(e){return e.CALLED=`CALLED`,e.ACCEPTED=`ACCEPTED`,e.REJECTED=`REJECTED`,e.HUNGUP=`HUNGUP`,e}(X||{}),Qa=function(e){return e.UPDATE=`UPDATE`,e.REMOVE=`REMOVE`,e.ACTIVATE=`ACTIVATE`,e.TIMEOUT=`TIMEOUT`,e}(Qa||{}),$a=function(e){return e.NO_AVAILABLE_TRACKS=`no-available-tracks`,e.UNKNOWN_ERROR=`unknown-error`,e}($a||{});function eo(e){switch(e){case 1:return`no-available-tracks`;default:return`unknown-error`}}var to=function(e){return e.CREATOR=`CREATOR`,e.ADMIN=`ADMIN`,e}(to||{});function no(e,t){if(e.length!==t.length)return!1;for(let n of e)if(!t.includes(n))return!1;return!0}var ro;(function(e){function t(e){let t=e?.transport??e?.lastEffective??N.WAITING,n={transport:t,stalled:e?.stalled??!1,sessionState:e?.sessionState,sessionStateApplicable:e?.sessionStateApplicable??!1,sessionStateConnectedBySpeaker:e?.sessionStateConnectedBySpeaker??!1,lastEffective:e?.lastEffective??t};return n.lastEffective=r(n),n}e.create=t;function n(e){return e===q.CONNECTED?N.CONNECTED:e===q.CONNECTING||e===q.OPENED?N.CONNECTING:e===q.RECONNECTING?N.RECONNECT:null}e.fromTransportState=n;function r(e){return[N.HANGUP,N.ERROR,N.ONHOLD].includes(e.transport)?e.transport:e.transport===N.RECONNECT||e.transport===N.CONNECTED&&e.stalled?N.RECONNECT:e.sessionStateApplicable&&e.sessionState?.connected===!1?e.sessionStateConnectedBySpeaker&&e.transport===N.CONNECTED?N.CONNECTED:N.CONNECTING:e.transport}e.computeEffective=r;function i(e,t,n=!1){return e.sessionState=t,e.sessionStateConnectedBySpeaker=t?.connected===!1&&n,c(e)}e.setSessionState=i;function a(e,t){return e.transport=t,t!==N.CONNECTED&&(e.sessionStateConnectedBySpeaker=!1),c(e)}e.setTransport=a;function o(e,t){return e.stalled=t,c(e)}e.setStalled=o;function s(e,t){return e.sessionStateApplicable=t,t||(e.sessionStateConnectedBySpeaker=!1),c(e)}e.setSessionStateApplicable=s;function c(e){let t=r(e);return e.lastEffective===t?{status:t,shouldNotify:!1}:(e.lastEffective=t,{status:t,shouldNotify:!0})}})(ro||(ro={}));var io=ro,ao=function(e){return e.USER=`USER`,e.ANONYM=`ANONYM`,e.GROUP=`GROUP`,e}({}),Z;(function(e){function t(e){return e.length?typeof e[0]==`object`?e:e.map(e=>n(e)):[]}e.fromIds=t;function n(e,t=`USER`,n=0){return{id:e,type:t,deviceIdx:n}}e.fromId=n;function r(e,t=!0,n=!1){let r=t?e.decorativeExternalUserId:e.externalId,a=e.deviceIdx??0;if(r)return i(r,a);if(n&&t&&e.externalId)return i(e.externalId,a)}e.fromSignalingParticipant=r;function i(e,t=0){let n=e.type===`ANONYM`?`ANONYM`:`USER`;return{id:e.id,type:n,deviceIdx:t}}e.fromSignaling=i;function a(e){return e.id}e.toSignaling=a;function o(e){let t=e.deviceIdx||0;return`{"id":"${e.id}","type":"${e.type}","deviceIdx":${t}}`}e.toString=o;function s(e,t=`USER`,r=0){return o(n(e,t,r))}e.fromIdToString=s;function c(e){try{return JSON.parse(e)}catch{throw Error(`Failed to parse ExternalId from string '${e}'`)}}e.fromString=c;function l(e,t){return e.id===t.id&&e.type===t.type&&e.deviceIdx===t.deviceIdx}e.compare=l;function u(e){return e?.deviceIdx||0}e.getDeviceIdx=u})(Z||(Z={}));function oo(e){try{return btoa(JSON.stringify(e))}catch(t){R.warn(`WaitingParticipant: failed convert to string`,e,t)}return null}function so(e){try{return JSON.parse(atob(e))}catch(t){R.warn(`WaitingParticipant: failed convert from string`,e,t)}return null}var co=(e,t)=>j.objectReduce(e,(e,n,r)=>(n===t&&e.push(r),e),[]);function lo(e){if(e.conversation?.muteStates)return e.conversation.muteStates;if(e.muteState&&e.muteOptions)return e.muteOptions.reduce((t,n)=>(t[n]=e.muteState,t),{})}function uo(e,t){switch(e){case S.AUDIO:return!!t.isAudioEnabled;case S.AUDIO_SHARING:return!!t.isAudioSharingEnabled;case S.VIDEO:return!!t.isVideoEnabled;case S.SCREEN_SHARING:return!!t.isFastScreenSharingEnabled||!!t.isScreenSharingEnabled;default:return!1}}function fo(e,t){return j.objectReduce(e,(e,n,r)=>{switch(n){case Za.MUTE:case Za.MUTE_PERMANENT:uo(r,t)||(e[r]=n);break;default:e[r]=n;break}return e},{})}function po(e){let{muteStates:t={},mediaSettings:n}=e;return fo(t,n)}function mo(e,t){let n=e.conversation.participants.find(t=>j.comparePeerId(t.peerId,e.peerId));if(!n)return t;let{mediaSettings:r}=n;return fo(t,r)}function ho(e){if(!e)return null;let t=Array.from(new Set((e.urls??[]).map(e=>e.trim()).filter(e=>e.length>0)));return t.length?{...e,urls:t}:null}function go(e,t){let n=[],r=ho(e),i=ho(t);if(r&&n.push(r),i){let e=[...i.urls];e.push(`${e[e.length-1]}?transport=tcp`),n.push({...i,urls:e})}return n}function _o(e,t){let n=new Uint8Array(t),r=0,i=0;for(;r<e.length&&i<t;){let a=e[r++],o=a>>4,s=a&15;if(o===15){let t;do t=e[r++],o+=t;while(t===255)}for(let a=0;a<o&&!(i>=t);a++)n[i++]=e[r++];if(r>=e.length||i>=t)break;let c=e[r]|e[r+1]<<8;if(r+=2,s===15){let t;do t=e[r++],s+=t;while(t===255)}s+=4;let l=i-c;for(let e=0;e<s&&!(i>=t);e++)n[i++]=n[l+e]}return n}function vo(e){let t,n=!1,r,i=async()=>{let t=!1,i;for(;n;){let a=r;n=!1;try{await e(a),t=!1}catch(e){t=!0,i=e}!t&&n&&Object.is(r,a)&&(n=!1)}if(t)throw i};return e=>(r=e,n=!0,t??(t=i().finally(()=>{t=void 0})),t)}var yo=class{constructor(e,t=R,n=null){h(this,`_fixNoPacketsApplied`,!1),h(this,`_fixNoPacketsChecked`,!1),h(this,`_fixTooManyPacketsApplied`,!1),h(this,`_fixTooManyPacketsSucceeded`,!1),h(this,`_fixTooManyPacketsFailed`,!1),h(this,`_fixTooManyPacketsTime`,void 0),h(this,`_mediaSource`,void 0),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_lastPacketsSent`,void 0),h(this,`_lastPacketsSentTime`,void 0),h(this,`_toggleAudioPromise`,null),h(this,`_fixNoPacketsAppliedVideo`,!1),this._mediaSource=e,this._debug=t,this._logger=n}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,this._logger?.log(C.ERROR,`audio_device_recover_${e.bandwidth?`success`:`fail`}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&e.packetsSent>0&&(this._fixNoPacketsApplied=!0,this._logger?.log(C.ERROR,`audio_device_recover`),this._debug.log(`[AudioFix] Trying to fix RV (no packets)`),this._toggleAudioPromise=this._mediaSource.toggleAudio(T.getMicrophonePermissionState()!==`denied`),this._toggleAudioPromise.catch(()=>void 0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=t,this._lastPacketsSent=e.packetsSent);else if(t-this._lastPacketsSentTime>500){let n=(e.packetsSent-this._lastPacketsSent)*1e3/(t-this._lastPacketsSentTime);this._lastPacketsSentTime=t,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?n>75?(this._debug.log(`[AudioFix] Failed to fix RV`),this._logger?.log(C.ERROR,`audio_device_recover_rv_fail`),this._fixTooManyPacketsFailed=!0):t-this._fixTooManyPacketsTime>6e4&&(this._debug.log(`[AudioFix] Fixed RV`),this._logger?.log(C.ERROR,`audio_device_recover_rv_success`),this._fixTooManyPacketsSucceeded=!0):n>75&&(this._fixTooManyPacketsApplied=!0,this._logger?.log(C.ERROR,`audio_device_recover`),this._debug.log(`[AudioFix] Trying to fix RV (too many packets)`),this._mediaSource.toggleAudio(!0).catch(e=>{this._debug.warn(`[AudioFix] Failed to fix RV (too many packets)`,e)}),this._fixTooManyPacketsTime=t)}}fix(e){if(!this._mediaSource)return;let t=e.find(e=>e.kind===k.audio);t&&(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}fixVideo(e){if(!this._mediaSource||this._fixNoPacketsAppliedVideo||!this._toggleAudioPromise)return;let t=e.find(e=>e.kind===k.video);t&&!t.bandwidth&&(this._fixNoPacketsAppliedVideo=!0,this._toggleAudioPromise.then(()=>{if(this._mediaSource.mediaSettings.isVideoEnabled)return this._mediaSource.toggleVideo(!0)}).catch(e=>{this._debug.warn(`[AudioFix] Failed to fix RV (no packets): video restart`,e)}))}},bo=class{constructor(e,t=!1,n=R,r=null){h(this,`_audioElement`,null),h(this,`_debug`,void 0),h(this,`_preparedAudioElement`,void 0),h(this,`_audioTracks`,new Map),h(this,`_allowMultipleTracks`,void 0),h(this,`_volume`,1),h(this,`_features`,{setSinkId:!!Audio.prototype.setSinkId}),h(this,`_statFirstMediaReceived`,void 0),h(this,`_logger`,void 0),this._statFirstMediaReceived=e,this._allowMultipleTracks=t,this._debug=n,this._logger=r,this._preparedAudioElement=this._prepareAudioElement()}add(e,t){this._allowMultipleTracks||this._clearTracks();let n=this._audioTracks.get(e);n&&n!==t&&(this._removeTrackFromAudioElement(n),n.stop()),this._audioTracks.set(e,t),this._audioElement?this._addTrackToAudioElement(t):this._initAudioElement()}remove(e,t){let n=this._audioTracks.get(e);if(!n){t.stop();return}if(n!==t){t.stop();return}if(!this._allowMultipleTracks){this.destroy();return}this._removeTrackFromAudioElement(t),t.stop(),this._audioTracks.delete(e),this._audioTracks.size||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._audioElement&&(this._audioElement.volume=this._volume)}destroy(){!this._audioElement&&!this._audioTracks.size||(this._stopAudioElement(),this._audioElement=null,this._audioTracks.clear())}async changeOutput(){try{if(!this._features.setSinkId)throw Error(`Feature "setSinkId" is not supported`);if(!this._audioElement)return;let e=T.getSavedOutput();e&&await this._audioElement.setSinkId?.(e.deviceId)}catch(e){throw this._logger?.log(C.ERROR,`change_output`),this._debug.error(`[audio] Output change failed`,e),e}}_getTracks(){return Array.from(this._audioTracks.values())}_initAudioElement(){if(M.muteMode)return;let e=this._getTracks();if(!e.length)return;let t=this._preparedAudioElement??this._createAudioElement();t.muted=!1,t.volume=this._volume,t.preload=`auto`;let n=()=>{this._debug.warn(`[audio] Error on play audio`),L.onAutoplayError()},r=e=>{this._debug.debug(`[audio] Play audio`),t.srcObject=null,t.srcObject=new MediaStream(e),t.load();let r=t.play();r&&r.catch(n)},i=()=>{this._debug.debug(`[audio] Recover audio playback`);let e=this._getTracks();e.length?r(e):this._debug.warn(`[audio] Broken audio tracks`)};t.onpause=i,t.onstalled=i,t.onerror=i,t.onloadeddata=()=>{this._statFirstMediaReceived.measure()},r(e),this._audioElement=t;let a=T.getSavedOutput()?.deviceId;a&&t.setSinkId?.(a).catch(e=>{this._debug.warn(`[audio] Failed to set output device '${a}'`,e)})}_stopAudioElement(){this._audioElement&&(this._audioElement.onpause=null,this._audioElement.onstalled=null,this._audioElement.onerror=null,this._audioElement.onloadeddata=null,this._audioElement.pause(),this._audioElement.srcObject=null);for(let e of this._audioTracks.values())e.stop()}_createAudioElement(){let e=T.browserName()!==`Safari`||T.isMobile()||M.safariAudioElement;return document.createElement(e?`audio`:`video`)}_prepareAudioElement(){if(M.muteMode||T.browserName()!==`Safari`||T.isMobile())return null;let e=this._createAudioElement();return e.load(),e}_addTrackToAudioElement(e){if(!this._audioElement)return;this._debug.debug(`[audio] Adding track ${e}`);let t=this._audioElement.srcObject;t||(t=new MediaStream,this._audioElement.srcObject=t),t.addTrack(e)}_removeTrackFromAudioElement(e){this._audioElement?.srcObject&&(this._debug.debug(`[audio] Removing track ${e}`),this._audioElement.srcObject.removeTrack(e))}_clearTracks(){for(let e of this._audioTracks.values())this._removeTrackFromAudioElement(e),e.stop();this._audioTracks.clear()}};function xo(e,t){e||Co(t,`response-empty`),e.id||Co(t,`id-empty`),e.endpoint||Co(t,`endpoint-empty`),!So(e.stun_server)&&!So(e.turn_server)&&Co(t,`ice-servers-empty`)}function So(e){return Array.isArray(e?.urls)&&e.urls.length>0}function Co(e,t){let n=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),r=e===`fastStart`||e===`fastJoin`;throw new O(r?e===`fastStart`?D.FAST_START_ERROR:D.FAST_JOIN_ERROR:D.UNKNOWN_ERROR,{message:`Invalid ${e} response: ${t}`,callError:r?{scope:`external`,source:`api`,code:`invalid-response`,description:`${n}-${t}`}:{scope:`server`,source:`api`,code:`invalid-response`,description:`${n}-${t}`}})}var wo=90,To=3,Eo=class extends b{constructor(e=R){super(),h(this,`_lastMemoryStat`,{percent:0,bytes:0}),h(this,`_debug`,void 0),this._debug=e}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(e=>{e.userId=(typeof e.userId==`string`&&t[e.userId]||null)?.externalId}),L.onStatistics(e,this._lastMemoryStat)}_calcMemory(){let e=window?.performance?.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),n=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>wo?this._debug.warn(`High memory usage: ${t}% (${n} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=To)&&(this._debug.debug(`Memory usage: ${t}% (${n} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}},Do=class{constructor({api:e,debug:t,getParticipants:n,isMe:r,updateDisplayLayout:i,onNonFatalError:a}){h(this,`_api`,void 0),h(this,`_debug`,void 0),h(this,`_getParticipants`,void 0),h(this,`_isMe`,void 0),h(this,`_updateDisplayLayout`,void 0),h(this,`_onNonFatalError`,void 0),h(this,`_requestedLayouts`,{}),h(this,`_uncertainLayouts`,{}),h(this,`_pendingRequests`,null),h(this,`_pendingPromises`,[]),h(this,`_lastRequests`,null),h(this,`_timer`,null),h(this,`_inFlight`,!1),h(this,`_lastFlushAt`,null),h(this,`_generation`,0),h(this,`_forceNextFlush`,!1),this._api=e,this._debug=t,this._getParticipants=n,this._isMe=r,this._updateDisplayLayout=i,this._onNonFatalError=a}request(e){this._pendingRequests=e.slice(),this._lastRequests=e.slice();let t=new Promise((e,t)=>{this._pendingPromises.push({resolve:e,reject:t})});return this._schedule(),t}resend(){this._lastRequests&&(this._pendingRequests=this._lastRequests.slice(),this._forceNextFlush=!0,this._schedule())}cleanupParticipant(e){for(let t of Object.keys(this._requestedLayouts))Fn(t).participantId===e&&delete this._requestedLayouts[t];for(let t of Object.keys(this._uncertainLayouts))Fn(t).participantId===e&&delete this._uncertainLayouts[t]}clear(){this._generation++,this._timer!==null&&(window.clearTimeout(this._timer),this._timer=null),this._pendingPromises.forEach(({resolve:e})=>e()),this._requestedLayouts={},this._uncertainLayouts={},this._pendingRequests=null,this._pendingPromises=[],this._lastRequests=null,this._inFlight=!1,this._lastFlushAt=null,this._forceNextFlush=!1}_schedule(){if(this._inFlight||this._timer!==null)return;let e=this._lastFlushAt===null?0:Math.max(0,M.requestDisplayLayoutThrottleMs-(Date.now()-this._lastFlushAt));this._timer=window.setTimeout(()=>{this._timer=null,this._flush()},e)}async _flush(){if(this._inFlight||!this._pendingRequests)return;this._inFlight=!0;let e=this._generation,t=this._pendingRequests,n=this._pendingPromises;this._pendingRequests=null,this._pendingPromises=[];let r={};try{let i=this._getRequestLayouts(t);if(!i){n.forEach(({resolve:e})=>e());return}r=i;let a=this._forceNextFlush||Object.keys(this._uncertainLayouts).length>0;this._forceNextFlush=!1;let o=this._getDiff(r,a);o.length&&await this._updateDisplayLayout(o),e===this._generation&&(this._requestedLayouts=r,this._uncertainLayouts={}),n.forEach(({resolve:e})=>e())}catch(t){e===this._generation?(this._uncertainLayouts={...this._uncertainLayouts,...r},n.forEach(({reject:e})=>e(t))):n.forEach(({resolve:e})=>e())}finally{e===this._generation&&(this._lastFlushAt=Date.now(),this._inFlight=!1,this._pendingRequests&&this._schedule())}}_getRequestLayouts(e){let t={},n=[],r=this._getParticipants();for(let i of e){let e=typeof i.uid==`object`?i.uid:Z.fromId(i.uid),a=this._api.getCachedParticipantIdByExternalId(e);if(!a){this._debug.log(`Unknown participant external ID ${typeof i.uid==`object`?Z.toString(i.uid):i.uid}`),n.push(e.id);continue}if(!r[a]&&!this._isMe(a))continue;let o=Pn({participantId:a,mediaType:i.mediaType,streamName:i.streamName});t[o]={uid:i.uid,mediaType:i.mediaType,width:i.width,height:i.height,fit:i.cover?`cv`:`cn`,...i.priority===void 0?{}:{priority:i.priority},...i.streamName===void 0?{}:{streamName:i.streamName}}}return n.length?(this._onNonFatalError(`Participant ID mapping not found for external IDs "${Array.from(new Set(n)).join(`", "`)}" while handling requestDisplayLayout`),null):t}_getDiff(e,t=!1){let n=[];if(t){let t={...this._requestedLayouts,...this._uncertainLayouts};n.push(...Object.values(e));for(let[r,i]of Object.entries(t))e[r]||n.push({uid:i.uid,mediaType:i.mediaType,stopStream:!0,...i.streamName===void 0?{}:{streamName:i.streamName}});return n}for(let[t,r]of Object.entries(e)){let e=this._requestedLayouts[t];(!e||this._isChanged(e,r))&&n.push(r)}for(let[t,r]of Object.entries(this._requestedLayouts))e[t]||n.push({uid:r.uid,mediaType:r.mediaType,stopStream:!0,...r.streamName===void 0?{}:{streamName:r.streamName}});return n}_isChanged(e,t){let n=e,r=t;return n.width!==r.width||n.height!==r.height||n.fit!==r.fit||n.priority!==r.priority}},Oo=44100,ko=class{constructor(e,t){h(this,`_analyser`,null),h(this,`_gainNode`,null),h(this,`_fftBins`,null),h(this,`_mediaStreamSource`,null),h(this,`_lastSmoothedLevel`,0),h(this,`_trackId`,void 0),h(this,`_track`,void 0),h(this,`_stream`,void 0),this._trackId=e,this._track=t,this._stream=new MediaStream([t]);try{let e=T.getAudioContext();this._analyser=e.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,T.browserName()===`Safari`&&(this._gainNode=e.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(e.destination),this._analyser.connect(this._gainNode)),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=e.createMediaStreamSource(this._stream),this._mediaStreamSource.connect(this._analyser)}catch{}}get track(){return this._track}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=Oo/this._fftBins.length,t=Math.ceil(M.voiceParams.minFreq/e),n=Math.floor(M.voiceParams.maxFreq/e);return this._fftBins.subarray(t,n)}getLevel(){let e=this._getBins(),t=e.reduce((e,t)=>e+t,0)/e.length/255,n=this._lastSmoothedLevel*M.voiceParams.smoothing+t*(1-M.voiceParams.smoothing);return this._lastSmoothedLevel=n,{real:t,smoothed:n}}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),this._stream.removeTrack(this._track)}},Ao=class extends b{constructor(e){super(),h(this,`_detector`,null),h(this,`_interval`,null);let t=()=>{this._detector&&L.onLocalVolume(this._detector.getLevel().real,e.mediaSettings.isAudioEnabled),this._interval=window.setTimeout(t,M.voiceParams.interval)};this._interval=window.setTimeout(t,M.voiceParams.interval);let n=()=>{let t=e.getSendAudioTrack();t&&this.init(t)};this.subscribe(e,Yt.SOURCE_CHANGED,t=>{t.kind===k.audio&&e.mediaSettings.isAudioEnabled&&n()}),this.subscribe(e,Yt.SOURCE_READY,n),n()}init(e){this._stopDetector(),this._detector=new ko(`local`,e.clone())}_stopDetector(){this._detector&&(this._detector.track.stop(),this._detector.destroy(),this._detector=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}},jo=class{constructor(e,t=R){h(this,`processor`,void 0),h(this,`queue`,[]),h(this,`isProcessing`,!1),h(this,`_debug`,void 0),this.processor=e,this._debug=t}add(e){this.queue.push(e),this.processQueue()}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length;){let e=this.queue.shift();if(e)try{await this.processor(e)}catch{this._debug.error(`Can't process message ${JSON.stringify(e)}`)}}this.isProcessing=!1}}},Mo=function(e){return e.VOLUMES_DETECTED=`VOLUMES_DETECTED`,e}({}),No=class extends b{constructor(e){super(),h(this,`_detectors`,new Map),h(this,`_interval`,null),h(this,`_activeParticipants`,void 0),h(this,`_removedParticipants`,void 0),h(this,`_topology`,void 0),this._topology=e.getTopology(),this.subscribe(e,Y.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,Y.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,Y.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,Y.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),this._destroyDetectors()}_onRemoteTrackAdded(e,t,n){if(n.kind===k.audio&&(this._detectors.get(e)?.destroy(),this._detectors.set(e,new ko(e,n)),!this._interval)){let e=()=>{this._collectVolumes(),this._interval=window.setTimeout(e,M.voiceParams.interval)};this._interval=window.setTimeout(e,M.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,n){if(n.kind!==k.audio)return;let r=this._detectors.get(e);!r||r.track!==n||(r.destroy(),this._detectors.delete(e))}_collectVolumes(){if(!this._detectors.size)return;let e={};if(this._topology===J.SERVER){if(this._activeParticipants)for(let t of this._activeParticipants){let n=this._getAudioTrackLevelByParticipantId(t);n&&(e[t]=n)}if(this._removedParticipants){for(let t of this._removedParticipants)e[t]={real:0,smoothed:0};this._removedParticipants=null}}else for(let[t,n]of this._detectors.entries())e[t]=n.getLevel();this._triggerEvent(`VOLUMES_DETECTED`,e)}_getAudioTrackLevelByParticipantId(e){let t=this._detectors.get(Yr.AUDIO_MIX);return t?t.getLevel():this._getTransparentAudioLevelByParticipantId(e)}_getTransparentAudioLevelByParticipantId(e){if(!this._activeParticipants?.includes(e))return null;let t=null;return this._detectors.forEach((e,n)=>{if(!n.startsWith(`${Yr.TRANSPARENT_AUDIO_TRACK_PREFIX}-`))return;let r=e.getLevel();(!t||r.real>t.real)&&(t=r)}),t}_onSignalledActiveParticipants(e){this._removedParticipants=this._activeParticipants?.filter(t=>!e.includes(t))??null,this._activeParticipants=e}_onTopologyChanged(e){this._topology=e,this._destroyDetectors(),e===J.DIRECT&&(this._activeParticipants=null,this._removedParticipants=null)}_destroyDetectors(){this._detectors.forEach(e=>{e.destroy()}),this._detectors.clear()}},Po=function(e){return e.SPEAKER_CHANGED=`SPEAKER_CHANGED`,e}({}),Fo=class extends b{constructor(e,t,n){super(),h(this,`_speakerId`,null),h(this,`_serverSideSpeakerDetection`,!1),this._serverSideSpeakerDetection=n===J.SERVER,this.subscribe(e,Mo.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,Y.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,Y.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,n=null;if(Object.keys(e).forEach(r=>{let i=e[r].smoothed;i>t&&i>M.voiceParams.threshold&&(t=i,n=r)}),n&&n!==this._speakerId){let r=this._speakerId&&Object.hasOwn(e,this._speakerId)?e[this._speakerId].smoothed:0;t>r*M.voiceParams.speakerLevelMultiplier&&(this._speakerId=n,this._triggerEvent(`SPEAKER_CHANGED`,n))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent(`SPEAKER_CHANGED`,e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e===J.SERVER}},Io=15e3,Lo=15e3,Ro=class extends b{constructor(e,t,n,r=R,i=null){super(),h(this,`_transport`,void 0),h(this,`_volumes`,{}),h(this,`_participants`,{}),h(this,`_debug`,void 0),h(this,`_logger`,void 0),h(this,`_connectionTimeout`,0),h(this,`_connectionTimeoutSuppressed`,!1),h(this,`_volumeTimeout`,0),this._transport=e,this._participants=n,this._debug=r,this._logger=i,this.subscribe(e,Y.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,Mo.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)}onParticipantHoldChanged(){this._connectionTimeout||!this._connectionTimeoutSuppressed||this._reportConnectionTimeout()}_getConnectionTimeout(){return this._transport.getTopology()===J.DIRECT?Io:M.specListenerParams.connectionTimeout}_getVolumeTimeout(){return this._transport.getTopology()===J.DIRECT?Lo:M.specListenerParams.volumeTimeout}_onTransportStateChanged(e,t){t===q.OPENED&&(this._connectionTimeout||(this._connectionTimeoutSuppressed=!1,this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),this._getConnectionTimeout()))),t===q.CONNECTED&&(this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),this._getVolumeTimeout())),this._volumeTimeout&&(window.clearTimeout(this._volumeTimeout),this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),this._getVolumeTimeout()))),t===q.FAILED&&this._connectionTimeout&&(this._debug.warn(`Transport failed, send callSpecError`),this._logger?.log(C.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(){this._reportConnectionTimeout(),this._connectionTimeout=0}_reportConnectionTimeout(){let e=!1,t=!1;Object.entries(this._transport.getStates()).forEach(([n,r])=>{if(r!==q.CONNECTED){if(this._participants[n]?.isOnHold){e=!0;return}t=!0}}),this._connectionTimeoutSuppressed=e&&!t,t&&(this._debug.warn(`There is not connected transport, send callSpecError`),this._logger?.log(C.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0||this._participants[t]?.isOnHold)return;let n=`UNKNOWN`,r=this._participants[t];r&&r.platform&&(n=r.platform),e.indexOf(n)<0&&(e.push(n),this._logger?.log(C.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${n}`))}),e.length&&this._debug.warn(`There is silent participant, send callSpecError`),this._volumeTimeout=0}},zo=function(e){return e[e.PARAM_SESSION_EXPIRED=102]=`PARAM_SESSION_EXPIRED`,e[e.PARAM_SESSION_KEY=103]=`PARAM_SESSION_KEY`,e[e.PARAM_SIGNATURE=104]=`PARAM_SIGNATURE`,e[e.AUTH_LOGIN=401]=`AUTH_LOGIN`,e}(zo||{});function Bo(e){return e===102||e===103||e===104}var Vo,Ho=`ok-calls-sdk-stats`,Uo=1,Wo=`events`,Go=100,Ko=5e3,qo=10080*60*1e3,Jo=5e3,Yo=6e4,Q=class e{static isSupported(){return e._supported}static async append(t){let n=await e._open();if(!n)return null;let r=await e._runTransaction(n,`readwrite`,e=>{let n=e.add(t);return new Promise(e=>{n.onsuccess=()=>e(n.result)})}).catch(e=>(R.error(`[StatQueue] failed to append event`,e),null));return r===null?null:(e._appendsSinceEvictCheck+=1,e._appendsSinceEvictCheck>=Go&&(e._appendsSinceEvictCheck=0,await e.evictToLimit(Ko)),r)}static async fillDelta(t,n){if(t.length===0)return;let r=await e._open();if(r)return e._runTransaction(r,`readwrite`,e=>new Promise(r=>{let i=t.length;for(let a of t){let t=e.get(a);t.onsuccess=()=>{let a=t.result;a&&typeof a.delta!=`number`&&e.put({...a,delta:n}),--i,i===0&&r()}}})).catch(e=>{R.error(`[StatQueue] failed to fill delta`,e)})}static async count(){let t=await e._open();return t?e._runTransaction(t,`readonly`,e=>{let t=e.count();return new Promise(e=>{t.onsuccess=()=>e(t.result)})}).catch(e=>(R.error(`[StatQueue] failed to count events`,e),0)):0}static async readOldest(t,n){let r=await e._open();return r?e._runTransaction(r,`readonly`,e=>{let r=e.index(`by_uid`).getAll(IDBKeyRange.only(t),n);return new Promise(e=>{r.onsuccess=()=>e(r.result)})}).catch(e=>(R.error(`[StatQueue] failed to read events`,e),[])):[]}static async remove(t){if(t.length===0)return;let n=await e._open();if(n)return e._runTransaction(n,`readwrite`,e=>{t.forEach(t=>e.delete(t))}).catch(e=>{R.error(`[StatQueue] failed to remove events`,e)})}static async listUids(){let t=await e._open();return t?e._runTransaction(t,`readonly`,e=>{let t=e.index(`by_uid`).openKeyCursor(null,`nextunique`),n=[];return new Promise(e=>{t.onsuccess=()=>{let r=t.result;if(!r){e(n);return}n.push(r.key),r.continue()}})}).catch(e=>(R.error(`[StatQueue] failed to list uids`,e),[])):[]}static async evictToLimit(t){let n=await e._open();if(!n)return;let r=1e3;for(;r>0;)if(--r,!await e._runTransaction(n,`readwrite`,async n=>{if(await new Promise(e=>{let t=n.count();t.onsuccess=()=>e(t.result)})<=t)return!1;let r=await e._readOldestRecord(n);return r?r.vcid===null?(n.delete(r.id),!0):(await e._deleteConversation(n,r.vcid),!0):!1}).catch(e=>(R.error(`[StatQueue] failed to evict events`,e),!1)))return}static async evictOlderThan(t,n=Date.now()){let r=await e._open();if(!r)return;let i=n-t;return e._runTransaction(r,`readwrite`,async t=>{let n=new Set;await new Promise(e=>{let r=t.openCursor();r.onsuccess=()=>{let t=r.result;if(!t){e();return}let a=t.value;a.ts<i&&(a.vcid===null?t.delete():n.add(a.vcid)),t.continue()}});for(let r of n)await e._deleteConversation(t,r)}).catch(e=>{R.error(`[StatQueue] failed to evict stale events`,e)})}static async __resetForTests(){if(e._appendsSinceEvictCheck=0,e._lastOpenFailureAt=null,e._supported=e._checkSupport(),e._dbName===Ho&&(e._dbName=`${Ho}-test-${Math.random().toString(36).slice(2)}`,e._close()),e._supported){let t=await e._open();t&&await e._runTransaction(t,`readwrite`,e=>{e.clear()}).catch(e=>{R.error(`[StatQueue] failed to reset storage`,e)})}e._close()}static _checkSupport(){return typeof window<`u`&&!!window.indexedDB}static _open(){if(!e._checkSupport())return e._supported=!1,Promise.resolve(null);if(e._dbPromise)return e._dbPromise;if(e._lastOpenFailureAt!==null&&Date.now()-e._lastOpenFailureAt<Yo)return Promise.resolve(null);let t=!1,n=new Promise(n=>{let r=(r,i)=>{t||(t=!0,R.error(r,i),e._supported=!1,e._dbPromise=null,e._lastOpenFailureAt=Date.now(),n(null))},i;try{i=window.indexedDB.open(e._dbName,Uo)}catch(e){r(`[StatQueue] storage is not accessible`,e);return}let a=window.setTimeout(()=>r(`[StatQueue] storage opening timed out`),Jo);i.onupgradeneeded=()=>{e._createSchema(i.result)},i.onsuccess=()=>{if(window.clearTimeout(a),t){i.result.close();return}t=!0,e._db=i.result,e._supported=!0,e._lastOpenFailureAt=null,e._db.onversionchange=()=>e._close(),e._db.onclose=()=>e._close(),n(e._db)},i.onerror=()=>{window.clearTimeout(a),r(`[StatQueue] failed to open storage`,i.error)},i.onblocked=()=>{R.error(`[StatQueue] storage opening is blocked`)}});return t||(e._dbPromise=n),n}static _close(){e._db&&(e._db.close(),e._db=null),e._dbPromise=null}static _createSchema(e){if(e.objectStoreNames.contains(Wo))return;let t=e.createObjectStore(Wo,{keyPath:`id`,autoIncrement:!0});t.createIndex(`by_uid`,`uid`,{unique:!1}),t.createIndex(`by_vcid`,`vcid`,{unique:!1})}static _runTransaction(e,t,n){return new Promise((r,i)=>{let a=e.transaction(Wo,t),o;a.oncomplete=()=>r(o),a.onerror=()=>i(a.error),a.onabort=()=>i(a.error),Promise.resolve(n(a.objectStore(Wo))).then(e=>{o=e}).catch(e=>{try{a.abort()}catch{}i(e)})})}static _readOldestRecord(e){let t=e.openCursor();return new Promise(e=>{t.onsuccess=()=>e(t.result?t.result.value:null)})}static _deleteConversation(e,t){let n=e.index(`by_vcid`).getAllKeys(IDBKeyRange.only(t));return new Promise(t=>{n.onsuccess=()=>{n.result.forEach(t=>e.delete(t)),t()}})}};Vo=Q,h(Q,`_db`,null),h(Q,`_dbPromise`,null),h(Q,`_dbName`,Ho),h(Q,`_supported`,Vo._checkSupport()),h(Q,`_appendsSinceEvictCheck`,0),h(Q,`_lastOpenFailureAt`,null);var Xo=null,Zo=null,Qo=64*1024;function $o(){Xo=null,Zo=null}function es(e){return e?.endsWith(`/`)?e.slice(0,-1):e}async function ts(e=null,t){let n=es(e??M.apiBaseUrl);if(n)return n;if((t??M.apiEnv)!==`AUTO`)return M.apiEndpoint(t);try{let e=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),t=(await(await fetch(e,{method:`GET`,mode:`cors`,cache:`no-cache`})).json())?.Answer[0]?.data;if(!t)throw Error(`Wrong DNS response`);return R.debug(`Resolved API endpoint`,t),t}catch(e){return R.warn(`Failed to resolve API endpoint using DNS, default is used`,e),M.apiEndpoint(t)}}async function ns(){return Xo||Zo||(Zo=ts(),Xo=await Zo,Zo=null,Xo)}async function rs(e,t={},n=!1){if(!window.Blob||!window.navigator.sendBeacon)return;await ns();let r=ls(e,t,n),i=new window.Blob([r],{type:`application/x-www-form-urlencoded`});window.navigator.sendBeacon(`${Xo}/fb.do`,i)}async function is(e,t={},n=!1,r){return await ns(),os(ls(e,t,n),r)}async function as(e,t={},n=!1){await ns();let r=ls(e,t,n);return os(r,void 0,new Blob([r]).size<=Qo)}async function os(e,t,n=!1){let r=`${t??Xo}/fb.do`,i=new AbortController,a=new O(x.NETWORK,{callError:{scope:`network`,source:`api`,code:`timeout`,description:`request-timeout`}}),o=setTimeout(()=>i.abort(a),M.apiTimeout);try{let t=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:e,signal:i.signal,...n&&{keepalive:!0}}),a=await t.text(),o;try{o=JSON.parse(a)}catch{o={result:a}}if(!t.ok&&!ss(o))throw new O(x.API,{callError:{scope:`server`,source:`api`,code:`http-${t.status}`,description:`http-error`}});if(ss(o))throw o;return o}catch(e){throw e instanceof O?e:i.signal.aborted?a:ss(e)?e:new O(x.NETWORK,{callError:{scope:`network`,source:`api`,code:`fetch-failed`,description:`request-failed`}})}finally{clearTimeout(o)}}function ss(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.error_code==`number`&&typeof t.error_msg==`string`}async function cs(e,t){try{let n=await fetch(e,{method:`POST`,body:t});if(!n.ok)throw Error(`HTTP error! status: ${n.status}`);let r=await n.text();R.debug(`Form data sent successfully`,r)}catch(e){throw R.warn(`Failed to send form data`,e),e}}function ls(e,t={},n=!1){t.method=e,t.format=`JSON`,t.application_key||(t.application_key=M.apiKey),n||(y.sessionKey?t.session_key=y.sessionKey:y.accessToken&&(t.access_token=y.accessToken));for(let[e,n]of Object.entries(t))typeof n==`object`&&(t[e]=JSON.stringify(n));let r=``;for(let[e,n]of Object.entries(t))r&&(r+=`&`),r+=`${e}=${encodeURIComponent(n)}`;return r}var us=`sessions`,ds=5,fs=class e{static remember(t,n){let r=e._read();r[String(t)]={...n,savedAt:Date.now()};let i=Object.keys(r);i.length>ds&&i.sort((e,t)=>r[e].savedAt-r[t].savedAt).slice(0,i.length-ds).forEach(e=>delete r[e]),e._write(r)}static get(t){return e._read()[String(t)]??null}static forget(t){let n=e._read();String(t)in n&&(delete n[String(t)],e._write(n))}static prune(t=Date.now()){let n=e._read(),r=!1;Object.keys(n).forEach(e=>{t-n[e].savedAt>6048e5&&(delete n[e],r=!0)}),r&&e._write(n)}static currentEndpoint(){return String(es(M.apiBaseUrl)||M.apiEndpoint())}static _read(){let t=st.get(us);if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};return Object.entries(t).forEach(([t,r])=>{e._isValid(r)&&(n[t]=r)}),n}static _write(e){if(Object.keys(e).length===0){st.remove(us);return}st.set(us,e)}static _isValid(e){let t=e;return typeof t==`object`&&!!t&&typeof t.sessionKey==`string`&&t.sessionKey.length>0&&typeof t.endpoint==`string`&&typeof t.savedAt==`number`}},ps=15e3,ms=class e{static setApi(t){e._api=t}static delta(){return e._delta}static ensure(){e._delta===null&&e._api&&e.get()}static get(){return e._delta===null?!e._api||!e._hasCredentials()||e._lastFailureAt!==null&&Date.now()-e._lastFailureAt<ps?Promise.resolve(0):(e._pending||(e._pending=e._measure().finally(()=>{e._pending=null})),e._pending):Promise.resolve(e._delta)}static noteAppended(t){if(e._delta!==null){Q.fillDelta([t],e._delta);return}e._idsAwaitingDelta.push(t)}static __resetForTests(){e._api=null,e._delta=null,e._pending=null,e._idsAwaitingDelta=[],e._lastFailureAt=null}static _hasCredentials(){return!!y.sessionKey||!!y.accessToken}static async _measure(){let t;try{let n=await e._api.getServerTime();t=Date.now()-n}catch{return e._lastFailureAt=Date.now(),0}e._lastFailureAt=null,e._delta=t;let n=e._idsAwaitingDelta;return e._idsAwaitingDelta=[],await Q.fillDelta(n,t),t}};h(ms,`_api`,null),h(ms,`_delta`,null),h(ms,`_pending`,null),h(ms,`_idsAwaitingDelta`,[]),h(ms,`_lastFailureAt`,null);var hs=`okcls-stat-unload.`,gs=class e{static beginTabSession(){e._tabKey=null,e._entries=[]}static writeSync(t){let n=e._storage();if(!n)return!1;try{return e._tabKey||(e._tabKey=hs+j.uuid()),e._entries.length>0&&n.getItem(e._tabKey)===null&&(e._entries=[]),e._entries.push(t),n.setItem(e._tabKey,JSON.stringify(e._entries)),!0}catch(e){return R.error(`[StatUnloadJournal] failed to write`,e),!1}}static async drainToQueue(){let t=e._storage();if(!t)return 0;let n=[];try{for(let e=0;e<t.length;e+=1){let r=t.key(e);r&&r.startsWith(hs)&&n.push(r)}}catch(e){return R.error(`[StatUnloadJournal] failed to scan journals`,e),0}let r=0;e.beginTabSession();for(let i of n){let n=e._take(t,i);if(n===null)continue;let a=null;try{a=JSON.parse(n)}catch{R.error(`[StatUnloadJournal] dropping corrupted journal`,i)}if(Array.isArray(a))for(let t of a)e._isValidEntry(t)&&await Q.append(t)&&(r+=1)}return r}static __resetForTests(){e._tabKey=null,e._entries=[]}static _take(e,t){try{let n=e.getItem(t);return n===null?null:(e.removeItem(t),n)}catch(e){return R.error(`[StatUnloadJournal] failed to take journal`,e),null}}static _storage(){try{return window.localStorage}catch{return null}}static _isValidEntry(e){let t=e;return typeof t==`object`&&!!t&&typeof t.uid==`number`&&(t.vcid===null||typeof t.vcid==`string`)&&typeof t.ts==`number`&&(t.delta===void 0||t.delta===null||typeof t.delta==`number`)&&typeof t.ev==`object`&&t.ev!==null}};h(gs,`_tabKey`,null),h(gs,`_entries`,[]);var _s=500,vs=100,ys=3e4,bs=1e3,xs=5e3,Ss=3e3,Cs=`okcls-stat-drain`,ws=class e{static setApi(t){e._api=t,ms.setApi(t)}static start(t){e.setApi(t),gs.drainToQueue().catch(e=>R.error(`[StatDrainScheduler] failed to import unload journal`,e)).then(async()=>(fs.prune(),await Q.evictOlderThan(qo),await Q.evictToLimit(Ko),e._drain())).catch(e=>R.error(`[StatDrainScheduler] failed to start`,e))}static notifyAppended(){if(e._api){if(e._localCount+=1,e._localCount>=vs){e._drain();return}e._state===`IDLE`&&e._arm(ys)}}static notifyCallFinished(){if(e._api){if(e._directBuffer.length>0&&e._armDirect(bs),e._state===`DRAINING`){e._callFinishedDuringDrain=!0;return}e._arm(bs)}}static drainOnce(){return e._withLock(async()=>{let t=e._api;if(!t)return!1;let n=e._currentUserId(),r=await Q.listUids(),i=!1,a=null;for(let o of r)try{(o===n?await e._drainCurrent(t,o):await e._drainStored(t,o))===_s&&(i=!0)}catch(e){a===null&&(a=e)}if(a!==null)throw a;return i})}static sendDirect(t){if(e._api){if(t.uid!==e._currentUserId()){R.error(`[StatDrainScheduler] direct send skipped: event belongs to another user`);return}e._directBuffer.push(t),e._directTimer===null&&e._armDirect(Ss)}}static __resetForTests(){ms.__resetForTests(),e._clearTimer(),e._clearDirectTimer(),e._directBuffer=[],e._api=null,e._state=`IDLE`,e._localCount=0,e._callFinishedDuringDrain=!1,e._blockedSession=null}static _currentUserId(){return y.userId}static async _drainCurrent(t,n){if(e._isSessionBlocked())return 0;let r=await Q.readOldest(n,_s);if(r.length===0)return 0;let i=await ms.get(),a=r.map(t=>e._toClientStats(t,i)),o=r.map(e=>e.id);try{await t.logClientStats(a)}catch(t){if(e._isRetryable(t))throw t;if(e._isReauthorizeFailure(t))throw e._blockSession(),t;return R.error(`[StatDrainScheduler] batch rejected, dropping`,t),await Q.remove(o),r.length}return await Q.remove(o),r.length}static async _drainStored(t,n){let r=fs.get(n);if(!r||r.endpoint!==fs.currentEndpoint())return 0;let i=await Q.readOldest(n,_s);if(i.length===0)return 0;let a=await ms.get(),o=i.map(t=>e._toClientStats(t,a)),s=i.map(e=>e.id);try{await t.logClientStatsWith(r.sessionKey,o),R.debug(`[StatDrainScheduler] delivered`,i.length,`stored events of uid`,n)}catch(t){if(e._isAuthError(t))return R.error(`[StatDrainScheduler] stored session expired, skipping uid`,n),fs.forget(n),0;if(e._isRetryable(t))throw t;return R.error(`[StatDrainScheduler] batch rejected, dropping`,t),await Q.remove(s),i.length}return await Q.remove(s),i.length}static _withLock(e){return typeof navigator>`u`||!navigator.locks?e():navigator.locks.request(Cs,e)}static _isSessionError(e){return Bo(e?.error_code)}static _isReauthorizeFailure(e){return e?.error===x.AUTH}static _blockSession(){e._blockedSession={key:y.sessionKey}}static _isSessionBlocked(){return e._blockedSession?e._blockedSession.key===y.sessionKey?!0:(e._blockedSession=null,!1):!1}static _isAuthError(t){let n=t?.error_code;return e._isSessionError(t)||n===zo.AUTH_LOGIN}static _isRetryable(t){if(e._isSessionError(t))return!0;let n=t?.callError;return n?n.scope===`network`?!0:!(`code`in n)||typeof n.code!=`string`?!1:n.code.startsWith(`http-5`)||n.code===`http-429`:!1}static _toClientStats(e,t){return{...e.ev,vcid:e.vcid,timestamp:e.ts-(e.delta??t)}}static _clearDirectTimer(){e._directTimer!==null&&(window.clearTimeout(e._directTimer),e._directTimer=null)}static _armDirect(t){e._clearDirectTimer(),e._directTimer=window.setTimeout(()=>{e._directTimer=null,e._flushDirect()},t)}static async _flushDirect(){let t=e._api,n=e._directBuffer;if(e._directBuffer=[],!(!t||n.length===0))try{let r=await ms.get();await t.logClientStats(n.map(t=>e._toClientStats(t,r)))}catch(e){R.error(`[StatDrainScheduler] direct send failed, events lost`,e)}}static _clearTimer(){e._timer!==null&&(window.clearTimeout(e._timer),e._timer=null)}static _arm(t){e._clearTimer(),e._state=`ARMED`,e._timer=window.setTimeout(()=>{e._timer=null,e._drain()},t)}static async _drain(){if(e._state!==`DRAINING`){e._clearTimer(),e._state=`DRAINING`,e._localCount=0,e._callFinishedDuringDrain=!1;try{if(await e.drainOnce()){e._arm(xs);return}if(e._callFinishedDuringDrain){e._arm(bs);return}if(e._localCount>0){e._arm(ys);return}e._state=`IDLE`}catch(t){R.error(`[StatDrainScheduler] drain failed`,t),e._arm(ys)}}}};h(ws,`_api`,null),h(ws,`_state`,`IDLE`),h(ws,`_timer`,null),h(ws,`_localCount`,0),h(ws,`_callFinishedDuringDrain`,!1),h(ws,`_blockedSession`,null),h(ws,`_directBuffer`,[]),h(ws,`_directTimer`,null);var Ts=class extends m{constructor(e,t,n,r=()=>void 0){super(),h(this,`_externalLogger`,void 0),h(this,`_api`,void 0),h(this,`_conversationIdProvider`,void 0),h(this,`_topologyProvider`,void 0),h(this,`_batchInterval`,3e3),h(this,`_batchedClientStats`,[]),h(this,`_batchTimeout`,null),h(this,`_serverTimeDelta`,0),h(this,`_waitingForServerTime`,!0),h(this,`_deferredClientStats`,[]),this._api=e,this._externalLogger=t,this._conversationIdProvider=n,this._topologyProvider=r,this._calculateServerTimeDelta()}log(e,t,n=!1){this._externalLogger&&this._externalLogger.log(e,t,n)}logClientStats(e,t=!1){let n=typeof t==`boolean`?{immediately:t}:t,r={...e,call_topology:e.call_topology??this._getCallTopology()};if(n.deferUntilServerTime&&this._waitingForServerTime){this._deferredClientStats.push({data:r,options:{...n}}),n.immediately&&this._flushDeferredClientStats();return}this._logClientStats(r,n)}destroy(){this._flushDeferredClientStats(),this._sendBatch(),this._stopTimeout()}_logClientStats(e,t){let n={...e,vcid:t.conversationId===void 0?this._getConversationId():t.conversationId,timestamp:t.occurredAt===void 0?this._now():t.occurredAt-this._serverTimeDelta};Object.keys(n).forEach(e=>{n[e]===void 0&&delete n[e]}),this._batchedClientStats.push(n),(t.immediately||!this._batchTimeout)&&this._sendBatch()}_getConversationId(){try{return this._conversationIdProvider()}catch{return null}}_getCallTopology(){try{return this._topologyProvider()===J.SERVER?`S`:`D`}catch{return`D`}}_sendBatch(){this._stopTimeout();let e=!1;this._batchedClientStats.length>0&&(this._sendClientStats(this._batchedClientStats),this._batchedClientStats=[],e=!0),e&&this._startTimeout()}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_sendClientStats(e){this._api.logClientStats(e)}async _calculateServerTimeDelta(){try{let e=await this._api.getServerTime();this._serverTimeDelta=Date.now()-e}catch{}finally{this._flushDeferredClientStats()}}_flushDeferredClientStats(){if(!this._waitingForServerTime)return;this._waitingForServerTime=!1;let e=this._deferredClientStats;this._deferredClientStats=[];for(let{data:t,options:n}of e)this._logClientStats(t,n)}_now(){return Date.now()-this._serverTimeDelta}},Es=class e extends m{static __resetForTests(){e._pending=[],e._pendingOverflow=!1}static _remember(t){if(e._pending.length>=5e3){e._pendingOverflow||(e._pendingOverflow=!0,R.error(`[StatEventCollector] pending buffer is full, dropping events until userId is known`));return}e._pending.push(t)}static _takePending(){let t=e._pending;return e._pending=[],e._pendingOverflow=!1,t}constructor(e,t,n,r=()=>void 0){super(),h(this,`_externalLogger`,void 0),h(this,`_conversationIdProvider`,void 0),h(this,`_topologyProvider`,void 0),h(this,`_unloadMode`,!1),h(this,`_legacy`,void 0),this._externalLogger=t,this._conversationIdProvider=n,this._topologyProvider=r,this._legacy=M.statQueueEnabled?null:new Ts(e,t,n,r)}log(e,t,n=!1){this._externalLogger&&this._externalLogger.log(e,t,n)}enterUnloadMode(){this._legacy||(this._unloadMode=!0,gs.beginTabSession())}exitUnloadMode(){this._legacy||!this._unloadMode||(this._unloadMode=!1,gs.drainToQueue().then(e=>{e>0&&ws.notifyAppended()}).catch(e=>R.error(`[StatEventCollector] failed to import unload journal`,e)))}logClientStats(t,n={}){if(this._legacy){this._legacy.logClientStats(t,n);return}let r={...t,call_topology:t.call_topology??this._getCallTopology()};Object.keys(r).forEach(e=>{r[e]===void 0&&delete r[e]}),ms.ensure();let i={vcid:n.conversationId===void 0?this._getConversationId():n.conversationId,ts:n.occurredAt===void 0?Date.now():n.occurredAt,delta:ms.delta(),ev:r},a=y.userId;if(a===null){e._remember(i);return}for(let t of e._takePending())this._store({...t,uid:a});this._store({...i,uid:a})}destroy(){if(this._legacy){this._legacy.destroy();return}}_store(e){this._unloadMode&&gs.writeSync(e)||Q.append(e).then(t=>{if(t!==null){typeof e.delta!=`number`&&ms.noteAppended(t),ws.notifyAppended();return}R.error(`[StatEventCollector] failed to store event, sending directly`),ws.sendDirect(e)}).catch(e=>R.error(`[StatEventCollector] failed to store event`,e))}_getConversationId(){try{return this._conversationIdProvider()}catch{return null}}_getCallTopology(){try{return this._topologyProvider()===J.SERVER?`S`:`D`}catch{return`D`}}};h(Es,`_pending`,[]),h(Es,`_pendingOverflow`,!1);var Ds=class{constructor(e){h(this,`_statAggregator`,void 0),this._statAggregator=e}log(e,t,n){this._statAggregator?.logEventualStat({name:H.API_CALL,value:Math.round(t),api_method:e,string_value:n})}},Os=`invalid-error-metadata`,ks=64,As=new Set(Object.values(D)),js=new Set(Object.values(x)),Ms={[D.CANCELED]:{type:`semantic`,reason:`canceled`},[D.REJECTED]:{type:`semantic`,reason:`rejected`},[D.REMOVED]:{type:`semantic`,reason:`removed`},[D.HUNGUP]:{type:`semantic`,reason:`hangup`},[D.MISSED]:{type:`semantic`,reason:`missed`},[D.BUSY]:{type:`semantic`,reason:`busy`},[D.FAILED]:{type:`failed`},[D.NETWORK_ERROR]:{type:`requires-call-error`},[D.KILLED]:{type:`semantic`,reason:`killed`},[D.BANNED]:{type:`semantic`,reason:`banned`},[D.HAS_ACTIVE_CALL]:{type:`semantic`,reason:`initially_closed`},[D.CALLER_IS_BLOCKED]:{type:`requires-call-error`},[D.NOT_FRIENDS]:{type:`direct-error`,error:{scope:`server`,source:`api`,code:1103,description:`friendship-required`}},[D.CALLEE_IS_OFFLINE]:{type:`direct-error`,error:{scope:`server`,source:`api`,code:1102,description:`target-user-unavailable`}},[D.CALLEE_UNAVAILABLE]:{type:`semantic`,reason:`unavailable`},[D.CALLER_IS_REJECTED]:{type:`direct-error`,error:{scope:`server`,source:`api`,code:1113,description:`caller-is-rejected`}},[D.UNKNOWN_ERROR]:{type:`failed`},[D.UNSUPPORTED]:{type:`direct-error`,error:{scope:`internal`,code:`observer-mode`,description:`video-tracks-count-must-be-zero`}},[D.SERVICE_DISABLED]:{type:`direct-error`,error:{scope:`server`,source:`api`,code:1101,description:`vchat-service-disabled`}},[D.SERVICE_UNAVAILABLE]:{type:`requires-call-error`},[D.EXTERNAL_API_ERROR]:{type:`requires-call-error`},[D.SOCKET_CLOSED]:{type:`semantic`,reason:`socket_closed`},[D.ENDED]:{type:`requires-call-error`},[D.KILLED_WITHOUT_DELETE]:{type:`semantic`,reason:`killed_without_delete`},[D.ANOTHER_DEVICE]:{type:`semantic`,reason:`another_device`},[D.NOT_FOUND]:{type:`requires-call-error`},[D.VCHAT_DETAILED_ERROR]:{type:`requires-call-error`},[D.TIMEOUT]:{type:`semantic`,reason:`timeout`},[D.PARTICIPANT_LIMIT_REACHED]:{type:`requires-call-error`},[D.FAST_START_ERROR]:{type:`failed`},[D.FAST_JOIN_ERROR]:{type:`failed`},[D.CALL_TIMEOUT]:{type:`semantic`,reason:`call_timeout`},[D.OBSOLETE_CLIENT]:{type:`semantic`,reason:`obsolete_client`}},Ns={[x.MIC_CAMERA_PERMISSION]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`mic-camera-permission`}},[x.CAMERA_PERMISSION]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`camera-permission`}},[x.MIC_PERMISSION]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`microphone-permission`}},[x.CAMERA_ACCESS]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`camera-access`}},[x.MIC_ACCESS]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`microphone-access`}},[x.MIC_NOT_FOUND]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`microphone-not-found`}},[x.SCREEN_PERMISSION]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`screen-permission`}},[x.SCREEN_ACCESS]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`screen-access`}},[x.CONNECTION]:{type:`direct-error`,error:{scope:`network`,source:`rtc`,code:`connection`,description:`connection-failed`}},[x.NETWORK]:{type:`requires-call-error`},[x.UNKNOWN]:{type:`failed`},[x.UNSUPPORTED]:{type:`requires-call-error`},[x.SIGNALING_FAILED]:{type:`requires-call-error`},[x.API]:{type:`requires-call-error`},[x.AUTH]:{type:`requires-call-error`},[x.OVERCONSTRAINED]:{type:`direct-error`,error:{scope:`internal`,code:`media`,description:`overconstrained`}}};function Ps(e){if(typeof e!=`string`&&typeof e!=`number`||typeof e==`number`&&!Number.isFinite(e))return Os;let t=String(e).trim();if(!t)return Os;let n=t.toLowerCase().replace(/[\s_:]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);return!n||!/^[a-z0-9.-]+$/.test(n)?Os:n.length>ks?`${n.slice(0,ks-3)}...`:n}function Fs(e){if(!e||typeof e!=`object`)return!1;let t=e;switch(t.scope){case`unknown`:case`internal`:return!0;case`external`:return t.source===`api`;case`server`:return t.source===`api`||t.source===`ws`||t.source===`wt`;case`network`:return t.source===`api`||t.source===`rtc`||t.source===`ws`||t.source===`wt`;default:return!1}}function Is(e){let t=Ps(e.description);if(e.scope===`unknown`)return`unknown:${t}`;let n=Ps(e.code);return e.scope===`internal`?`internal:${n}:${t}`:`${e.scope}:${e.source}:${n}:${t}`}function Ls(e,t){return t===null?e.type===`direct-error`?{reason:`error`,string_value:Is(e.error)}:{reason:`failed`}:Fs(t)?{reason:`error`,string_value:Is(t)}:{reason:`failed`}}function Rs(e){if(e.hangup){let t=Ms[e.hangup];return t?t.type===`semantic`?e.hangup===D.OBSOLETE_CLIENT&&e.custom_error?.vchat_detailed_api_error.code?{reason:t.reason,string_value:e.custom_error.vchat_detailed_api_error.code}:{reason:t.reason}:Ls(t,e.callError):{reason:`failed`}}if(e.error){let t=Ns[e.error];return t?Ls(t,e.callError):{reason:`failed`}}return{reason:`failed`}}function zs(e){return e instanceof O?Rs(e):typeof e==`string`&&(As.has(e)||js.has(e))?Rs(new O(e)):{reason:`failed`}}var Bs={wallNow:()=>Date.now(),monotonicNow:()=>performance.now()};function Vs(e){return e===`anonym_join`?`join`:e}var Hs=class{constructor(e,t=Bs){h(this,`_logger`,void 0),h(this,`_clock`,void 0),h(this,`_conversationId`,null),h(this,`_callStartLabel`,null),h(this,`_lifecycleStartedAtMonotonic`,0),h(this,`_pendingEvents`,[]),h(this,`_callStarted`,!1),h(this,`_accepted`,!1),h(this,`_firstMediaSent`,!1),h(this,`_finished`,!1),h(this,`_destroyed`,!1),this._logger=e,this._clock=t}get firstMediaSentReported(){return this._firstMediaSent}get terminated(){return this._finished||this._destroyed}markInitializationStarted({source:e,conversationId:t}){if(this._destroyed||this._callStartLabel!==null)return;let n=this._clock.wallNow();this._callStartLabel=Vs(e),this._lifecycleStartedAtMonotonic=this._clock.monotonicNow(),t&&(this._conversationId=t),this._record({name:H.CALL_INIT,source:e},n)}bindConversationId(e){this._destroyed||this._conversationId||!e||(this._conversationId=e,this._flushPendingEvents())}markCallStarted(){!this._canRecord()||this._callStarted||!this._callStartLabel||(this._callStarted=!0,this._record({name:H.CALL_START,value:this._durationSince(this._lifecycleStartedAtMonotonic),string_value:JSON.stringify({labels:[this._callStartLabel]})}))}markOutgoingAccepted(){!this._canRecord()||this._accepted||(this._accepted=!0,this._record({name:H.CALL_ACCEPTED_OUTGOING}))}markIncomingAccepted(e){!this._canRecord()||this._accepted||(this._accepted=!0,this._record({name:H.CALL_ACCEPTED_INCOMING,...e&&{string_value:`concurrent`}}))}markFirstMediaSent(){!this._canRecord()||this._firstMediaSent||(this._firstMediaSent=!0,this._record({name:H.FIRST_MEDIA_SENT}))}markFinished(e){this._finish(zs(e))}markTerminated(){this._finish({reason:`terminated`})}destroy(){this._destroyed||(this._destroyed=!0,this._pendingEvents=[])}_canRecord(){return this._callStartLabel!==null&&!this._finished&&!this._destroyed}_durationSince(e){return Math.max(0,Math.round(this._clock.monotonicNow()-e))}_finish({reason:e,string_value:t}){this._canRecord()&&(this._finished=!0,this._ensureConversationId(),this._record({name:H.CALL_FINISH,reason:e,...t&&{string_value:t}},void 0,!0))}_ensureConversationId(){this._conversationId||(this._conversationId=j.uuid(),this._flushPendingEvents())}_record(e,t=this._clock.wallNow(),n=!1){if(this._destroyed)return;let r={data:e,occurredAt:t,immediately:n};if(!this._conversationId){this._pendingEvents.push(r);return}this._logEvent(r)}_flushPendingEvents(){if(!this._conversationId||!this._pendingEvents.length)return;let e=this._pendingEvents;this._pendingEvents=[];for(let t of e)this._logEvent(t)}_logEvent({data:e,occurredAt:t,immediately:n}){this._logger.logClientStats(e,{conversationId:this._conversationId,deferUntilServerTime:!0,occurredAt:t,...n&&{immediately:!0}})}},Us=class{constructor(e,t){h(this,`_logger`,void 0),h(this,`_codecUsages`,new Map),h(this,`getCurrentTransportTopology`,void 0),this._logger=e,this.getCurrentTransportTopology=t}reportUsage(e){let t=this.getCurrentTransportTopology();if(!t)return;let n=e.rtps.filter(e=>e.type===`outbound-rtp`&&!e.mid?.endsWith(`s`));M.simulcast&&(n=n.reduce((e,t)=>{if(t.kind!==`video`)return e.concat(t);let n=e.find(e=>e.kind===`video`);return n?n.totalEncodeTime=(n.totalEncodeTime??0)+(t.totalEncodeTime??0):e.push(t),e},[])),n.forEach(e=>{let n=e.kind,r=e.mimeType;if((n===`audio`||n===`video`)&&r){let i=[r,`encoder`,e.encoderImplementation].filter(Boolean).join(`/`);this.saveUsage({kind:n,codecName:i,totalEncodeTime:(e.totalEncodeTime??0)*1e3,audioCodecParams:e.sdpFmtpLine,topology:t})}})}saveUsage({kind:e,codecName:t,totalEncodeTime:n,audioCodecParams:r,topology:i}){let a=this._codecUsages.get(e);if(a&&a.codecName!==t&&this.report(a),a&&a.codecName===t){this._codecUsages.set(e,{...a,totalEncodeTime:n,topology:i});return}this._codecUsages.set(e,{kind:e,codecName:t,audioCodecParams:r,totalEncodeTime:n,topology:i})}report(e){if(e.kind===`video`&&e.totalEncodeTime===0)return;let t={name:H.CODEC_USAGE,codec_implementation:e.codecName,value:Number.parseFloat(e.totalEncodeTime.toFixed(3)),call_topology:e.topology===J.DIRECT?`D`:`S`};e.audioCodecParams&&(t.string_value=e.audioCodecParams),this._logger.logClientStats(t)}destroy(){this._codecUsages.forEach(e=>{this.report(e)}),this._codecUsages.clear()}},Ws=class{constructor(e){h(this,`_logger`,void 0),h(this,`_eventualLogs`,new Set),h(this,`_lastCallStatContext`,null),this._logger=e}logCallStat(e){this._lastCallStatContext=this._getCallStatContext(e),this._flushEventualStats(),this._logger.logClientStats(e)}logEventualStat(e){this._eventualLogs.add({data:e,occurredAt:Date.now()})}logEventualStatSinceMark(e){let t=W.measureMark(e.name);t!==null&&this.logEventualStat({...e,value:t})}destroy(){this._flushEventualStats()}_getCallStatContext(e){return{call_topology:e.call_topology,local_address:e.local_address,local_connection_type:e.local_connection_type,network_type:e.network_type,remote_address:e.remote_address,remote_connection_type:e.remote_connection_type,transport:e.transport}}_flushEventualStats(){let e=[...this._eventualLogs];for(let t of e)this._logEventualStat(t),this._eventualLogs.delete(t)}_logEventualStat({data:e,occurredAt:t}){this._logger.logClientStats({...e,...this._lastCallStatContext??{}},{occurredAt:t})}},Gs=class{constructor(e){if(h(this,`q`,void 0),h(this,`inits`,[]),h(this,`n`,[1,2,3,4,5]),h(this,`np`,[1,1,1,1,1]),h(this,`qv`,[]),!(e>0&&e<1))throw Error(`q must be in (0,1)`);this.q=e}add(e){if(this.inits.length<5){this.inits.push(e),this.inits.length===5&&this.bootstrap();return}let t=0;if(e<this.qv[0])this.qv[0]=e,t=0;else if(e>=this.qv[4])this.qv[4]=e,t=3;else for(;!(e<this.qv[t+1]);)t++;for(let e=0;e<5;e++)this.n[e]+=e<=t?0:1;this.np[0]=1,this.np[1]+=this.q/2,this.np[2]+=this.q,this.np[3]+=(1+this.q)/2,this.np[4]+=1;for(let e=1;e<=3;e++){let t=this.np[e]-this.n[e];if(t>=1&&this.n[e+1]-this.n[e]>1||t<=-1&&this.n[e]-this.n[e-1]>1){let n=Math.sign(t),r=this.qv[e]+n/(this.n[e+1]-this.n[e-1])*((this.n[e]-this.n[e-1]+n)*(this.qv[e+1]-this.qv[e])/(this.n[e+1]-this.n[e])+(this.n[e+1]-this.n[e]-n)*(this.qv[e]-this.qv[e-1])/(this.n[e]-this.n[e-1]));r>this.qv[e-1]&&r<this.qv[e+1]?this.qv[e]=r:this.qv[e]=this.qv[e]+n*(this.qv[e+n]-this.qv[e])/(this.n[e+n]-this.n[e]),this.n[e]+=n}}}value(){if(this.inits.length===0)return NaN;if(this.inits.length<5){let e=[...this.inits].sort((e,t)=>e-t),t=this.q*(e.length-1),n=Math.floor(t),r=t-n;return n+1<e.length?e[n]*(1-r)+e[n+1]*r:e[n]}return this.qv[2]}bootstrap(){this.inits.sort((e,t)=>e-t),this.qv=this.inits.slice(0,5),this.n=[1,2,3,4,5],this.np=[1,1+2*this.q,1+4*this.q,3+2*this.q,5]}},Ks=class{constructor(){h(this,`n`,0),h(this,`mean`,0)}add(e){this.n++;let t=e-this.mean;this.mean+=t/this.n}get avg(){return this.n?this.mean:NaN}},qs=class{constructor(){h(this,`count`,0),h(this,`minVal`,1/0),h(this,`maxVal`,-1/0),h(this,`mean`,new Ks),h(this,`p50`,new Gs(.5)),h(this,`p95`,new Gs(.95))}add(e){e<this.minVal&&(this.minVal=e),e>this.maxVal&&(this.maxVal=e),this.mean.add(e),this.p50.add(e),this.p95.add(e),this.count++}snapshot(){return{min:this.minVal===1/0?NaN:this.minVal,max:this.maxVal===-1/0?NaN:this.maxVal,avg:+this.mean.avg.toFixed(),median:+this.p50.value().toFixed(),p95:+this.p95.value().toFixed(),count:this.count}}get hasData(){return this.count>0}},Js=class{constructor(e){h(this,`_logger`,void 0),h(this,`trackerByTransport`,{ws:new qs,wt:new qs}),h(this,`lastSeen`,{}),this._logger=e}mark(e){let t=Date.now(),n=this.lastSeen[e];if(typeof n==`number`){let r=t-n;r>=0&&this.trackerByTransport[e].add(r)}this.lastSeen[e]=t}logMetrics(){[xr.WEBSOCKET,xr.WEBTRANSPORT].forEach(e=>{if(!this.trackerByTransport[e].hasData)return;let t=this.trackerByTransport[e].snapshot();this._logger.logClientStats({name:H.SIGNALING_PING_SUMMARY,min_value:t.min,max_value:t.max,avg_value:t.avg,median_value:t.median,p95_value:t.p95,values_count:t.count,signaling_transport:e})})}destroy(){this.trackerByTransport={ws:new qs,wt:new qs},this.lastSeen={}}},Ys=class{constructor(e){h(this,`_logger`,void 0),h(this,`trackerByCommand`,new Map),this._logger=e}mark(e,t,n){let r=`${e}|${n}`,i;this.trackerByCommand.has(r)?i=this.trackerByCommand.get(r):(i=new qs,this.trackerByCommand.set(r,i)),i.add(t)}logMetrics(){for(let[e,t]of this.trackerByCommand.entries()){if(!t.hasData)continue;let[n,r]=e.split(`|`),i=t.snapshot();this._logger.logClientStats({name:H.SIGNALING_COMMAND_SUMMARY,api_method:n,min_value:i.min,max_value:i.max,avg_value:i.avg,median_value:i.median,p95_value:i.p95,values_count:i.count,signaling_transport:r})}}destroy(){this.trackerByCommand.clear()}},Xs=class{constructor(e,t,n,r){h(this,`logger`,void 0),h(this,`lifecycle`,void 0),h(this,`statAggregator`,void 0),h(this,`codecStatsAggregator`,void 0),h(this,`pings`,void 0),h(this,`signalingCommands`,void 0),h(this,`apiCalls`,void 0),h(this,`_api`,void 0),h(this,`_unloading`,!1),this.logger=new Es(e,t,n,r),this.lifecycle=new Hs(this.logger),this.statAggregator=new Ws(this.logger),this.codecStatsAggregator=new Us(this.logger,r),this.pings=new Js(this.logger),this.signalingCommands=new Ys(this.logger),this.apiCalls=new Ds(this.statAggregator),this._api=e,this._api.setApiCallStats(this.apiCalls)}prepareForUnload(){M.statQueueEnabled&&(this._unloading=!0,this.logger.enterUnloadMode(),this.pings.logMetrics(),this.signalingCommands.logMetrics())}restoreAfterUnload(){M.statQueueEnabled&&(this._unloading=!1,this.logger.exitUnloadMode())}logHangup(e){this.lifecycle.markFinished(e)}flushCallMetrics(){this.codecStatsAggregator.destroy(),this.pings.logMetrics(),this.pings.destroy(),this.signalingCommands.logMetrics(),this.signalingCommands.destroy()}destroy(){this._api.setApiCallStats(null),this.lifecycle.markTerminated(),this.lifecycle.destroy(),this.statAggregator.destroy(),this.codecStatsAggregator.destroy(),this.pings.destroy(),this.signalingCommands.destroy(),this.logger.destroy(),M.statQueueEnabled&&!this._unloading&&ws.notifyCallFinished()}},Zs=class{constructor(e){h(this,`_statAggregator`,void 0),h(this,`_isCallMarked`,!1),h(this,`_isFinished`,!1),h(this,`_callType`,null),this._statAggregator=e}markAcceptCall(e){this.mark(e===J.DIRECT?`direct_incoming`:`server_incoming`)}markAcceptedCall(e){e===J.DIRECT&&this.mark(`direct_outgoing`)}markOnJoin(e){this.mark(e===J.DIRECT?`direct_join`:`server_join_server`,e===J.DIRECT)}markTopologyChanged(e){this._isFinished||e!==J.SERVER||(this._callType=`server_change_topology`)}mark(e,t=!1){(!this._isCallMarked||t)&&(this._isCallMarked=!0,this._callType=e,W.setMark(H.FIRST_MEDIA_RECEIVED))}measure(){this._isFinished||(this._isFinished=!0,this._callType&&this._statAggregator.logEventualStatSinceMark({name:H.FIRST_MEDIA_RECEIVED,call_type:this._callType}))}},Qs=1e3,$s=1e4;function ec(e,t,n,r){return new O(e,{callError:{scope:`external`,source:`api`,code:t,description:n},message:r})}var tc=15,$=class e extends b{constructor(e,t){super(),h(this,`_api`,void 0),h(this,`_signaling`,void 0),h(this,`_signalingActor`,void 0),h(this,`_displayLayoutRequester`,void 0),h(this,`_mediaSource`,null),h(this,`_conversation`,null),h(this,`_myLastRequestedLayouts`,{}),h(this,`_state`,`IDLE`),h(this,`_previousState`,null),h(this,`_waitingHallHoldPending`,!1),h(this,`_participantState`,X.CALLED),h(this,`_participants`,{}),h(this,`_directTransportIsMaster`,void 0),h(this,`_transport`,null),h(this,`_debugInfo`,null),h(this,`_debug`,R.createSessionLogger()),h(this,`_volumesDetector`,null),h(this,`_speakerDetector`,null),h(this,`_localVolumeDetector`,null),h(this,`_specListener`,null),h(this,`_activeSpeakerId`,null),h(this,`_lastSignalledActiveSpeakerId`,null),h(this,`_isRealTimeAsrRequested`,!1),h(this,`_serverSettings`,jr()),h(this,`_serverTimeOffset`,0),h(this,`_delayedHangup`,!1),h(this,`_onFastHangup`,void 0),h(this,`_hangupEmitted`,!1),h(this,`_hangupPromise`,null),h(this,`_abortController`,null),h(this,`_registeredPeerReceived`,!1),h(this,`_calleeUnavailableTimer`,null),h(this,`_reservedId`,null),h(this,`_onUnload`,void 0),h(this,`_onRestore`,void 0),h(this,`_audioOutput`,void 0),h(this,`_stats`,void 0),h(this,`_lastStalled`,{}),h(this,`_audioMixStalled`,!1),h(this,`_audioFix`,null),h(this,`_streamByStreamId`,new Map),h(this,`_streamIdByStreamDescription`,new Map),h(this,`_streamWaitTimerByStreamDescription`,new Map),h(this,`_sequenceNumberByStreamDescription`,new Map),h(this,`_cooldownTimestampByStreamDescription`,new Map),h(this,`_cooldownQueueCleanupTimer`,null),h(this,`_statFirstMediaReceived`,void 0),h(this,`_toggleLocalVideo`,vo(e=>{if(this._mediaSource)return this._stats.logger.log(C.MEDIA_STATUS,e?`video_1`:`video_0`),this._mediaSource.toggleVideo(e)})),h(this,`_toggleLocalAudio`,vo(e=>{if(this._mediaSource)return this._stats.logger.log(C.MEDIA_STATUS,e?`audio_1`:`audio_0`),this._mediaSource.toggleAudio(e)})),h(this,`_changeMediaSettings`,j.debounce(async e=>{if(this._signaling.ready)try{await this._signaling.changeMediaSettings(e)}catch(e){if(this._debug.warn(`changeMediaSettings failed with error`,e),e.message===`chatRoom.maxShareCountExceeded`)return this.toggleScreenCapturing({captureScreen:!1,fastScreenSharing:!1,captureAudio:!1})}},100)),this._stats=new Xs(e,t,()=>this._conversation?.id||null,()=>this._transport?.getTopology()??this._conversation?.topology),this._api=e,this._signaling=new Ua(this._debug,this._stats.logger,this._stats.statAggregator,this._stats.pings,this._stats.signalingCommands),this._signalingActor=new jo(this._onSignalingNotification.bind(this),this._debug),this._displayLayoutRequester=new Do({api:this._api,debug:this._debug,getParticipants:()=>this._participants,isMe:e=>this._isMe(e),updateDisplayLayout:e=>this.updateDisplayLayout(e),onNonFatalError:e=>this._onNonFatalError(e)}),this._onUnload=()=>{this._stopFirstMediaSentProbe(),this._conversation&&this._api&&this._sendHangupApi(this._conversation.id,this._state===`IDLE`?D.CANCELED:D.HUNGUP),this._stats.prepareForUnload(),this._stats.destroy()},this._onRestore=()=>{this._stats.restoreAfterUnload()},window.addEventListener(`pagehide`,this._onUnload),window.addEventListener(`pageshow`,this._onRestore),this._statFirstMediaReceived=new Zs(this._stats.statAggregator),this._audioOutput=new bo(this._statFirstMediaReceived,M.transparentAudio,this._debug,this._stats.logger),M.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Qs))}static current(){return z.getActive()??(M.hold?null:z.getFirst())}static hangupAfterInit(e){let t=nc;if(t){if(typeof e==`function`&&(t._onFastHangup=e),t._delayedHangup===!1&&!t._conversation){t._delayedHangup=!0,t._abortController?.abort(new O(D.CANCELED));return}t._conversation&&t.hangup({onFastHangup:e,reason:D.CANCELED})}}static id(){return z.getActiveId()}get id(){return this._conversation?.id??``}get externalId(){return this._conversation?.externalId}get mediaSettings(){return this._mediaSource?.mediaSettings}get isCallHeld(){return this._state===`HELD`}get isIncomingRinging(){return this._conversation?.direction===Wa.INCOMING&&this._state===`IDLE`}static debugSessionId(){return e.current()?.debugSessionId??null}static debugMessage(t,...n){let r=e.current();return r?(r._debug.send(t,...n),!0):!1}static debugMessageWithContext(e,t,...n){let r=z.get(t);return r?(r._debug.send(e,...n),!0):!1}static getSyncedTime(){return Date.now()+(e.current()?._serverTimeOffset??0)}get debugSessionId(){return this._debug.sessionId}getCachedParticipantIdByExternalId(e){return this._api.getCachedParticipantIdByExternalId(e)}_onNonFatalError(e){L.onNonFatalError(Error(e),this.id)}getIncomingCallerExternalId(){return this._conversation?.direction===Wa.INCOMING?Object.values(this._participants).find(e=>!this._isMe(e.id))?.externalId??null:null}_buildInternalParams(){let e={deviceId:this._api.deviceId(),sdkVersion:M.sdkVersion,clientAppKey:M.apiKey,platform:M.platform,protocolVersion:M.protocolVersion,domainId:M.domain,capabilities:wa.getFlags()};return JSON.stringify(e)}async onStart({opponentIds:e,opponentType:t,mediaOptions:n,payload:r=``,joiningAllowed:i=!1,requireAuthToJoin:a=!1,onlyAdminCanShareMovie:o,externalIds:s,onFastStart:c,conversationId:l}){let u=l??j.uuid(),d=(e?.length??0)+(s?.length??0),f=t===Ga.USER&&d===1?M.calleeUnavailableWaitingTime:void 0;this._stats.lifecycle.markInitializationStarted({source:`outgoing`,conversationId:u}),this._debug.setConversationId(u),nc=this,this._abortController=new AbortController,this._api.setAbortSignal(this._abortController?.signal),this._signaling.setAbortSignal(this._abortController?.signal);try{this._mediaSource=this._createMediaSource(),await this._mediaSource.request(n);let l=this._mediaSource.mediaSettings;t===Ga.CHAT||e&&e.length>1?this._logWithMediaSettings(C.OUTGOING_MULTIPARTY_CALL,l):this._logWithMediaSettings(C.OUTGOING_CALL,l);let d=await this._startConversation({opponentIds:e,opponentType:t,direction:Wa.OUTGOING,mediaOptions:n,payload:r,joiningAllowed:i,requireAuthToJoin:a,onlyAdminCanShareMovie:o,externalIds:s,onFastStart:c,conversationId:u});if(!this._conversation)throw new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`conversation`,description:`not-initialized-after-start`}});if(this._participantState=X.ACCEPTED,this._changeMediaSettings(l),await this._processConnection(d),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),this._delayedHangup)throw new O(D.CANCELED);if(this._debug.debug(`Outgoing call`,{opponentIds:e,opponentType:t,mediaOptions:n}),this._processConnectionSharedMovieInfo(d),this._processConversationUrlSharingInfo(d),L.onLocalStream(this._mediaSource.getStream(),this._mediaSource.mediaSettings,this.id),L.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),this._getMainRoomParticipants(),void 0,this.id),this._onConversationParticipantListChunk(d),this._processPinnedParticipants(d),L.onLocalStatus(N.WAITING,this.id),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),this._conversation?.concurrent){let e=z.get(this._conversation.id);e&&e!==this&&e._close(new O(D.HUNGUP,{remote:!0}))}return z.add(this),await z.setActive(this.id),nc=null,this._conversation.concurrent&&await this._acceptConcurrent(),f&&!this._registeredPeerReceived&&this._state!==`CLOSE`&&(this._calleeUnavailableTimer=window.setTimeout(()=>{this._calleeUnavailableTimer=null,this._close(new O(D.CALLEE_UNAVAILABLE),{signalingReason:D.CANCELED})},f)),this._conversation}catch(e){throw nc=null,this._cleanupRegistry(),this._close(e,{errorText:`Unable to start conversation`}),e}}async onJoin(e){this._stats.lifecycle.markInitializationStarted({source:e.anonymous?`anonym_join`:`join`,conversationId:e.conversationId}),nc=this,this._state=`PROCESSING`,this._debug.setConversationId(e.conversationId??null),this._abortController=new AbortController,this._api.setAbortSignal(this._abortController?.signal),this._signaling.setAbortSignal(this._abortController?.signal);try{let t=!!e.observedIds?.length;if(t&&M.videoTracksCount>0)throw this._debug.error(`Observer mode: please set videoTracksCount=0`),new O(D.UNSUPPORTED,{callError:{scope:`internal`,code:`observer-mode`,description:`video-tracks-count-must-be-zero`}});this._mediaSource=this._createMediaSource(),await this._mediaSource.request(e.mediaOptions,!t);let n=this._mediaSource.mediaSettings;this._logWithMediaSettings(C.JOIN_CONVERSATION,n);let r=await this._joinConversation(e);if(!this._conversation)throw new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`conversation`,description:`not-initialized-after-join`}});return this._conversation.observer=t,L.onLocalStream(this._mediaSource.getStream(),n,this.id),this._conversation.waitForAdmin||this._conversation.waitingHall?(this._debug.log(this._conversation.waitForAdmin?`Wait for admin`:`In waiting hall`),z.add(this),nc=null,this._signaling.readyToSend(),L.onLocalStatus(this._conversation.waitForAdmin?N.WAIT_FOR_ADMIN:N.WAITING_HALL,this.id),this._conversation):this._onJoinPart2(r)}catch(e){throw nc=null,this._cleanupRegistry(),this._close(e,{errorText:`Unable to join conversation`}),e}}async _onJoinPart2(e,t=!0,n=!1){this._debug.debug(`Join conversation part 2`);try{if(this._participantState=X.ACCEPTED,!this._conversation||!this._mediaSource)throw new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`join`,description:`runtime-not-initialized`}});if(this._statFirstMediaReceived.markOnJoin(this._conversation.topology),!n&&!this._conversation.observer&&!this._isAudienceModeListener()&&this._changeMediaSettings(this._mediaSource.mediaSettings),await this._processConnection(e),t&&(this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener()),this._signaling.readyToSend(),this._state===`CLOSE`)return this._conversation;if(this._delayedHangup)throw new O(D.CANCELED);this._processConnectionSharedMovieInfo(e),this._processConversationUrlSharingInfo(e),this._processConnectionAsrInfo(e);let r=this._extractExternalRoomsData(e.rooms?.rooms,e.rooms?.roomId);L.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),this._getMainRoomParticipants(),r,this.id),this._onConversationParticipantListChunk(e),this._processPinnedParticipants(e),L.onLocalStatus(N.WAITING,this.id),this._toggleJoinAvailability(),this._changeNeedRate(),t&&(this._state=`ACTIVE`),this._changeFeatureSet(),t&&(z.add(this),n?await this._holdLocally():await z.setActive(this.id),nc=null);let i=this._extractLocalParticipantFromConnection(e);if(i){let e=j.mapParticipantState(i);Object.keys(e).length>0&&L.onLocalParticipantState(e,!1,this.id)}return t&&this._openTransport(Object.values(this._participants),!1),this._conversation}catch(e){throw nc=null,this._cleanupRegistry(),this._close(e,{errorText:`Unable to join conversation`}),e}}_extractExternalRooms(e){let t=[],n=[];return e.forEach(e=>{let{room:r,missingParticipantIds:i}=this._convertRoomToExternal(e);r&&n.push(r),t.push(...i)}),this._reportMissingExternalIds(t,`EXTRACT_EXTERNAL_ROOMS`),n.filter(e=>!!e)}_extractExternalRoomsData(e,t){if(!e||!e.length)return;let n={rooms:this._extractExternalRooms(e)};return t&&(n.roomId=t),n}async onPush(e,t=A.USER,n,r,i,a){if(z.has(e))throw new O(D.HAS_ACTIVE_CALL);z.reserve(e),this._reservedId=e,a&&this._api.setUserId(a),this._stats.lifecycle.markInitializationStarted({source:`incoming`,conversationId:e}),this._debug.setConversationId(e),nc=this,this._abortController=new AbortController,this._api.setAbortSignal(this._abortController?.signal),this._signaling.setAbortSignal(this._abortController?.signal);try{let a=await this._prepareConversation(e,t,n,r,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`conversation`,description:`incoming-not-initialized`}});if(!a.conversation.participants.find(e=>e.state===X.CALLED&&e.id===this._conversation?.userId))throw this._debug.log(`Push rejected (there is an active call)`),this._stats.logger.log(C.PUSH,`rejected`),new O(D.REJECTED);if(await this._processConnection(a),this._extractConnectionUrlSharingInfo(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._processPinnedParticipants(a),this._signaling.readyToSend(),this._stats.lifecycle.markCallStarted(),this._stats.logger.log(C.PUSH,`accepted`),z.add(this),nc=null,this._delayedHangup)throw new O(D.CANCELED)}catch(e){throw nc=null,this._cleanupRegistry(),this._close(e,{errorText:`Unable to handle inbound call push`,signalingReason:e instanceof O&&e.hangup===D.BUSY?D.BUSY:void 0}),e}}_isInWaitingHall(e){return!e.conversation||!e.conversation.options.includes(Ja.WAITING_HALL)?!1:this._isRestricted(e)}_isWaitForAdmin(e){if(!e.conversation)return!1;let t=e.conversation.options.includes(Ja.WAIT_FOR_ADMIN),n=e.conversation.options.includes(Ja.ADMIN_IS_HERE);return!t||t&&n?!1:this._isRestricted(e)}_isRestricted(e){let t=(e.conversation.participants||[]).find(t=>j.comparePeerId(t.peerId,e.peerId));return t&&t.restricted||!1}_isAudienceMode(e){return e.conversation?.options?.includes(Ja.AUDIENCE_MODE)||!1}_isAudienceModeListener(){return this._conversation?.audienceMode&&this._conversation?.restricted}async _acceptConcurrent(){if(!this._mediaSource||!this._conversation||!this._transport)throw new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`accept`,description:`runtime-not-initialized`}});this._state=`PROCESSING`;let e=this._mediaSource.mediaSettings;this._logWithMediaSettings(C.ACCEPT_CONCURRENT,e),this._debug.debug(`Concurrent call`,{conversationId:this._conversation.id});try{this._statFirstMediaReceived.markAcceptCall(this._transport.getTopology()),await this._signaling.acceptCall(this._mediaSource.mediaSettings),this._stats.lifecycle.markIncomingAccepted(!0),L.onCallAccepted(this.id),this._state=`ACTIVE`,this._participantState=X.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(e){this._close(e,{errorText:`Unable to accept concurrent call`})}}_getMainRoomParticipants(){let e=this._participants;return j.mapSharedParticipants(Object.values(e).filter(e=>!e.isInRoom))}_decodeExternalConversationParams(e){let[t,n]=e.split(`:`),r=parseInt(t,10);if(isNaN(r))throw Error(`Invalid original length in prefix`);let i=atob(n),a=new Uint8Array(i.length);for(let e=0;e<i.length;e++)a[e]=i.charCodeAt(e);try{let e=_o(a,r).reduce((e,t)=>(e+=String.fromCharCode(t),e),``),{srcp:t,stne:n,tkn:i,trne:o,trnp:s,trnu:c,wse:l,wte:u}=JSON.parse(e);return{token:i,endpoint:l,wt_endpoint:u,turn_server:{urls:o.split(`,`),username:c,credential:s},stun_server:{urls:n.split(`,`)},client_type:t}}catch(e){throw this._close(e,{errorText:`Can't decompress conversation params`}),e}}async accept(e){if(this._state!==`IDLE`)throw this._stats.logger.log(C.ERROR,`acceptIncoming`),this._debug.error(`Unable to accept a call - invalid state`),Error(`Unable to accept a call - invalid state`);if(!this._mediaSource||!this._conversation||!this._transport)throw new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`accept`,description:`runtime-not-initialized`}});this._state=`PROCESSING`,this._debug.setConversationId(this._conversation.id),this._debug.debug(`Accept incoming call`,e);try{await this._mediaSource.request(e);let t=this._mediaSource.mediaSettings;this._logWithMediaSettings(C.ACCEPT_INCOMING,t),this._changeMediaSettings(t),this._statFirstMediaReceived.markAcceptCall(this._transport.getTopology()),await this._signaling.acceptCall(t),this._stats.lifecycle.markIncomingAccepted(!1),this._participantState=X.ACCEPTED;let n=this._getMuteStatesForCurrentRoom(),r=Object.keys(n);r.length&&this._onMuteParticipant({muteStates:n,mediaOptions:r,muteAll:!0,stateUpdated:!0}),this._registerParticipantLocalMuteState({muteStates:this._conversation.muteStatesPersonal});let i=await this._signaling.getRooms(this._isCallAdmin());if(i.rooms?.rooms?.length){let e=this._participants;i.rooms.rooms.forEach(t=>{t.participantIds?.forEach(t=>{e[t]&&(e[t].isInRoom=!0)})})}this._conversation.roomId=i.rooms?.roomId||null;let a=this._extractExternalRoomsData(i.rooms?.rooms,i.rooms?.roomId);if(L.onCallAccepted(this.id),L.onLocalStream(this._mediaSource.getStream(),t,this.id),L.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),this._getMainRoomParticipants(),a,this.id),await this._emitHeldParticipantsStatus(),M.useParticipantListChunk){let e=await this._getInitialParticiapntListChunk(),t=this._participants;e?.participants?.forEach(e=>{let n=t[j.composeId(e)];n&&(n.movieShareInfos=e.movieShareInfos)}),this._onConversationParticipantListChunk({participants:e})}return L.onLocalStatus(N.WAITING,this.id),this._toggleJoinAvailability(),this._changeNeedRate(),this._state=`ACTIVE`,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0),this._processConversationUrlSharingInfo(),this._processConnectionAsrInfo(),z.setActive(this.id).catch(e=>{this._debug.error(e),this._close(e,{errorText:`Unable to activated accepted call`})}),this._conversation}catch(e){throw this._close(e,{errorText:`Unable to accept call`}),e}}async decline(e){if(this._state!==`IDLE`)throw this._stats.logger.log(C.ERROR,`declineIncoming`),this._debug.error(`Unable to decline a call - invalid state`),Error(`Unable to decline a call - invalid state`);let t=e?.reason;this._state=`PROCESSING`,this._debug.debug(`Decline incoming call`),this._logWithMediaSettings(C.DECLINE_INCOMING,this.mediaSettings),this._participantState=X.HUNGUP;let n=t??D.REJECTED,r=new O(n);this._finishLifecycle(r),this._onFastHangup=e?.onFastHangup??this._onFastHangup;let i=this._conversation?.id;i&&typeof this._onFastHangup==`function`&&this._sendHangup(i,n,this._onFastHangup),this._close(r,{signalingReason:n})}hangup(e){if(this._hangupPromise)return this._hangupPromise;let t=e?.reason;this._clearCalleeUnavailableWatchdog(),this._debug.debug(`Hangup`);let n=t??(this._state===`ACTIVE`||this._state===`HELD`?D.HUNGUP:D.CANCELED),r=new O(n),i=this._conversation?.id??null;this._onFastHangup=e?.onFastHangup??this._onFastHangup,this._stats.logger.log(C.HANGUP,n),this._finishLifecycle(r);let a=!!i&&typeof this._onFastHangup==`function`;return i&&a&&this._sendHangup(i,n,this._onFastHangup),this._hangupPromise=this._signaling.hangup(n).then(()=>void 0).catch(e=>{if(!(e instanceof En))throw e}).finally(()=>(i!=null&&!a&&this._sendHangupApi(i,n),this._close(r))),this._emitHangupOnce(r,i),this._cleanupTransport(),this._cleanupMediaSource(),this._hangupPromise}async addParticipant(e,t){if(!this._signaling.ready){this._close(new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`add-participant`,description:`signaling-not-ready`}}),{errorText:`Unable to add participant`});return}let n=await this._signaling.addParticipant(e.map(Z.toSignaling),t),r=null;n.type===`error`&&(r=n.error===`call-unfeasible`?n.status:D.UNKNOWN_ERROR);let i=n.participants;if(!i&&n.rejectedParticipants?.length)throw Error(n.rejectedParticipants[0].reason);for(let e of i)await this._onAddParticipant(j.composeId(e),e,r)}async addParticipantLegacy(e,t){if(!this._signaling.ready){this._close(new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`add-participant`,description:`signaling-not-ready`}}),{errorText:`Unable to add participant`});return}let n=await this._signaling.addParticipantLegacy(e,t),r=null;n.type===`error`&&(r=n.error===`call-unfeasible`?n.status:D.UNKNOWN_ERROR);let i=n.participants;for(let e of i)await this._onAddParticipant(j.composeId(e),e,r)}async removeParticipant(e,t=!1){this._signaling.ready&&(await this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){if(!this._transport)return;let n=new Set(this._transport.opened()),r=[];for(let i of e)(i.state===X.CALLED||i.state===X.ACCEPTED)&&(this._transport.isAllocated(i.id)||this._allocateParticipantTransport(i.id,t)),i.state===X.ACCEPTED&&!n.has(i.id)&&r.push(i.id);r.length?this._transport.open(r,null,!!this._conversation?.observer):this._transport.getTopology()===J.SERVER&&this._forceOpenTransportForAloneInCall()}_allocateParticipantTransport(e,t){this._transport&&(this._transport.getTopology()===J.DIRECT&&(t=this._directTransportIsMaster??(this._directTransportIsMaster=t)),this._transport.allocate(e,t))}_closeParticipantTransport(e){let t=this._transport?.getTopology()===J.DIRECT&&this._transport.opened().includes(e);this._transport?.close(e),t&&(this._directTransportIsMaster=void 0)}_cleanupRegistry(){z.remove(this._reservedId),z.remove(this.id),this._reservedId=null}_emitHangupOnce(e,t){this._hangupEmitted||(this._hangupEmitted=!0,L.onHangup(e,t))}_sendHangupApi(e,t){let n=this._signaling.getPeerId(),r={};n!=null&&(r.peerId=String(n)),this._api.hangupConversation(e,t,r)}_close(e,t={}){this._clearCalleeUnavailableWatchdog(),t.errorText&&this._debug.error(t.errorText,e),this._debug.debug(`Close conversation`,e),this._finishLifecycle(e),this._stats.flushCallMetrics();let n=t.signalingReason??(e.error?D.FAILED:void 0),r=n&&this._signaling.ready?this._signaling.hangup(n):void 0;this._signaling.readyToSend(!1),e.error||this._stats.logger.log(C.ERROR,e.hangup);let i=this._conversation&&this._conversation.id;if([D.CANCELED,D.NOT_FRIENDS,D.CALLEE_IS_OFFLINE,D.CALLEE_UNAVAILABLE,D.CALLER_IS_BLOCKED,D.CALLER_IS_REJECTED,D.HAS_ACTIVE_CALL].indexOf(e.hangup)!==-1||e.hangup===D.REJECTED&&!e.remote){this._emitHangupOnce(e,i),this._destroy(r);return}if(e.hangup===D.HUNGUP&&(!e.remote||this._isCalledState())){this._emitHangupOnce(e,i),this._destroy(r);return}if(e.hangup===D.MISSED&&!e.remote){this._emitHangupOnce(e,i),this._destroy(r);return}if(this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null),(e.hangup===D.SOCKET_CLOSED||e.hangup===D.NOT_FOUND)&&z.getActive()&&!this._conversation){this._disposeSignaling(r),this._cleanupMediaSource();return}if(e.hangup===D.BUSY&&!e.remote){this._disposeSignaling(r),this._cleanupMediaSource();return}this._state=`CLOSE`,this._participantState=X.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._disposeSignaling(r),this._api.cleanup(),this._api.setAbortSignal(void 0),this._stats.destroy(),this._cleanupRegistry(),this._conversation=null,this._myLastRequestedLayouts={},this._displayLayoutRequester.clear(),this._delayedHangup=!1,this._abortController=null,this._emitHangupOnce(e||new O(D.UNKNOWN_ERROR),i)}_sendHangup(e,t,n){typeof n==`function`?n({conversationId:e,reason:t,internalParams:this._buildInternalParams()},this._abortController?.signal).then(e=>{e?.success||this._debug.error(`Fast hangup was not successful`,e)}).catch(e=>{this._debug.error(`Fast hangup error`,e)}):this._sendHangupApi(e,t)}destroy(){this._destroy()}_destroy(e){this._clearCalleeUnavailableWatchdog();let t=this._conversation&&this._conversation.id;if(this._debug.debug(`Destroy conversation`,{conversationId:t}),this._stopFirstMediaSentProbe(),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null),this._state=`CLOSE`,this._participantState=X.HUNGUP,this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._disposeSignaling(e),this._delayedHangup&&t)try{this._sendHangup(t,D.CANCELED,this._onFastHangup)}catch{}this._api.cleanup(),this._api.setAbortSignal(void 0),this._cleanupListeners(),this._stats.destroy(),this._cleanupRegistry(),this._conversation=null,this._myLastRequestedLayouts={},this._displayLayoutRequester.clear(),this._delayedHangup=!1,this._abortController=null}async _getConversationParams(e){let t=await this._api.getConversationParams(e);this._debug.debug(`Api.getConversationParams`,t);let{turn_server:n,stun_server:r}=t;return M.iceServers=go(r,n),M.wssBase=t.endpoint,t.wt_endpoint&&(M.wtsBase=t.wt_endpoint),M.wssToken=t.token,t.client_type&&(M.clientType=t.client_type),t.external_user_type&&(M.externalUserType=t.external_user_type),t}_setConversationParams({turn_server:e,stun_server:t,endpoint:n,wt_endpoint:r,token:i,client_type:a}){M.iceServers=go(t,e),M.wssBase=n,M.wssToken=i,r&&(M.wtsBase=r),a&&(M.clientType=a)}_buildSignalingEndpoint({baseEndpoint:e,userId:t,type:n,deviceIdx:r,conversationId:i,token:a,conversationParams:o}){let s=new URL(e),c=s.searchParams;return c.set(`userId`,String(t)),c.set(`entityType`,n),c.set(`deviceIdx`,String(r)),c.set(`conversationId`,i),c.set(`token`,a),o?.isp_as_no&&c.set(`ispAsNo`,String(o.isp_as_no)),o?.isp_as_org&&c.set(`ispAsOrg`,o.isp_as_org),o?.loc_cc&&c.set(`locCc`,o.loc_cc),o?.loc_reg&&c.set(`locReg`,o.loc_reg),s.toString()}_clearCalleeUnavailableWatchdog(){this._calleeUnavailableTimer!==null&&(window.clearTimeout(this._calleeUnavailableTimer),this._calleeUnavailableTimer=null)}async _startConversation({opponentIds:e,opponentType:t,direction:n,mediaOptions:r,payload:i=``,joiningAllowed:a=!1,requireAuthToJoin:o=!1,onlyAdminCanShareMovie:s,externalIds:c,onFastStart:l,conversationId:u}){let d=u??j.uuid();if(z.has(d))throw new O(D.HAS_ACTIVE_CALL);z.reserve(d),this._reservedId=d,this._debug.debug(`Conversation: start`,{conversationId:d,opponentIds:e,opponentType:t,direction:n});let f=r.includes(S.VIDEO),p,m;if(l){let e;try{if(e=await l({internalParams:this._buildInternalParams(),conversationId:d,externalIds:c,payload:i,opponentType:t,mediaOptions:r,isVideo:f,joiningAllowed:a,requireAuthToJoin:o},this._abortController?.signal),!e)throw ec(D.FAST_START_ERROR,`invalid-response`,`fast-start-response-empty`);if(!e.internalCallerParams){let t=e.rejectedParticipants[0]?.status;throw ec(D.FAST_START_ERROR,t?`fast-start`:`invalid-response`,t??`fast-start-internal-caller-params-empty`,JSON.stringify(e))}}catch(e){throw this._delayedHangup&&this._abortController?.signal.aborted?new O(D.CANCELED):e instanceof O?e:e instanceof Error?new O(D.FAST_START_ERROR,{message:e.message}):new O(D.FAST_START_ERROR,{message:String(e)})}try{let t=JSON.parse(e.internalCallerParams);p={endpoint:t.endpoint,wt_endpoint:t.wtEndpoint,id:d,is_concurrent:t.isConcurrent,client_type:t.clientType,rejected_participants:e.rejectedParticipants?.map(e=>({...e,status:e.status})),stun_server:t.stun,turn_server:t.turn,token:new URL(t.endpoint).searchParams.get(`token`)??``},this._debug.debug(`FastStart`,p),m=`fastStart`}catch{throw ec(D.FAST_START_ERROR,`invalid-response`,`fast-start-internal-caller-params-invalid`)}}else p=await this._api.startConversation(d,e,t,f,i,a,o,{onlyAdminCanShareMovie:s},c),this._debug.debug(`Api.startConversation`,p),m=`startConversation`;xo(p,m),this._setConversationParams(p),this._stats.lifecycle.bindConversationId(p.id);let ee=await this._connectSignaling(br.START,p);return this._setConversation(p,ee,n),this._stats.lifecycle.markCallStarted(),ee}async _joinConversation(e){W.setMark(H.SIGNALING_CONNECTED);let{conversationId:t,mediaOptions:n,chatId:r,joinLink:i,observedIds:a,payload:o,onFastJoin:s}=e;if(this._debug.debug(`Conversation: join`,{conversationId:t,joinLink:i,observedIds:a}),t&&z.has(t))throw new O(D.HAS_ACTIVE_CALL);let c=n.includes(S.VIDEO),l,u;if(s){if(!i)throw new O(D.FAST_JOIN_ERROR,{callError:{scope:`internal`,code:`fast-join`,description:`join-link-required`}});let e;try{if(e=await s({joinLink:i,isVideo:c,internalParams:this._buildInternalParams()},this._abortController?.signal),!e)throw ec(D.FAST_JOIN_ERROR,`invalid-response`,`fast-join-response-empty`);if(!e.internalCallerParams)throw ec(D.FAST_JOIN_ERROR,`invalid-response`,`fast-join-internal-caller-params-empty`,JSON.stringify(e));if(!e.conversationId)throw ec(D.FAST_JOIN_ERROR,`invalid-response`,`fast-join-conversation-id-empty`,JSON.stringify(e))}catch(e){throw this._delayedHangup&&this._abortController?.signal.aborted?new O(D.CANCELED):e instanceof O?e:e instanceof Error?new O(D.FAST_JOIN_ERROR,{message:e.message}):new O(D.FAST_JOIN_ERROR,{message:String(e)})}try{let t=JSON.parse(e.internalCallerParams);if(z.has(e.conversationId))throw new O(D.HAS_ACTIVE_CALL);l={endpoint:t.endpoint,wt_endpoint:t.wtEndpoint,id:e.conversationId,is_concurrent:t.isConcurrent,client_type:t.clientType,stun_server:t.stun,turn_server:t.turn,token:new URL(t.endpoint).searchParams.get(`token`)??``},this._debug.debug(`FastJoin`,l),u=`fastJoin`}catch(e){throw e instanceof O?e:ec(D.FAST_JOIN_ERROR,`invalid-response`,`fast-join-internal-caller-params-invalid`)}}else if(t)l=await this._api.joinConversation(t,c,r),u=`joinConversation`;else if(i)l=await this._api.joinConversationByLink(i,c,a,o),u=`joinConversationByLink`;else throw new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`join`,description:`target-missing`}});if(this._debug.debug(`Api.joinConversation`,l),l.id&&this._stats.lifecycle.bindConversationId(l.id),xo(l,u),l.id){if(z.has(l.id))throw new O(D.HAS_ACTIVE_CALL);z.reserve(l.id),this._reservedId=l.id}this._setConversationParams(l);let d=await this._connectSignaling(br.JOIN,l);return this._setConversation(l,d,Wa.JOINING),this._stats.lifecycle.markCallStarted(),d}async _prepareConversation(e,t=A.USER,n,r,i){W.setMark(H.SIGNALING_CONNECTED),this._debug.debug(`Conversation: push`,{conversationId:e,type:t,peerId:n});let a=this._api.getUserId();if(!a)throw new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`incoming`,description:`user-id-missing`}});let o=0,s=``,c=``,l={id:e,peerId:n,endpoint:s,wt_endpoint:c,is_concurrent:!1,p2p_forbidden:!1,device_idx:0,token:``};if(r){let n=this._decodeExternalConversationParams(r);this._setConversationParams(n),s=i??this._buildSignalingEndpoint({baseEndpoint:M.wssBase,userId:a,type:t,deviceIdx:o,conversationId:e,token:M.wssToken}),l.token=n.token,l.endpoint=s,M.wtsBase&&(c=this._buildSignalingEndpoint({baseEndpoint:M.wtsBase,userId:a,type:t,deviceIdx:o,conversationId:e,token:M.wssToken}),l.wt_endpoint=c)}else{let n=await this._getConversationParams(e);o=n.device_idx||0,s=i??this._buildSignalingEndpoint({baseEndpoint:M.wssBase,userId:a,type:t,deviceIdx:o,conversationId:e,token:M.wssToken,conversationParams:n}),l.token=n.token,l.endpoint=s,l.device_idx=o,M.wtsBase&&(c=this._buildSignalingEndpoint({baseEndpoint:M.wtsBase,userId:a,type:t,deviceIdx:o,conversationId:e,token:M.wssToken,conversationParams:n}),l.wt_endpoint=c)}let u=await this._connectSignaling(br.ACCEPT,l);return z.callsLength>=M.maxParallelCalls||!M.hold&&z.callsLength>0?(this._debug.log(`Push rejected (busy)`),this._stats.logger.log(C.PUSH,`busy`),Promise.reject(new O(D.BUSY))):(this._setConversation(l,u,Wa.INCOMING,t),u)}_createParticipant(e,t,n=!0){let r=Object.assign({id:null,externalId:null,mediaSettings:E(),participantState:{},state:X.CALLED,connectionStatus:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[],isInRoom:!1,markers:null},e),i=!!r.externalId;if(!i){let e=this._getParticipantId(t??r.id);e&&(r.externalId=e)}return n&&i&&this._api.cacheExternalId(t??r.id,r.externalId),t&&this._api.mapDecorativeId(t,r.id),r.observedIds?.length&&r.externalId&&(r.externalId.observer=!0),e.markers&&(r.markers=this._denormalizeMarkers(r.id,e.markers)),r.connectionStatus=io.create(r.connectionStatus),r}_getParticipantId(e){let t=this._api.userId(e);if(t)return t;let{compositeUserId:n,deviceIdx:r}=j.decomposeParticipantId(e),{id:i,type:a}=j.decomposeId(n);return a===A.GROUP?Z.fromId(String(i),void 0,r):null}_cacheParticipantExternalIds(e){e.forEach(e=>{let t=j.composeId(e),n=Z.fromSignalingParticipant(e,!1);if(n){this._api.cacheExternalId(t,n);let r=j.composeDecorativeId(e),i=Z.fromSignalingParticipant(e);r&&i&&(this._api.cacheExternalId(r,i),this._api.mapDecorativeId(r,t))}})}_setConversation(e,t,n,r=A.USER){let{participants:i}=t.conversation;t.conversationParams?.serverTime&&(this._serverTimeOffset=t.conversationParams.serverTime-Date.now()),this._cacheParticipantExternalIds(i);let a=this._api.getUserId(),o=this._extractLocalParticipantFromConnection(t),s=e.device_idx||0;if(!a){if(!o)throw new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`conversation`,description:`anonymous-local-participant-missing`}});a=Number(o.id),o.idType&&(r=o.idType),o.deviceIdx&&(s=o.deviceIdx),this._api.setUserId(a)}let c=j.composeParticipantId(a,r,s);this._conversation={userId:a,compositeUserId:c,externalId:this._getExternalIdByParticipantId(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||J.DIRECT,direction:n,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:o?.roles??[],recordsInfoByRoom:new Map,asrInfoByRoom:new Map,muteStates:new Map,muteStatesPersonal:{},joinLink:e.join_link??t.conversation.joinLink,pinnedParticipantIdByRoom:new Map,mediaModifiers:t.mediaModifiers,options:[],networkRating:1,waitingHall:this._isInWaitingHall(t),waitForAdmin:this._isWaitForAdmin(t),observer:!1,asrInfo:t.conversation.asrInfo||null,roomId:t.rooms?.roomId||null,audienceMode:this._isAudienceMode(t),restricted:this._isRestricted(t),urlSharingInfoByRoom:new Map},this._debug.setConversationId(t.conversation.id||e.id),e.p2p_forbidden&&(M.forceRelayPolicy=e.p2p_forbidden),this._stats.logger.log(C.RELAY_POLICY,M.forceRelayPolicy?`1`:`0`);let l=z.get(this._conversation.id);if(l&&l!==this)this._conversation.concurrent=!0;else if(!M.hold&&z.callsLength>0)throw new O(D.HAS_ACTIVE_CALL);this._changeFeatureSet(),this._changeFeaturesPerRole(),this._logDevices()}_updateConversation(e){if(!this._conversation)throw new O(D.UNKNOWN_ERROR,{callError:{scope:`internal`,code:`conversation`,description:`update-without-conversation`}});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||J.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1,this._conversation.waitForAdmin=!1,this._conversation.restricted=!1,this._cacheParticipantExternalIds(e.conversation.participants??[])}_createMediaSource(){let e=new Zt(this._debug,this._stats.logger);return this.subscribe(e,Yt.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Yt.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new yo(e,this._debug,this._stats.logger),e}async _connectSignaling(e,t){this._signaling.setEndpoint(t.endpoint),this._signaling.setWebTransportEndpoint(t.wt_endpoint?t.wt_endpoint:null),this.subscribe(this._signaling,G.NOTIFICATION,e=>this._signalingActor.add(e)),this.subscribe(this._signaling,G.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,G.RECONNECT,this._onSignalingReconnect.bind(this));let n=await this._signaling.connect(e,t);return this._stats.statAggregator.logEventualStatSinceMark({name:H.SIGNALING_CONNECTED}),n}async _processConnection(e){await this._registerConnectionParticipants(e),this._processRooms(e),this._processMuteStates(e),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Ka.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants,null,null)}_onConversationParticipantListChunk(e){let t=e.participants;t&&L.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(this._createParticipantListChunk(t)),this.id)}_createParticipantListChunk(e){return{participants:[],countBefore:0,countAfter:0,markerFound:!1,...e}}_participantListChunkToExternalChunk(e){let t=this._participants,n=j.mapSharedParticipants(e.participants.reduce((e,n)=>{let r=j.composeId(n);return t[r]&&e.push(t[r]),e},[]));return{...e,participants:n}}async _registerConnectionParticipants(e){await this._registerParticipants(e.conversation.participants),e.participants?.participants&&await this._registerParticipants(e.participants?.participants);let t=e?.rooms?.rooms??[];for(let e of t)await this._registerParticipants(e?.participants?.participants??[],!0)}async _registerParticipants(e,t=!1){if(!this._conversation)return;let n=e[0]?.externalId?.type;n&&(M.externalUserType=n);let r=this._participants;for(let n of e){let e=j.composeId(n);if(R.test(`Conversation:RegisterParticipant`,e),this._isMe(e)){this._conversation.roles=n.roles||[],this._conversation.roles.length&&(this._debug.debug(`Local roles changed: ${n.roles}`),L.onLocalRolesChanged(this._conversation.roles,!0,this.id)),this._registerParticipantLocalMuteState(n);continue}if(n.state===X.HUNGUP||n.state===X.REJECTED){r[n.id]&&await this._removeParticipant(r[n.id],D.HUNGUP);continue}let i=j.composeDecorativeId(n);this._registerParticipant({id:e,externalId:Z.fromSignalingParticipant(n,!0,!0),mediaSettings:E(n.mediaSettings),participantState:j.mapParticipantState(n),state:n.state,roles:n.roles||[],connectionStatus:this._buildConnectionStatus(e,n.sessionState,void 0,n.onHold),isOnHold:!!n.onHold,muteStates:n.muteStates||{},unmuteOptions:n.unmuteOptions||[],observedIds:n.observedIds||[],markers:this._denormalizeMarkers(e,n.markers),movieShareInfos:n.movieShareInfos,isInRoom:t},i);let a=this._getParticipant(e);a&&n.roles&&n.roles.length&&(this._debug.debug(`Roles for participant [${e}] changed: ${n.roles}`),L.onRolesChanged(a.externalId,n.roles,!0,this.id)),a&&a.isOnHold&&L.onRemoteStatus([a.externalId],N.ONHOLD,null,this.id)}}_registerParticipantLocalMuteState({muteStates:e,unmuteOptions:t}){if(!e)return;let n=async()=>{let n=co(e,Za.MUTE),r=co(e,Za.MUTE_PERMANENT);for(let i of[n,r])i.length&&await this._onMuteParticipant({muteStates:e,unmuteOptions:t,mediaOptions:i,stateUpdated:!0})};j.setImmediate(()=>n().catch(e=>this._debug.error(e)))}_remoteParticipantSessionState(e,t){if(!(!M.enableSessionStateUpdates||this._isMe(e)))return t}_buildConnectionStatus(e,t,n,r=!1){return io.create({transport:r?N.ONHOLD:io.fromTransportState(n)??N.WAITING,sessionState:this._remoteParticipantSessionState(e,t),sessionStateApplicable:this._isParticipantSessionStateApplicable(e)})}_isParticipantSessionStateApplicable(e){return M.enableSessionStateUpdates&&!this._isMe(e)&&this._conversation?.topology===J.SERVER}_setTransportStatus(e,t){return io.setTransport(e.connectionStatus,t)}_setSessionState(e,t){let n=io.setSessionStateApplicable(e.connectionStatus,this._isParticipantSessionStateApplicable(e.id));this._emitParticipantTransition(e,n);let r=e.connectionStatus.sessionStateApplicable&&e.id===this._activeSpeakerId&&e.connectionStatus.transport===N.CONNECTED,i=io.setSessionState(e.connectionStatus,t,r);return this._emitParticipantTransition(e,i),i}_emitParticipantTransition(e,t,n=null){t.shouldNotify&&L.onRemoteStatus([e.externalId],t.status,n,this.id)}_registerParticipantInCache(e){return this._participants[e.id]=e,e}_getExistedParticipantByIdOrCreate(e){let t=this._participants[e];if(t)return t;let n=this._api.getDecorativeIdByInitialId(e),r=this._getParticipantId(e),{deviceIdx:i}=j.decomposeParticipantId(e);return this._createParticipant({id:e,externalId:r?{...r,deviceIdx:i}:void 0},n,!1)}_getExternalIdByParticipantId(e){if(this._isMe(e))return this._conversation?.externalId??null;if(M.useParticipantListChunk)return this._getExistedParticipantByIdOrCreate(e).externalId;let t=this._participants;if(t[e]?.externalId)return t[e].externalId;let n=this._api.getCachedExternalIdByParticipantId(e);if(n)return n;let r=this._getParticipantId(e);return r&&this._api.cacheExternalId(e,r),r}_getExternalIdsByParticipantIds(e){let t=[],n=[];return e.forEach(e=>{let r=this._getExternalIdByParticipantId(e);r?t.push(r):n.push(e)}),{externalIds:t,missingIds:n}}_reportMissingExternalIds(e,t){e.length&&this._onNonFatalError(`External ID mapping not found for participants "${Array.from(new Set(e)).join(`", "`)}" while handling ${t}`)}_reportMissingExternalIdsById(e,t){e.length&&this._onNonFatalError(`Participant ID mapping not found for external IDs "${Array.from(new Set(e)).join(`", "`)}" while handling ${t}`)}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){if(M.useParticipantListChunk){let n=this._registerParticipantInCache(this._getExistedParticipantByIdOrCreate(e));return n.markers=this._denormalizeMarkers(n.id,t),n}return this._participants[e]}_warnParticipantNotInConversation(e){this._debug.warn(`Participant [${e}] isn't in conversation`)}_denormalizeMarkers(e,t){if(!t)return null;let n=Object.values(t).find(e=>`ts`in e&&`rank`in e);return Object.entries(t).reduce((t,[r,i])=>(t[r]={...n,...i,id:e},t),{})}_processRooms(e){let t=e.rooms?.roomId??null;this._onRoomSwitched(t,!0)}_processMuteStates(e,t=!1){let n=lo(e);this._setMuteStatesForRoomId(n,null);for(let t of e.rooms?.rooms??[])this._setMuteStatesForRoomId(t.muteStates,t.id);let r=this._getMuteStatesForCurrentRoom();t&&(r=mo(e,r));let i=Object.keys(r),a=this._conversation?.roomId;i.length&&this._onMuteParticipant({muteStates:r,mediaOptions:i,muteAll:!0,stateUpdated:!0,roomId:a},t)}_processRecordInfos(e){this._onRecordInfo(e.conversation?.recordInfo??null);for(let t of e.rooms?.rooms??[])this._onRecordInfo(t.recordInfo??null,t.id)}_processPinnedParticipants(e){e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId):this._conversation?.pinnedParticipantIdByRoom.delete(null);for(let t of e.rooms?.rooms??[])t.pinnedParticipantId?this._onPinParticipant(t.pinnedParticipantId,!1,void 0,t.id):this._conversation?.pinnedParticipantIdByRoom.delete(t.id)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new fa(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings,this._debug,this._stats.logger,this._stats.statAggregator,this._stats.codecStatsAggregator,this._getFirstMediaSentCallback()),this._debugInfo=new Eo(this._debug),this.subscribe(this._transport,Y.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,Y.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,Y.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,Y.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,Y.AUDIO_MIX_STALL,this._onAudioMixStall.bind(this)),this.subscribe(this._transport,Y.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,Y.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,Y.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,Y.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,Y.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,Y.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this)),this.subscribe(this._transport,Y.ASR_TRANSCRIPTION,this._onAsrTranscription.bind(this)),this.subscribe(this._transport,Y.ANIMOJI_STREAM,this._onAnimojiStream.bind(this)),this.subscribe(this._transport,Y.ANIMOJI_ERROR,this._onAnimojiError.bind(this));let e=this._conversation.direction===Wa.OUTGOING&&!this._conversation.concurrent,t=this._participants;for(let n of Object.values(t))(n.state===X.ACCEPTED||n.state===X.CALLED)&&this._allocateParticipantTransport(n.id,e)}_createSpeakerDetector(){this._transport&&this._conversation&&(this._volumesDetector=new No(this._transport),this.subscribe(this._volumesDetector,Mo.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Fo(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,Po.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Ao(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Ro(this._transport,this._volumesDetector,this._participants,this._debug,this._stats.logger))}_logDevices(){let e=T.getCameras().length,t=T.getMicrophones().length;this._debug.debug(`Cameras: `+e+(T.hasCameraPermission()?`✔`:`✖`)+`, Microphones: `+t+(T.hasMicrophonePermission()?`✔`:`✖`)),this._stats.logger.log(C.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){this._stats.logger.log(e,[t?.isAudioEnabled&&`audio`,t?.isVideoEnabled&&`video`].filter(Boolean).join(`_`))}async _removeParticipant(e,t){if(e.state===X.CALLED||e.state===X.ACCEPTED||this._state===`CLOSE`)return;e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null);let n=this._participants;if(n[e.id]){t===D.HUNGUP?this._setParticipantsStatus([e],N.HANGUP):this._setParticipantsStatus([e],N.ERROR,t),e.mediaSource?.disconnect(),this._displayLayoutRequester.cleanupParticipant(e.id),this._conversation&&this._conversation.pinnedParticipantIdByRoom.get(null)===e.id&&this._conversation.pinnedParticipantIdByRoom.delete(null),this._conversation&&this._conversation.roomId&&this._conversation.pinnedParticipantIdByRoom.get(this._conversation.roomId)===e.id&&this._conversation.pinnedParticipantIdByRoom.delete(this._conversation.roomId);for(let[t,n]of Object.entries(e.lastRequestedLayouts))this._streamIdByStreamDescription.delete(t),this._sequenceNumberByStreamDescription.delete(t),this._cooldownTimestampByStreamDescription.delete(t),this._streamWaitTimerByStreamDescription.has(t)&&(window.clearTimeout(this._streamWaitTimerByStreamDescription.get(t)),this._streamWaitTimerByStreamDescription.delete(t)),this._sendUpdateDisplayLayout({[t]:{stopStream:!0}},!1);this._api.unmapDecorativeId(e.id),delete n[e.id],L.onRemoteRemoved(e.externalId,e.markers,this.id)}}_cleanupListeners(){this.unsubscribe(),window.removeEventListener(`pagehide`,this._onUnload),window.removeEventListener(`pageshow`,this._onRestore)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{e.remoteStream?.getTracks().forEach(e=>e.stop()),e.remoteAudioTrack?.stop(),e.secondStream?.getTracks().forEach(e=>e.stop()),e.mediaSource?.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){this._debug.debug(`cleaning up participant-agnostic streams`),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(e=>{e.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)}_finishLifecycle(e){this._stopFirstMediaSentProbe(),this._stats.logHangup(e)}_getFirstMediaSentCallback(){let{lifecycle:e}=this._stats;return e.firstMediaSentReported||e.terminated?null:()=>e.markFirstMediaSent()}_stopFirstMediaSentProbe(){this._transport?.stopFirstMediaSentProbe?.()}_cleanupTransportForHold(){this._transport&&(this._transport.holdClose(),this._transport=null),this._debugInfo&&(this._debugInfo=null),this._cleanupSpeakerDetector(),this._cleanupSpecListener()}_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)}_disposeSignaling(e){if(!e){this._signaling.dispose();return}e.catch(e=>{e instanceof En||this._debug.warn(`[signaling] unable to send hangup`,e)}).finally(()=>this._signaling.dispose())}async _onAddParticipant(e,t,n){this._debug.debug(`Add new participant [${e}]`);let r=this._getParticipant(e);r&&this._updateParticipantExternalId(r,t);let i=!r;if(r&&(r.state===X.ACCEPTED||r.state===X.CALLED)){this._debug.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}if(!r){let n=j.composeDecorativeId(t);this._registerParticipant({id:e,externalId:Z.fromSignalingParticipant(t,!0,!0),mediaSettings:E(t.mediaSettings),state:t.state,roles:t.roles||[],connectionStatus:this._buildConnectionStatus(e,t.sessionState,this._transport?.getState(),t.onHold),isOnHold:!!t.onHold,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]},n),r=this._getParticipant(e)}this._setParticipantsStatus([r],N.WAITING),i&&this._emitParticipantEffectiveStatusIfSessionOverridesTransport(r),n?(r.state=X.HUNGUP,await this._removeParticipant(r,n)):this._transport&&(r.state=X.CALLED,this._allocateParticipantTransport(r.id,!0),this._stats.logger.log(C.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))}_onRemoveParticipant(e){this._debug.debug(`Remove participant [${e}]`);let t=[],n=this._participants;for(let r=0;r<=tc;r++){let i=n[j.compose(e,r)];i&&t.push(i)}if(!t.length){this._warnParticipantNotInConversation(e);return}for(let e of t)this._closeParticipantTransport(e.id);this._stats.logger.log(C.REMOVE_PARTICIPANT)}async changeDevice(e){return e===`audiooutput`?this._audioOutput.changeOutput():this._mediaSource?this._mediaSource.changeDevice(e):Promise.reject(x.UNKNOWN)}stopVideoTrack(){return this._mediaSource?.stopVideoTrack()}async toggleScreenCapturing(e){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(x.UNKNOWN)}async disableScreenCapturing(){return this._mediaSource?this._mediaSource.disableScreenCapturing():Promise.reject(x.UNKNOWN)}toggleAnimojiCapturing(e){this._mediaSource&&this._mediaSource.toggleAnimojiCapturing(e)}setAnimojiSvg(e,t=null,n=null){if(!this._transport||!this._conversation)return;let r=!t,i=t??this._conversation.compositeUserId;if(e instanceof ArrayBuffer){let t=n??this._conversation.externalId.id;this._transport.setAnimojiSvg(i,{svg:e,userId:t,isMe:r});return}this._transport.setAnimojiSvg(i,{svg:e,isMe:r})}setAnimojiFill(e){this._transport?.setAnimojiFill(e)}async setVideoStream(e,t=!1){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)}async setAudioStream(e){if(this._mediaSource)return this._mediaSource.setAudioStream(e)}toggleLocalVideo(e){return this._toggleLocalVideo(e)}toggleLocalAudio(e){return this._toggleLocalAudio(e)}async changePriorities(e){if(e.length<2||!this._signaling.ready)return;let t={},n={};for(let t of e){let e=typeof t.uid==`object`?t.uid:Z.fromId(t.uid),r=Z.toString(e);n[r]=t.priority}let r=this._participants;for(let e of Object.values(r)){let r=Z.toString(e.externalId);Object.hasOwn(n,r)&&(t[e.id]=n[r])}await this._signaling.changePriorities(t)}async changeParticipantState(e,t){for(let[t,n]of Object.entries(e))if(t.length>5||n.length>5)throw Error(`key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded`);t&&!this._isCallAdmin()&&(t=void 0),await this._signaling.changeParticipantState(e,t)}async hold(e,t){if(e){if(this._state===`HELD`)return;if(this._isWaitingForPromotion()){this._waitingHallHoldPending=!0,await this._holdLocally();return}await Promise.all([this._holdLocally(),this._signaling.hold(!0)]);return}if(this._isWaitingForPromotion()){this._waitingHallHoldPending=!1,await this._resumeLocalMedia(t,this._getWaitingForPromotionStatus()),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener();return}let n=Sa.get();await this._signaling.hold(!1,n),this._restoreStateAfterHold();let r=null;if(this._state===`IDLE`&&this._participantState===X.ACCEPTED&&(r=Object.values(this._participants),r.some(e=>e.state===X.ACCEPTED)&&(this._state=`ACTIVE`,this._changeFeatureSet())),await this._resumeLocalMedia(t,N.WAITING),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._state===`ACTIVE`){let e=this._conversation?.direction===Wa.OUTGOING&&!this._conversation.concurrent;this._openTransport(r??Object.values(this._participants),e)}}async _holdLocally(){this._state!==`HELD`&&(this._previousState=this._state,this._state=`HELD`);let e=this._mediaSource?.stopLocalMedia();this._cleanupTransportForHold(),L.onLocalStatus(N.ONHOLD,this.id),await e}async _resumeLocalMedia(e,t){this._restoreStateAfterHold(),await this._mediaSource?.resumeLocalMedia(e),L.onLocalStatus(t,this.id),this._mediaSource&&L.onLocalStream(this._mediaSource?.getStream()??null,this._mediaSource.mediaSettings,this.id)}_restoreStateAfterHold(){this._state===`HELD`&&(this._state=this._previousState||`ACTIVE`,this._previousState=null)}_isWaitingForPromotion(){return!!this._conversation?.waitingHall||!!this._conversation?.waitForAdmin}_getWaitingForPromotionStatus(){return this._conversation?.waitForAdmin?N.WAIT_FOR_ADMIN:N.WAITING_HALL}async putHandsDown(){this._checkAdminRole(),await this._signaling.putHandsDown()}async requestKeyFrame(e){let t={};return t[Pn(e)]={keyFrameRequested:!0},this._signaling.updateDisplayLayout(t)}async requestTestMode(e,t){return this._signaling.requestTestMode(e,t)}async updateDisplayLayout(e){if(e.length<1||!this._signaling.ready)return;this._debug.log(`Update display layout request [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={},n=[],r=[],i=this._participants;for(let a of e){let e=typeof a.uid==`object`?a.uid:Z.fromId(a.uid),o=this._api.getCachedParticipantIdByExternalId(e);if(!o){let t=Z.toString(e);this._debug.log(`Unknown participant external ID ${t}`),r.push(e.id);continue}let s=Pn({participantId:o,mediaType:a.mediaType,streamName:a.streamName}),c=i[o];c?n.push(()=>{c.lastRequestedLayouts[s]=a}):this._isMe(o)&&n.push(()=>{this._myLastRequestedLayouts[s]=a}),kn(a)?(this._isMe(o)&&n.push(()=>{delete this._myLastRequestedLayouts[s]}),this._streamIdByStreamDescription.has(s)&&!this._cooldownTimestampByStreamDescription.has(s)&&this._cooldownTimestampByStreamDescription.set(s,Date.now())):(this._cooldownTimestampByStreamDescription.delete(s),!this._streamIdByStreamDescription.has(s)&&M.videoTracksCount>0&&this._streamIdByStreamDescription.set(s,null),t[s]=a),a.mediaType===V.SCREEN&&!kn(a)&&W.setMark(W.getMarkNameScreenshareFirstFrame(o))}if(r.length){this._reportMissingExternalIdsById(r,`updateDisplayLayout`);return}let a=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>M.videoTracksCount;){let e=a.next();if(e.done){this._debug.error(`Cannot accommodate all streaming requests: tracks available `+M.videoTracksCount+`; requested streams: `+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(e.value),t[e.value]={stopStream:!0}}if(this._transport?.getTopology()!==J.SERVER){n.forEach(e=>e());return}await this._sendUpdateDisplayLayout(t),n.forEach(e=>e())}async requestDisplayLayout(e){return this._displayLayoutRequester.request(e)}async 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)&&(this._debug.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 t=this._participants,n=Fn(e),r=t[n.participantId],i=this._conversation?.externalId,a=this._isMe(n.participantId);if(r||a){switch(n.mediaType){case V.STREAM:case V.MOVIE:if(n.streamName){let e={stream:null,streamName:n.streamName,mediaType:n.mediaType};a?L.onLocalLive(i,e,this.id):L.onRemoteLive(r.externalId,e,this.id)}break;case V.CAMERA:L.onRemoteStream(r.externalId,null,this.id);break;case V.SCREEN:L.onRemoteScreenStream(r.externalId,null,this.id);break}this._stats.logger.log(C.PAT_DEALLOCATED)}else this._debug.log(`Cannot find participant to stop streaming: ${n.participantId}`)}this._streamIdByStreamDescription.delete(e)}async _sendUpdateDisplayLayout(e,t=!0){if(Object.keys(e).length===0)return;this._debug.log(`Update display layout send [${this._signaling.getNextCommandSequenceNumber()}]`,e);let n;try{if(n=await this._signaling.updateDisplayLayout(e),!n)return}catch(n){if(this._debug.warn(`Failed to update display layout ${JSON.stringify(e)}. ${n}`),t)throw n;return}let r=[],i=this._participants;for(let[e,t]of Object.entries(n.errorCodeByParticipantId||{})){let n=Fn(e),a=i[n.participantId];if(a){let e;typeof t==`number`?e=eo(t):(this._debug.warn(`Unexpected error code ${t} received for participant ${n.participantId}`),e=$a.UNKNOWN_ERROR),r.push({externalId:a.externalId,errorReason:e})}}if(r&&r.length&&(this._debug.warn(`Could not allocate one or more participants`,r),t))throw new rc(`Could not allocate one or more participants`,r)}async _cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let n=t.next();if(n.done)break;let r=n.value;if(r[1]+$s>Date.now())break;let i=r[0];await this._stopStreaming(i),e[i]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e,!1)}_onParticipantSourcesUpdate(e){if(this._conversation){let t=e.participantUpdateInfos;this._debug.log(`Received participant sources update notification`,t);for(let e of t)this._waitForStreamIfNeeded(e)}}async _onParticipantPromoted(e){this._conversation&&this._conversation.audienceMode?(this._debug.log(`Promoted in audience mode`,!e.demote),this._conversation.restricted=e.demote,this._processRecordInfos(e),!e.demote&&this._mediaSource&&this._changeMediaSettings(this._mediaSource.mediaSettings)):(this._debug.log(`Promoted in waiting hall`,!e.demote),e.demote?(this._debug.log(`Kicked from waiting hall`),this._close(new O(D.REMOVED))):(this._updateConversation(e),this._waitingHallHoldPending?(await this._signaling.hold(!0),await this._onJoinPart2(e,!1),this._waitingHallHoldPending=!1):z.getActive()&&M.hold?(await this._signaling.hold(!0),await this._onJoinPart2(e,!0,!0),this._waitingHallHoldPending=!1):await this._onJoinPart2(e))),L.onPromoted(e.demote,this.id)}_onChatRoomUpdated(e,t=0,n=[],r,i){this._debug.log(`Chat room updated: ${e}`);let a=[],o=[];n.length&&n.forEach(e=>{if(e.externalId){let t=Z.fromSignaling(e.externalId);a.push(t),this._api.cacheExternalId(e.id.id,t)}else{let t=this._getExternalIdByParticipantId(e.id.id);t?a.push(t):o.push(e.id.id)}});let{externalIds:s,missingIds:c}=this._getExternalIdsByParticipantIds(r??[]);o.push(...c);let{externalIds:l,missingIds:u}=this._getExternalIdsByParticipantIds(i??[]);o.push(...u),this._reportMissingExternalIds(o,`CHAT_ROOM_UPDATED`),L.onChatRoomUpdated(e,t,a,s,l,this.id)}_onSharedMovieUpdate(e){let t=this._conversation?.externalId;for(let n of e.data)if(this._isMe(n.participantId))L.onLocalLiveUpdate(t,n,this.id);else{let e=this._getExternalIdByParticipantId(n.participantId);e&&L.onRemoteLiveUpdate(e,n,this.id)}}_onSharedMovieInfoStarted(e){this._debug.log(`Shared movie started data received: ${e.notification}`),this._processSharedMovieInfo(e.movieShareInfo,e.roomId)}_processSharedMovieInfos(e,t=null){e&&e.forEach(e=>this._processSharedMovieInfo(e,t))}_processSharedMovieInfo(e,t=null){if(!e)return;let n=this._conversation?.externalId;if(this._isMe(e.initiatorId))L.onLocalSharedMovieInfo(n,e,t,this.id);else{let n=this._getExternalIdByParticipantId(e.initiatorId);n&&L.onRemoteSharedMovieInfo(n,e,t,this.id)}}_processConnectionSharedMovieInfo(e){let t=e.conversation.participants.find(e=>this._isMe(j.composeId(e)));this._processSharedMovieInfos(t?.movieShareInfos,e?.rooms?.roomId??null)}_processConnectionAsrInfo(e){let t=e?.conversation.asrInfo??this._conversation?.asrInfo;if(t&&this._conversation?.asrInfoByRoom.set(null,t),e?.rooms?.rooms)for(let t of e.rooms.rooms)t.asrInfo&&this._conversation?.asrInfoByRoom.set(t.id,t.asrInfo);let n=e?.rooms?.roomId??this._conversation?.roomId??null,r=this._conversation?.asrInfoByRoom.get(n);if(r){let e=this._getExternalIdByParticipantId(r.initiatorId);e&&L.onAsrSet({externalId:e,movieId:r.movieId},n,this.id)}else n&&L.onAsrSet(null,n,this.id)}_processConversationUrlSharingInfo(e){if(!this._conversation)return;e&&this._extractConnectionUrlSharingInfo(e);let{urlSharingInfoByRoom:t}=this._conversation,n=this._conversation.roomId,r=t.get(n);if(r&&!this._isMe(r.initiatorId)){let e=this._getExternalIdByParticipantId(r.initiatorId);e&&L.onRemoteSharedUrl(e,r.sharedUrl,n,this.id)}}_extractConnectionUrlSharingInfo(e){if(!this._conversation)return;let{urlSharingInfoByRoom:t}=this._conversation;if(e.conversation.urlSharingInfo?t.set(null,e.conversation.urlSharingInfo):t.delete(null),e.rooms?.rooms)for(let n of e.rooms.rooms)n.urlSharingInfo?t.set(n.id,n.urlSharingInfo):t.delete(n.id)}_onSharedMovieInfoStopped(e){this._debug.log(`Shared movie stopped data received: ${e.notification}`);let t=this._conversation?.externalId,{initiatorId:n,movieId:r,source:i,roomId:a=null}=e,o={initiatorId:n,movieId:r,source:i};if(this._isMe(n))L.onLocalSharedMovieStoppedInfo(t,o,a,this.id);else{let e=this._getExternalIdByParticipantId(n);if(e){let t=this._participants[n];t?.movieShareInfos&&(t.movieShareInfos=t.movieShareInfos.filter(e=>e&&e.movieId!==r)),L.onRemoteSharedMovieStoppedInfo(e,o,a,this.id)}}}_onUrlSharingInfoUpdated(e){if(this._debug.log(`Shared URL data received: ${e.notification}`),!this._conversation)return;let{urlSharingInfoByRoom:t,roomId:n}=this._conversation,{initiatorId:r,sharedUrl:i,roomId:a=null}=e;if(i?t.set(a,{sharedUrl:i,initiatorId:r}):t.delete(a),!(!i&&a!==n&&t.has(n))&&(!i||!this._isMe(r))){let e=this._getExternalIdByParticipantId(r);e&&L.onRemoteSharedUrl(e,i,a,this.id)}}_onFeaturesPerRoleChanged(e){this._debug.log(`Features per role changed: ${e.notification}`),this._conversation&&(this._conversation.featuresPerRole=e.featuresPerRole??{}),L.onFeaturesPerRoleChanged(e.featuresPerRole,this.id)}async _waitForStreamIfNeeded(e){if(e.fastScreenShare&&!e.participantStreamDescription){let t=this._getStreamDescriptionById(e.streamId);if(t){let e=Fn(t),n=this._getParticipant(e.participantId);L.onRemoteScreenStream(n.externalId,null,this.id);return}}let t=this._matchStreamDescription(e.participantStreamDescription);if(!t)return;let{mediaType:n,participantId:r}=t;if(n===V.ANIMOJI)return;let i=this._getParticipant(r);if(n===V.SCREEN&&!e.fastScreenShare){this._debug.log(`skipping participant-sources-update notification since screenshare will be received over datachannel`);return}let a=Pn(t),o=this._sequenceNumberByStreamDescription.get(a);if(o&&o>e.sequenceNumber){this._debug.warn(`Participant ${r} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${o}`),this._stats.logger.log(C.PAT_OUTDATED_RESPONSE);return}i&&e.suspend!==void 0&&n&&(this._debug.debug(`participant-sources-update: mediaType=${n}, suspend=${e.suspend}`),L.onRemoteStreamSuspended(i.externalId,n,e.suspend,this.id));let s=e.streamId,c=e.rtpTimestamp?this._getWaitingTime(s,e.rtpTimestamp):0;if(c<=0){this._streamWaitTimerByStreamDescription.delete(a);let t=this._conversation?.externalId,n=this._isMe(r);if(!i&&!n){this._stats.logger.log(C.PAT_ERROR,`participantMissing`),this._debug.error(`Could not find participant by ID: ${r}`);return}let o=n?t:i.externalId,c=this._streamByStreamId.get(s);if(!c){this._stats.logger.log(C.PAT_ERROR,`streamNotFound`),this._debug.error(`Could not find stream by ID: ${s}`);return}this._stats.logger.log(C.PAT_ALLOCATED),this._streamIdByStreamDescription.set(a,s);let l=e.participantStreamDescription?.mediaType;if(l===V.STREAM||l===V.MOVIE){if(e.participantStreamDescription?.streamName){let t={streamName:e.participantStreamDescription.streamName,stream:c,mediaType:l};n?L.onLocalLive(o,t,this.id):L.onRemoteLive(o,t,this.id)}}else l===V.SCREEN?L.onRemoteScreenStream(i.externalId,c,this.id):n||L.onRemoteStream(i.externalId,c,this.id)}else{this._debug.debug(`Waiting for ${c} until stream ${s} for ${a} is switched`);let t=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),c);this._streamWaitTimerByStreamDescription.set(a,t)}}_getStreamDescriptionById(e){for(let[t,n]of this._streamIdByStreamDescription.entries())if(n===e)return t;return null}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Pn(e)))return e;let t=e.participantId;if(e.mediaType){let e={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Pn(e)))return e}else{let e={participantId:t,mediaType:V.CAMERA};if(this._streamIdByStreamDescription.has(Pn(e)))return e;let n={participantId:t,mediaType:V.SCREEN};if(this._streamIdByStreamDescription.has(Pn(n)))return n}return this._debug.error(`Received unrequested allocation`,e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw Error(`transport is not initialized`)}_isCallAdmin(){return this._conversation?j.includesOneOf(this._conversation.roles,[to.ADMIN,to.CREATOR]):!1}_checkAdminRole(){if(this._conversation&&!j.includesOneOf(this._conversation.roles,[to.ADMIN,to.CREATOR]))throw Error(`You don't have the required permission`)}_isCalledState(){return this._participantState===X.CALLED}async grantRoles(e,t,n){this._checkAdminRole(),await this._signaling.grantRoles(e,t,n)}async startAsr(e){await this._signaling.startAsr(e)}async stopAsr(e){await this._signaling.stopAsr(e)}async requestAsr(e){this._isRealTimeAsrRequested=e,await this._signaling.requestAsr(e)}async muteParticipant(e=null,t,n=[],r=null){this._checkAdminRole(),await this._signaling.muteParticipant(e,t,n,r)}async enableFeatureForRoles(e,t){await this._signaling.enableFeatureForRoles(e,t)}async pinParticipant(e,t,n=null){this._checkAdminRole(),await this._signaling.pinParticipant(e,t,n),this._conversation?.pinnedParticipantIdByRoom.set(n,t?null:e)}async updateMediaModifiers(e){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,await this._signaling.updateMediaModifiers(e))}async enableVideoSuspend(e){this._signaling.ready&&this._conversation&&this._transport?.getTopology()===J.SERVER&&await this._signaling.enableVideoSuspend(e)}async enableVideoSuspendSuggest(e){this._signaling.ready&&this._conversation&&this._transport?.getTopology()===J.SERVER&&await this._signaling.enableVideoSuspendSuggest(e)}async changeOptions(e){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),await this._signaling.changeOptions(e);let t=Xa(this._conversation.options,e);this._onOptionsChanged(t)}}async getWaitingHall(e,t,n){if(!this._signaling)return Promise.reject();let r=null;if(e&&(r=so(e),r)){let e=this._api.getDecorativeIdByInitialId(r.id);r.id=e??r.id}let i=await this._signaling.getWaitingHall(r,t,n);if(i.error)return Promise.reject(i.message);let a=i.participants||[],{externalIds:o}=this._resolveWaitingHallExternalIds(a,`getWaitingHall`),s=null;return a.length&&i.hasMore&&(s=oo(a[a.length-1].id)),{participants:o,pageMarker:s,totalCount:i.totalCount||0}}_resolveWaitingHallExternalIds(e,t){let n=[],r=[],i=[];return e.length&&e.forEach(e=>{if(e.externalId){let t=Z.fromSignaling(e.externalId);n.push(e.id.addedTs),r.push(t),this._api.cacheExternalId(e.id.id,t)}else{let t=this._getExternalIdByParticipantId(e.id.id);t?(r.push(t),n.push(e.id.addedTs)):i.push(e.id.id)}}),this._reportMissingExternalIds(i,t),{externalIds:r,timestamps:n}}async getAudienceModeHands(){if(!this._signaling.ready)throw Error(`Signaling is not ready`);let e=await this._signaling.getHandQueue();if(e.error)return Promise.reject(e.message);let t=e.participants||[],{externalIds:n,timestamps:r}=this._resolveWaitingHallExternalIds(t,`getAudienceModeHands`);return{timestamps:r,participants:n,totalCount:e.totalCount||0}}async promoteParticipant(e,t){if(this._signaling&&this._conversation)try{if(!j.includesOneOf(this._conversation.options,[Ja.WAITING_HALL,Ja.AUDIENCE_MODE]))throw Error(`Unable to promote a participant in the conversation with current options`);if(this._checkAdminRole(),!e&&t)throw Error(`participantId is required`);await this._signaling.promoteParticipant(e,t)}catch(t){throw this._debug.warn(`Failed to promote participant ${e}. ${t}`),t}}async requestPromotion(e=!1){this._signaling.ready&&await this._signaling.requestPromotion(e)}async acceptPromotion(e=!1){this._signaling.ready&&await this._signaling.acceptPromotion(e)}async chatMessage(e,t=null){this._signaling.ready&&await this._signaling.chatMessage(e,t)}async chatHistory(e){if(this._signaling.ready){let t=await this._signaling.chatHistory(e);for(let e=t.messages.length-1;e>=0;e--){let n=t.messages[e];this._onChatMessage(n)}}}async customData(e,t=null){this._signaling.ready&&await this._signaling.customData(e,t)}async createJoinLink(){if(this._conversation){let e=(await this._api.createJoinLink(this._conversation.id)).join_link;if(e)return this._conversation.joinLink=e,e}return Promise.reject()}async removeJoinLink(){if(this._conversation&&(await this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()}async addMovie({movieId:e,gain:t,metadata:n,lang:r}){let i={movieId:e,lang:r};(t||t===0)&&(i.gain=t),n&&(i.metadata=n);let a=await this._signaling.addMovie(i);if(a.error)throw Error(a.error);return{movieId:a.movieId,streamType:a.streamType}}async updateMovie(e){let t=await this._signaling.updateMovie(e);if(t.error)throw Error(t.error)}async removeMovie(e){let t={movieId:e},n=await this._signaling.removeMovie(t);if(n.error)throw Error(n.error)}async startUrlSharing(e){let t=await this._signaling.startUrlSharing(e);if(t.error)throw Error(t.error)}async stopUrlSharing(){let e=await this._signaling.stopUrlSharing();if(e.error)throw Error(e.error)}async updateRooms(e,t){let n=await this._signaling.updateRooms(e,t);if(n.error)throw Error(n.error)}async activateRooms(e,t){let n=await this._signaling.activateRooms(e,t);if(n.error)throw Error(n.error)}async switchRoom(e,t){let n=await this._signaling.switchRoom(e,t);if(n.error)throw Error(n.error)}async removeRooms(e){let t=await this._signaling.removeRooms(e);if(t.error)throw Error(t.error)}async startStream(e=!1,t=null,n=null,r=`DIRECT_LINK`,i=null,a=null){let o={movieId:n,name:t,privacy:r,groupId:i,roomId:a,streamMovie:!e},s=await this._signaling.startStream(o);if(s.error)return Promise.reject(Error(s.message))}async stopStream(e=null,t){let n=await this._signaling.stopStream({roomId:e,...t&&{remove:t}});if(n.error)return Promise.reject(Error(n.message))}async publishStream(e=null){if((await this._signaling.publishStream({roomId:e})).error)return Promise.reject()}async getStreamInfo(){let e=await this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}}async setLocalResolution({video:e,effect:t}){if(e.width<M.videoMinWidth||e.height<M.videoMinHeight)throw Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(t){if(t.width<M.videoMinWidth||t.height<M.videoMinHeight)throw Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");M.videoEffectMaxHeight=t.height,M.videoEffectMaxWidth=t.width}M.videoMaxWidth=e.width,M.videoMaxHeight=e.height,this._debug.debug(`Set local video resolution:`,`video ${e.width}x${e.height}`+(t?`, effect ${t.width}x${t.height}`:``)),this._mediaSource&&(await this._mediaSource.setResolution({video:e,effect:t}),this._transport&&await this._transport.onCameraResolutionChanged())}async videoEffect(e){return this._mediaSource?.videoEffect(e)}async audioEffect(e,t){return this._mediaSource?.audioEffect(e?{effects:e,isPreset:t}:null)}_convertExternalIdsToServerExternalIds(e){return e.map(e=>({id:e.id,type:M.externalUserType}))}async getParticipants(e){let t=this._convertExternalIdsToServerExternalIds(e.externalIds),n=await this._signaling.getParticipants(t);if(n.error)throw Error(n.error);let r=n.participants,i=this._transport?.getState();return j.mapSharedParticipants(r.map(e=>{let t=j.composeId(e);return this._createParticipant({id:t,externalId:Z.fromSignalingParticipant(e,!0,!0),mediaSettings:E(e.mediaSettings),participantState:j.mapParticipantState(e),state:e.state,roles:e.roles||[],connectionStatus:this._buildConnectionStatus(t,e.sessionState,i,e.onHold),isOnHold:!!e.onHold,muteStates:e.muteStates||{},unmuteOptions:e.unmuteOptions||[],observedIds:e.observedIds||[],markers:this._denormalizeMarkers(t,e.markers)},j.composeDecorativeId(e))}))}async getParticipantListChunk(e){this._debug.log(`Request participant list chunk`,e);let t=await this._signaling.getParticipantListChunk(e);if(t.error)throw Error(t.error);let n=this._createParticipantListChunk(t.chunk),r=this._participants,i=n.participants.filter(e=>!r[j.composeId(e)]);await this._registerParticipants(i);let a=this._transport?.getState();return n.participants.forEach(e=>{let t=j.composeId(e),n=r[t];this._updateParticipantExternalId(n,e),this._setSessionState(n,this._remoteParticipantSessionState(t,e.sessionState)),n.isOnHold||this._setTransportStatus(n,io.fromTransportState(a)??N.WAITING),n.movieShareInfos=e.movieShareInfos,Object.assign(n.mediaSettings,E(e.mediaSettings)),Object.assign(n.muteStates,e.muteStates),n.unmuteOptions=e.unmuteOptions??n.unmuteOptions,this._openTransport([n],!0)}),this._participantListChunkToExternalChunk(n)}async _getInitialParticiapntListChunk(){let e=M.participantListChunkInitIndex,t=M.participantListChunkInitCount,n=await this._signaling.getParticipantListChunk({listType:`GRID`,fromIdx:e,count:t});return this._debug.debug(`Get initial participant list chunk`,n.chunk),n.chunk}_onLocalMediaStreamChanged(e){if(!this._conversation||!this._mediaSource)return;let t=this._mediaSource.mediaSettings;this._debug.debug(`Local media stream changed`,t),e.kind===k.audio&&this._mediaSource&&(this._audioFix=new yo(this._mediaSource,this._debug,this._stats.logger)),L.onLocalStreamUpdate(t,e.kind,this.id),!this._conversation?.waitingHall&&!this._conversation?.observer&&!this._isAudienceModeListener()&&this._changeMediaSettings(t)}_onScreenSharingStatus(e){let t=this.mediaSettings;this._debug.log(`Screen sharing changed`,e.track,t);let n=e.track?new MediaStream([e.track]):null;L.onScreenStream(n,t,this.id)}_changeRemoteMediaSettings(e,t){this._debug.debug(`Remote media settings changed [${e}]`,t);let n=this._conversation?.externalId;if(this._isMe(e)&&n){L.onLocalMediaSettings(n,t,this.id);return}let r=this._getParticipant(e);if(!r){this._warnParticipantNotInConversation(e);return}r.mediaSettings=t,[`ACTIVE`,`HELD`].includes(this._state)&&(r.externalId?L.onRemoteMediaSettings(r.externalId,t,r.markers,this.id):this._reportMissingExternalIds([e],`REMOTE_MEDIA_SETTINGS`)),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t)}_extractLocalParticipantFromConnection(e){let t=this._api.getUserId();return(e.conversation.participants||[]).find(n=>n.id===t||j.comparePeerId(n.peerId,e.peerId))}_changeLocalParticipantState(e){this._debug.debug(`Local participant state force changed by admin`,e),[`ACTIVE`,`HELD`].includes(this._state)&&L.onLocalParticipantState(e,!1,this.id)}async _changeRemoteParticipantState(e,t){this._debug.debug(`Remote participant state changed [${e}]`,t);let n=this._getParticipant(e);if(!n){this._warnParticipantNotInConversation(e);return}n.participantState=t||{},[`ACTIVE`,`HELD`].includes(this._state)&&(n.externalId?L.onRemoteParticipantState(n.externalId,n.participantState,n.markers,this.id):this._reportMissingExternalIds([e],`REMOTE_PARTICIPANT_STATE`))}_changeMultipleParticipantState(e,t){this._debug.debug(`Multiple participants state changed`,e);let n=[],r,i=this._participants;e.forEach((e,t)=>{if(this._isMe(t))r=e;else{let r=i[t];if(!r){this._warnParticipantNotInConversation(t);return}r.participantState=e,n.push({externalId:r.externalId,participantState:{...e},markers:r.markers})}}),[`ACTIVE`,`HELD`].includes(this._state)&&(r&&L.onLocalParticipantState(r,!0,this.id),n.length&&L.onRemoteParticipantsState(n,t,this.id))}_invokeRolesChangedCallbackIfNeeded(e){this._state===`ACTIVE`&&e.roles&&e.roles.length&&(this._debug.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),L.onRolesChanged(e.externalId,e.roles,!0,this.id))}_onSignalingNotification(e){switch(e.notification){case K.ACCEPTED_CALL:return this._onAcceptedCall(e);case K.HUNGUP:return this._onHungup(e);case K.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case K.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case K.CLOSED_CONVERSATION:return this._onClosedConversation(e);case K.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case K.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case K.SESSION_STATE:return this._onSessionState(e);case K.PARTICIPANTS_STATE_CHANGED:return this._onParticipantsStateChanged(e);case K.RATE_CALL_DATA:return this._onNeedRate();case K.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case K.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case K.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case K.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case K.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case K.REGISTERED_PEER:return this._onPeerRegistered(e);case K.SWITCH_MICRO:return this._onMicSwitched(e);case K.CHAT_MESSAGE:return this._onChatMessage(e);case K.CUSTOM_DATA:return this._onCustomData(e);case K.RECORD_STARTED:return this._onRecordInfo(e.recordInfo,e.roomId);case K.RECORD_STOPPED:return this._onStopRecordInfo(e,e.roomId);case K.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case K.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case K.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin,e.markers,e.roomId);case K.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case K.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e);case K.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case K.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants,e.addedParticipantIds,e.removedParticipantIds);case K.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e);case K.FEEDBACK:return this._onFeedback(e);case K.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e);case K.MOVIE_SHARE_STARTED:return this._onSharedMovieInfoStarted(e);case K.MOVIE_SHARE_STOPPED:return this._onSharedMovieInfoStopped(e);case K.URL_SHARING_INFO_UPDATED:return this._onUrlSharingInfoUpdated(e);case K.ROOMS_UPDATED:return this._onRoomsUpdated(e);case K.ROOM_UPDATED:return this._onRoomUpdated(e);case K.ROOM_PARTICIPANTS_UPDATED:return this._onRoomParticipantsUpdated(e);case K.FEATURES_PER_ROLE_CHANGED:return this._onFeaturesPerRoleChanged(e);case K.PARTICIPANT_ANIMOJI_CHANGED:return this._onParticipantAnimojiChanged(e);case K.ASR_STARTED:return this._onAsrStart(e);case K.ASR_STOPPED:return this._onAsrStop(e);case K.PROMOTION_APPROVED:return this._onPromotionApproved(e);case K.DECORATIVE_PARTICIPANT_ID_CHANGED:return this._onDecorativeParticipantIdChanged(e);case K.VIDEO_SUSPEND_SUGGEST:return this._onVideoSuspendSuggest(e);case K.HOLD:return this._onParticipantHold(e);case K.TOPOLOGY_CHANGED:return this._onSignalingTopologyChanged(e)}}_onSignalingTopologyChanged(e){this._conversation&&e.topology!==this._conversation.topology&&(this._debug.log(`Signaling topology changed while transport is down: ${this._conversation.topology} -> ${e.topology}`),this._conversation.topology=e.topology)}_onPromotionApproved(e){let t=this._getExternalIdByParticipantId(e.adminId);if(!t){this._warnParticipantNotInConversation(e.adminId);return}L.onPromotionApproved(t,this.id)}async _onSignalingReconnect(e){if(!this._conversation)return;e.conversationParams?.serverTime&&(this._serverTimeOffset=e.conversationParams.serverTime-Date.now()),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(),this._changeFeaturesPerRole()),this._processPinnedParticipants(e),e.conversation.state;let t=null;if(e.conversation.participants){let n=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let e=j.composeId(n),i=n.roles||[];if(this._isMe(e)){no(this._conversation.roles,i)||this._onRolesChanged(e,i),t=()=>{this._registerParticipantLocalMuteState({muteStates:po(n),unmuteOptions:n.unmuteOptions})};continue}r.push(e);let a=this._getParticipant(e);if(!a)await this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{this._updateParticipantSessionState(a,e,n.sessionState);let t=E(n.mediaSettings);Kt(t,a.mediaSettings)||this._changeRemoteMediaSettings(e,t);let r=j.mapParticipantState(n),o=a.participantState;j.isEqualParticipantState(r,o)||await this._changeRemoteParticipantState(e,r),no(i,a.roles)||this._onRolesChanged(a.id,i),!!n.onHold!=!!a.isOnHold&&(a.isOnHold=!!n.onHold,this._setParticipantsStatus([a],n.onHold?N.ONHOLD:N.CONNECTED))}}let i=this._participants;for(let e of n)r.indexOf(e)<0&&i[e]&&this._removeParticipant(i[e],D.HUNGUP)}let n=[...e.participants?.participants??[],...e.rooms?.rooms.flatMap(e=>e.participants?.participants??[])??[]];await this._reconcileParticipantSessionStates(n);let r=e.rooms?.roomId??null;if(!this._conversation){this._debug.warn(`Conversation is empty, but should be filled`);return}this._conversation.roomId===r?this._processMuteStates(e,!0):await this._onRoomSwitched(r),t?.(),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options)}_onSignalingFailed(e){this._debug.error(`Signaling failed`,e),this._close(e)}async _onAcceptedCall(e){let t=j.composeMessageId(e),n=j.getPeerIdString(e.peerId);if(this._debug.debug(`Participant accepted call [${t}]`),this._statFirstMediaReceived.markAcceptedCall(this._transport?.getTopology()),this._conversation&&this._isMe(t)){if(this._conversation.concurrent)return;this._close(new O(D.MISSED),{errorText:`Call accepted on other device`});return}this._conversation?.direction===Wa.OUTGOING&&!this._conversation.concurrent&&this._stats.lifecycle.markOutgoingAccepted();let r=this._getParticipant(t);if(!r){let n=this._api.getDecorativeIdByInitialId(t);r=this._registerParticipantInCache(this._createParticipant({id:t,externalId:e.externalId?Z.fromSignaling(e.externalId,e.deviceIdx):void 0,mediaSettings:E(e.mediaSettings)},n))}else if(e.externalId){let t=Z.fromSignaling(e.externalId,e.deviceIdx);r.externalId=t,this._api.cacheExternalId(r.id,t)}r.state=X.ACCEPTED,r.mediaSettings=E(e.mediaSettings),this._logWithMediaSettings(C.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Wa.OUTGOING&&(this._state===`IDLE`||this._state===`PROCESSING`)&&(this._state=`ACTIVE`,this._changeFeatureSet()),this._state===`ACTIVE`&&this._transport&&this._transport.open([r.id],n),this._changeRemoteMediaSettings(t,r.mediaSettings),await this._changeRemoteParticipantState(t);let i=Object.keys(r.muteStates);if(i.length&&this._onMuteParticipant({muteStates:r.muteStates,mediaOptions:i,stateUpdated:!0,participantId:t}),[`ACTIVE`,`HELD`].includes(this._state)){if(!r.externalId){this._reportMissingExternalIds([t],`ACCEPTED_CALL`);return}L.onAcceptedCall(r.externalId,wa.parseCapabilities(e.capabilities),this.id)}}async _onHungup(e){this._debug.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=j.composeMessageId(e);if(this._conversation&&this._isMe(t)){let t={remote:!0,callError:e.callError,message:void 0};e.reason===D.OBSOLETE_CLIENT&&e.errorCode&&(t.message=e.errorCode),this._close(new O(e.reason,t));return}this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers);let n=this._getParticipant(t);if(!n){this._warnParticipantNotInConversation(t);return}if(this._closeParticipantTransport(t),n.state=e.reason===D.REJECTED?X.REJECTED:X.HUNGUP,this._state!==`CLOSE`){let t=e.reason===D.OBSOLETE_CLIENT?D.OBSOLETE_CLIENT:D.HUNGUP;this._removeParticipant(n,t)}}_onSessionState(e){if(!M.enableSessionStateUpdates)return;let t=j.composeMessageId(e);if(this._isMe(t))return;this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers);let n=this._getParticipant(t);if(!n){this._warnParticipantNotInConversation(t);return}if(e.connected){let e=io.fromTransportState(this._transport?.getState());e&&this._setTransportStatus(n,e)}this._setSessionState(n,{connected:e.connected})}async _reconcileParticipantSessionStates(e){if(!M.enableSessionStateUpdates||!e.length)return;let t=this._participants;for(let n of e){let e=j.composeId(n),r=t[e];r&&!this._isMe(e)&&(this._updateParticipantExternalId(r,n),this._updateParticipantSessionState(r,e,n.sessionState))}}_updateParticipantExternalId(e,t){let n=Z.fromSignalingParticipant(t)??Z.fromSignalingParticipant(t,!1);n&&(e.externalId=n,this._api.cacheExternalId(e.id,n))}_updateParticipantSessionState(e,t,n){return this._setSessionState(e,this._remoteParticipantSessionState(t,n))}_emitParticipantEffectiveStatusIfSessionOverridesTransport(e){e.connectionStatus.sessionState?.connected!==!1||e.connectionStatus.lastEffective===e.connectionStatus.transport||L.onRemoteStatus([e.externalId],e.connectionStatus.lastEffective,null,this.id)}async _onAddedParticipant(e){this._debug.debug(`Participant added [${e.participantId}]`);let t=j.composeMessageId(e),n=this._getParticipant(t);n&&this._updateParticipantExternalId(n,e.participant);let r=!n;if(n&&n.state!==X.HUNGUP&&n.state!==X.REJECTED){this._debug.debug(`Participant [${t}] is already in conversation and is active`);return}if(!n){let{participant:r}=e,i=j.composeDecorativeId(r);this._registerParticipant({id:t,externalId:Z.fromSignalingParticipant(r,!0,!0),mediaSettings:E(r.mediaSettings),state:r.state,participantState:j.mapParticipantState(r),roles:r.roles||[],connectionStatus:this._buildConnectionStatus(t,r.sessionState,this._transport?.getState(),r.onHold),isOnHold:!!r.onHold,muteStates:r.muteStates||{},unmuteOptions:r.unmuteOptions||[],observedIds:r.observedIds||[]},i),n=this._getParticipant(t)}n.state=X.CALLED,n.mediaSettings=E(e.participant?.mediaSettings),n.participantState=j.mapParticipantState(e.participant),n.roles=e.participant?.roles||[],this._updateParticipantSessionState(n,t,e.participant.sessionState),this._setParticipantsStatus([n],N.WAITING),r&&this._emitParticipantEffectiveStatusIfSessionOverridesTransport(n),this._state!==`IDLE`&&this._transport&&this._allocateParticipantTransport(n.id,!0),L.onParticipantAdded(n.externalId,n.markers,this.id),this._changeRemoteMediaSettings(t,n.mediaSettings),await this._changeRemoteParticipantState(t,n.participantState),this._invokeRolesChangedCallbackIfNeeded(n)}async _onJoinedParticipant(e){this._debug.debug(`Participant joined [${e.participantId}]`),this._statFirstMediaReceived.markOnJoin(this._transport?.getTopology());let t=j.composeMessageId(e),n=this._getParticipant(t);n&&this._updateParticipantExternalId(n,e.participant);let r=!n;if(n&&n.state===X.ACCEPTED){this._debug.warn(`Participant [${t}] is already in conversation and is active`);return}if(!n){let{participant:r}=e,i=j.composeDecorativeId(r);this._registerParticipant({id:t,externalId:Z.fromSignalingParticipant(r,!0,!0),mediaSettings:E(r.mediaSettings),state:r.state,participantState:j.mapParticipantState(r),roles:r.roles||[],muteStates:r.muteStates||{},movieShareInfos:r.movieShareInfos,unmuteOptions:r.unmuteOptions||[],observedIds:r.observedIds||[],connectionStatus:this._buildConnectionStatus(t,r.sessionState,this._transport?.getState(),r.onHold),markers:this._denormalizeMarkers(t,r.markers),isOnHold:!!r.onHold},i),n=this._getParticipant(t)}this._conversation&&this._conversation.direction===Wa.OUTGOING&&(this._state===`IDLE`||this._state===`PROCESSING`)&&(this._state=`ACTIVE`,this._changeFeatureSet()),n.state=X.ACCEPTED,n.mediaSettings=E(e.mediaSettings),n.participantState=j.mapParticipantState(e.participant),n.roles=e.participant.roles||[],this._updateParticipantSessionState(n,t,e.participant.sessionState),e.participant.onHold?(n.isOnHold=!0,this._setParticipantsStatus([n],N.ONHOLD)):this._transport?.isAllocated(n.id)?this._setParticipantsStatus([n],N.CONNECTED):this._setParticipantsStatus([n],N.WAITING),r&&this._emitParticipantEffectiveStatusIfSessionOverridesTransport(n),this._state!==`IDLE`&&this._transport&&(this._transport.isAllocated(n.id)||this._allocateParticipantTransport(n.id,!0),this._transport.open([n.id],null,!!this._conversation?.observer)),L.onParticipantJoined(n.externalId,n.markers,this.id),this._changeRemoteMediaSettings(t,n.mediaSettings),await this._changeRemoteParticipantState(t,n.participantState),this._invokeRolesChangedCallbackIfNeeded(n);let i=Object.keys(n.muteStates);i.length&&this._onMuteParticipant({muteStates:n.muteStates,mediaOptions:i,stateUpdated:!0,participantId:t}),this._processSharedMovieInfos(n.movieShareInfos)}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new O(e.reason,{remote:!0,callError:e.callError}))}_onMediaSettingsChanged(e){let t=j.composeMessageId(e);this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,E(e.mediaSettings))}async _onParticipantStateChanged(e){let t=j.composeMessageId(e),n=j.mapParticipantState(e);this._isMe(t)?this._changeLocalParticipantState(n):(this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),await this._changeRemoteParticipantState(t,n))}_onParticipantsStateChanged(e){let{participants:t,roomId:n}=e;t.map(({id:e,markers:t})=>this._registerParticipantAndSetMarkersIfChunkEnabled(e,t));let r=new Map,i=t.map(({id:e,participantState:t})=>[e,this._getExternalIdByParticipantId(e)?j.mapParticipantState({participantState:t}):void 0]);try{i.forEach(([e,t])=>{t&&r.set(e,t)}),this._changeMultipleParticipantState(r,n)}catch(e){this._debug.warn(`_onParticipantsStateChanged: Failed to get external ids. ${e}`)}}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),L.onMultipartyChatCreated(this._conversation))}async _onForceMediaSettingsChange(e){if(!this._mediaSource||this._state===`HELD`)return;let t=this._mediaSource.mediaSettings,n=E(e.mediaSettings);t.isAudioEnabled!==n.isAudioEnabled&&await this._mediaSource.toggleAudio(n.isAudioEnabled),t.isVideoEnabled!==n.isVideoEnabled&&await this._mediaSource.toggleVideo(n.isVideoEnabled),t.isScreenSharingEnabled!==n.isScreenSharingEnabled&&await this._mediaSource.toggleScreenCapturing({captureScreen:n.isScreenSharingEnabled,fastScreenSharing:n.isFastScreenSharingEnabled,captureAudio:n.isAudioSharingEnabled})}_onSettingsUpdate(e){this._debug.debug(`Got settings update notification`,e);let t={camera:e.camera,screenSharing:e.screenSharing,fastScreenSharing:e.fastScreenSharing};this._serverSettings=Ar(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){this._debug.debug(`Got video quality update notification`,e);let t={maxBitrateK:Math.round(e.quality.maxBitrate/1024),maxDimension:e.quality.maxDimension},n;n=e.mediaType&&e.mediaType===V.SCREEN?{camera:null,screenSharing:null,fastScreenSharing:Object.assign({},this._serverSettings.fastScreenSharing,t)}:{camera:Object.assign({},this._serverSettings.camera,t),screenSharing:null,fastScreenSharing:null},this._serverSettings=Ar(this._serverSettings,n),this._transport&&this._transport.updateSettings(this._serverSettings)}async _onPeerRegistered(e){this._registeredPeerReceived=!0,this._clearCalleeUnavailableWatchdog();let t=j.composeMessageId(e),n=this._getParticipant(t);n&&(n.clientType=e.clientType,n.platform=e.platform,L.onPeerRegistered(this.id,[n.externalId]))}async _onMicSwitched(e){L.onDeviceSwitched(S.AUDIO,!e.mute,this.id),await this.toggleLocalAudio(!e.mute)}_onChatMessage(e){let t=j.composeMessageId(e),n=this._getExternalIdByParticipantId(t);if(!n){this._warnParticipantNotInConversation(t);return}L.onChatMessage(e.message,n,e.direct,this.id)}_onCustomData(e){if(Object.hasOwn(e.data,`sdk`))return;let t=j.composeMessageId(e),n=this._getExternalIdByParticipantId(t);if(!n){this._warnParticipantNotInConversation(t);return}L.onCustomData(e.data,n,e.direct,this.id)}_onRecordInfo(e,t=null){if(!this._conversation||!e)return;let n=this._conversation.recordsInfoByRoom.get(t);if(n?.recordMovieId!==e?.recordMovieId||n?.recordStartTime!==e?.recordStartTime){this._conversation.recordsInfoByRoom.set(t,e);let n=this._getExternalIdByParticipantId(e.initiator);n?L.onRecordStarted(n,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId,t,this.id):this._warnParticipantNotInConversation(e.initiator)}}_onStopRecordInfo({participant:e,recordMovieId:t},n=null){if(!this._conversation)return;let r=this._conversation.recordsInfoByRoom.get(n);if(!(!r||r.recordMovieId!==t))if(this._conversation.recordsInfoByRoom.set(n,null),e){let t=this._getExternalIdByParticipantId(e);L.onRecordStopped(n,t??null,this.id)}else L.onRecordStopped(n,null,this.id)}_changePinnedParticipantForRoom(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.pinnedParticipantIdByRoom.get(e);if(t&&!this._isMe(t)){let n=this._getExternalIdByParticipantId(t);n&&L.onPinnedParticipant(n,!1,null,e,this.id)}}_changeRecordInfoForRoom(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.recordsInfoByRoom.get(e);if(t){let n=this._getExternalIdByParticipantId(t.initiator);n?L.onRecordStarted(n,t.recordMovieId,t.recordStartTime,t.recordType,t.recordExternalMovieId,t.recordExternalOwnerId,e,this.id):this._warnParticipantNotInConversation(t.initiator)}else L.onRecordStopped(e,null,this.id)}_changeAsrInfoForRoom(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.asrInfoByRoom.get(e);if(t){let n=this._getExternalIdByParticipantId(t.initiatorId);n&&L.onAsrSet({externalId:n,movieId:t.movieId},e,this.id)}else L.onAsrSet(null,e,this.id)}_changeUrlSharingInfoForRoom(){if(!this._conversation)return;let{roomId:e}=this._conversation,{urlSharingInfoByRoom:t}=this._conversation,n=t.get(e);if(n){let t=this._getExternalIdByParticipantId(n.initiatorId);t&&L.onRemoteSharedUrl(t,n.sharedUrl,e,this.id)}}_onParticipantAnimojiChanged(e){if(this._conversation){let t=this._getExternalIdByParticipantId(e.participantId);if(!t){this._warnParticipantNotInConversation(e.participantId);return}L.onParticipantVmojiUpdate(t,this.id)}}_onAsrStart(e){if(!this._conversation)return;let t=e.asrInfo,n=e.roomId||null;this._conversation.asrInfoByRoom.set(n,t);let r=this._getExternalIdByParticipantId(t.initiatorId);if(!r){this._warnParticipantNotInConversation(t.initiatorId);return}L.onAsrStarted(r,t.movieId,n,this.id)}_onAsrStop(e){if(!this._conversation)return;let t=e.roomId||null;t===null&&(this._conversation.asrInfo=null),this._conversation.asrInfoByRoom.delete(t),L.onAsrStopped(t,this.id)}_onAsrTranscription(e){if(!this._conversation)return;let t=this._getExternalIdByParticipantId(e.participantId);if(!t){this._warnParticipantNotInConversation(e.participantId);return}L.onAsrTranscription(t,e.text,e.timestamp,e.duration,this.id)}async _onRolesChanged(e,t){if(this._conversation&&this._isMe(e)&&!no(this._conversation.roles,t)){this._debug.debug(`Local roles changed: ${t}`),this._conversation.roles=t,L.onLocalRolesChanged(t,!1,this.id),this._processMuteState({mediaOptions:co(this._getMuteStatesForCurrentRoom(),Za.MUTE_PERMANENT),stateUpdated:!0}),j.includesOneOf(t,[to.ADMIN,to.CREATOR])?this._refreshRooms(!0):t.length||this._onRoomSwitched(null);return}let n=this._getParticipant(e);n&&!no(n.roles,t)&&(this._debug.debug(`Roles for participant [${e}] changed: ${t}`),n.roles=t,L.onRolesChanged(n.externalId,t,!1,this.id))}async _onMuteParticipant(e,t=!1){if(!this._conversation)return;let{muteAll:n,muteStates:r={},unmuteOptions:i=[],mediaOptions:a=[],roomId:o=null}=e;if(e.participantId&&!this._isMe(e.participantId)){if(!this._isCallAdmin()){this._debug.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let t=this._getParticipant(e.participantId);if(t){this._debug.debug(`Mute states for participant [${e.participantId}] changed`,r);let o=e.adminId?this._getExternalIdByParticipantId(e.adminId):null;L.onMuteStates(r,i,a,n,e.unmute,t.externalId,o,e.stateUpdated,e.requestedMedia,e.roomId,this.id)}return}if(e.requestedMedia?.length||(n&&!t?this._setMuteStatesForRoomId(r,o):n||(this._conversation.muteStatesPersonal=r)),e.adminId&&this._isMe(e.adminId)){n&&L.onMuteStates(r,i,a,n,e.unmute,null,this._conversation.externalId,e.stateUpdated,e.requestedMedia,e.roomId,this.id);return}await this._processMuteState({mediaOptions:a,muteAll:n,unmute:e.unmute,adminId:e.adminId,stateUpdated:e.stateUpdated,requestedMedia:e.requestedMedia,roomId:e.roomId,unmuteOptions:i,muteStates:r})}_changeMuteStatesForRoom(e,t){if(!this._conversation)return;let n=this._getMuteStatesForRoomId(t),r=this._getMuteStatesForRoomId(e),i=Object.keys(n),a=Object.keys(r);this._processMuteState({mediaOptions:Array.from(new Set([...i,...a])),roomId:e,muteAll:!0,stateUpdated:!0})}async _processMuteState(e){if(!this._conversation||!this._mediaSource||this._participantState!==X.ACCEPTED)return;let{mediaOptions:t=[],muteAll:n,unmute:r,stateUpdated:i,requestedMedia:a,roomId:o=null,unmuteOptions:s=[]}=e,c=e.adminId?this._getExternalIdByParticipantId(e.adminId):null,l=Object.assign({},e.muteStates??this._getMuteStatesForRoomId(o)),u=this._mediaSource.mediaSettings,d=Object.entries(l);for(let[e,i]of d){let a=this._isCallAdmin()&&n;if(!(i!==Za.MUTE&&i!==Za.MUTE_PERMANENT||a)&&(this._isCallAdmin()&&i===Za.MUTE_PERMANENT&&!n&&(l[e]=Za.MUTE),!(!t.includes(e)||r)))switch(e){case S.VIDEO:u.isVideoEnabled&&(L.onDeviceSwitched(S.VIDEO,!1,this.id),await this.toggleLocalVideo(!1));break;case S.AUDIO:u.isAudioEnabled&&(L.onDeviceSwitched(S.AUDIO,!1,this.id),await this.toggleLocalAudio(!1));break;case S.SCREEN_SHARING:u.isScreenSharingEnabled&&(L.onDeviceSwitched(S.SCREEN_SHARING,!1,this.id),await this.disableScreenCapturing());break;case S.AUDIO_SHARING:u.isAudioSharingEnabled&&(L.onDeviceSwitched(S.AUDIO_SHARING,!1,this.id),await this.toggleScreenCapturing({captureScreen:u.isScreenSharingEnabled,fastScreenSharing:u.isFastScreenSharingEnabled,captureAudio:!1}));break}}L.onMuteStates(l,s,t,n,r,null,c,i,a,o,this.id)}_onPinParticipant(e,t=!1,n,r=null){if(!this._conversation)return;let i=this._conversation.pinnedParticipantIdByRoom.get(r);if(i&&i!==e)if(this._isMe(i))L.onLocalPin(!0,r,this.id);else{let t=this._getExternalIdByParticipantId(i);t&&L.onPinnedParticipant(t,!0,this._denormalizeMarkers(e,n),r,this.id)}if(this._isMe(e))L.onLocalPin(t,r,this.id);else{let i=this._getExternalIdByParticipantId(e);i&&L.onPinnedParticipant(i,t,this._denormalizeMarkers(e,n),r,this.id)}this._conversation.pinnedParticipantIdByRoom.set(r,t?null:e)}_onOptionsChanged(e){this._conversation&&!Ya(this._conversation.options,e)&&(this._conversation.options=e,L.onOptionsChanged(e,this.id),e.includes(Ja.ADMIN_IS_HERE)?this._conversation.restricted&&this._conversation.waitingHall&&L.onLocalStatus(N.WAITING_HALL,this.id):e.includes(Ja.WAIT_FOR_ADMIN)&&this._conversation.restricted&&L.onLocalStatus(N.WAIT_FOR_ADMIN,this.id))}async _onNetworkStatus(e){if(this._conversation){let t=[],n=this._participants;for(let[r,i]of Object.entries(e)){let e;if(this._isMe(r)||r===``)e=this._conversation.networkRating;else if(n[r])e=n[r].networkRating;else continue;if(e!==i)if(this._isMe(r)||r===``)this._conversation.networkRating=i,$r.getInstance().value=i,L.onLocalNetworkStatusChanged(i,this.id);else{let e=n[r];e.networkRating=i,t.push({uid:e.externalId,rating:i})}}if(t.length===0)return;this._debug.log(`Received network status update: `,e),L.onNetworkStatusChanged(t,this.id)}}async _emitHeldParticipantsStatus(){let e=Object.values(this._participants).filter(e=>e.isOnHold).map(e=>e.externalId);e.length&&L.onRemoteStatus(e,N.ONHOLD,null,this.id)}async _onRemoteStreamSecond(e,t){let n=this._getParticipant(e);n&&L.onRemoteScreenStream(n.externalId,t,this.id)}async _onAnimojiStream(e,t){if(this._isMe(e)&&this._mediaSource){L.onVmojiStream(t,this._mediaSource.mediaSettings,this.id);return}let n=this._getParticipant(e);n&&L.onRemoteVmojiStream(n.externalId,t,this.id)}_onAnimojiError(e){try{let t=this._getExternalIdByParticipantId(e.participantId);t&&(delete e.participantId,L.onVmojiError({...e,externalId:t},this.id))}catch(e){this._debug.warn(`_onAnimojiError failed`,e)}}_onPeerConnectionClosed(e){this._state!==`HELD`&&(e===J.SERVER&&this._cleanupParticipantAgnosticStreams(),this._audioOutput.destroy())}_changeFeatureSet(){if(this._conversation){let e=this._state===`ACTIVE`,t=this._conversation.features.includes(qa.ADD_PARTICIPANT);L.onCallState(e,t,this._conversation,this.id)}}_changeFeaturesPerRole(){this._conversation&&L.onFeaturesPerRoleChanged(this._conversation.featuresPerRole??{},this.id)}_changeNeedRate(){this._conversation&&this._conversation.needRate&&L.onRateNeeded(this.id)}async _onVolumesDetected(e){let t=[];for(let[n,r]of Object.entries(e)){let e=this._getParticipant(n);e&&e.externalId&&t.push({uid:e.externalId,volume:r.real})}L.onVolumesDetected(t,this.id)}async _onSpeakerChanged(e){let t=this._activeSpeakerId;if(this._activeSpeakerId=e,t&&t!==e){let e=this._getParticipant(t);if(e?.connectionStatus.sessionStateConnectedBySpeaker){e.connectionStatus.sessionStateConnectedBySpeaker=!1;let t=this._setTransportStatus(e,e.connectionStatus.transport);this._emitParticipantTransition(e,t)}}let n=this._getParticipant(e);if(n){if(n.connectionStatus.sessionStateApplicable&&n.connectionStatus.sessionState?.connected===!1){let e=io.fromTransportState(this._transport?.getState());e&&this._setTransportStatus(n,e),n.connectionStatus.sessionStateConnectedBySpeaker=!0;let t=this._setTransportStatus(n,n.connectionStatus.transport);this._emitParticipantTransition(n,t)}this._lastSignalledActiveSpeakerId!==e&&(L.onSpeakerChanged(n.externalId,this.id),this._lastSignalledActiveSpeakerId=e)}}async _onTransportStateChanged(e,t){this._debug.debug(`Transport state has changed: ${t}`,e);let n=io.fromTransportState(t);if(!n)return;let r=this._participants,i=[],a=e.reduce((e,n)=>{if(n in r){let a=r[n];e.push(a),t===q.CONNECTED&&(a.remoteStream||(a.mediaSettings&&this._changeRemoteMediaSettings(n,a.mediaSettings),this._changeRemoteParticipantState(n,a.participantState)),i.push(...Object.values(a.lastRequestedLayouts)))}else this._warnParticipantNotInConversation(n);return e},[]);a.length&&(this._updateDisplayLayoutFromCache(i),this._setParticipantsStatus(a,n))}async _onTransportLocalStateChanged(e){if(this._debug.debug(`Local transport state has changed: ${e}`),e===q.CONNECTED&&(T.releaseFirefoxMicrophonePermissionWarmup(),L.onLocalStatus(N.CONNECTED,this.id),this._transport?.getTopology()===J.SERVER)){let e=Object.values(this._myLastRequestedLayouts);await this.updateDisplayLayout(e),this._displayLayoutRequester.resend()}this._state!==`HELD`&&((e===q.CONNECTING||e===q.RECONNECTING)&&this._areTransportParticipantsOnHold()||(e===q.CONNECTING&&L.onLocalStatus(N.CONNECTING,this.id),e===q.RECONNECTING&&L.onLocalStatus(N.RECONNECT,this.id),e===q.FAILED&&this._transport&&this._transport.allocated().length===0&&this._close(new O(D.FAILED,{callError:{scope:`network`,source:`rtc`,code:`connection-failed`,description:`transport-failed`}}),{errorText:`Transport failed`,signalingReason:D.FAILED})))}_areTransportParticipantsOnHold(){if(!M.hold||!this._transport)return!1;let e=this._transport.opened().length?this._transport.opened():this._transport.allocated();if(!e.length)return!1;let t=this._participants;return e.every(e=>t[e]?.isOnHold)}_onRemoteTrackAdded(e,t,n){if(e.endsWith(Yr.AUDIO_MIX))this._debug.debug(`Remote audio mix track added`),this._audioOutput.add(e,n),L.onRemoteMixedAudioStream(t,this.id);else if(e.startsWith(Yr.TRANSPARENT_AUDIO_TRACK_PREFIX))this._debug.debug(`Remote transparent audio track added: ${e}`),this._audioOutput.add(e,n);else if(e.startsWith(Yr.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))this._debug.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{this._debug.debug(`Remote track added on the participant [${e}]`,{kind:n.kind});let r=this._getParticipant(e);if(!r){let t=this._api.getDecorativeIdByInitialId(e);this._debug.warn(`Conversation: track added before participant [id: ${e}, decorativeId: ${t}]`),this._registerParticipant({id:e},t),r=this._getParticipant(e),this._setParticipantsStatus([r],N.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(L.onSpeakerChanged(r.externalId,this.id),this._lastSignalledActiveSpeakerId=e)}if(this._transport&&!this._transport.isAllocated(r.id)&&this._allocateParticipantTransport(r.id,!1),n.kind===k.audio&&(this._audioOutput.add(e,n),M.preserveAudioTracks||(r.remoteAudioTrack=n,t.removeTrack(n))),r.remoteStream!==t&&t.getTracks().length){if(r.remoteStream=t,r.secondStream)return;L.onRemoteStream(r.externalId,t,this.id)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings)}}_onRemoteTrackRemoved(e,t,n){switch(this._debug.debug(`[${e}] remote track (removed)`,{track:n}),n.kind){case k.audio:this._removeAudioTrack(e,t,n);break;case k.video:case k.screen:this._removeVideoTrack(e,t,n);break}}async _removeAudioTrack(e,t,n){if(e!==Yr.AUDIO_MIX){let n=this._getParticipant(e);if(!n||n.remoteStream&&n.remoteStream!==t)return}this._audioOutput.remove(e,n)}_removeVideoTrack(e,t,n){}_onTopologyChanged(e){if(this._state===`HELD`){this._conversation&&(this._conversation.topology=e);return}if(this._statFirstMediaReceived.markTopologyChanged(e),e===J.DIRECT&&(this._onRemoteSignalledStall([]),this._onAudioMixStall(!1)),this._conversation){this._conversation.topology=e;for(let e of Object.values(this._participants)){let t=io.setSessionStateApplicable(e.connectionStatus,this._isParticipantSessionStateApplicable(e.id));this._emitParticipantTransition(e,t)}this._changeFeatureSet(),this._forceOpenTransportForAloneInCall()}this._audioOutput.destroy()}_onAudioMixStall(e){this._audioMixStalled!==e&&!this.isCallHeld&&(this._audioMixStalled=e,this._debug.debug(`Audio mix stalled:`,e),L.onLocalStatus(e?N.RECONNECT:N.CONNECTED,this.id))}_onRemoteSignalledStall(e){let t={},n=[],r=[];this._debug.debug(`Participants stalled:`,e);let i=this._participants;for(let r of e){t[r]=!0;let e=i[r];e&&n.push(e),delete this._lastStalled[r]}for(let e of Object.keys(this._lastStalled)){let t=i[e];t&&r.push(t)}n.length&&this._setParticipantsStalled(n,!0),r.length&&this._setParticipantsStalled(r,!1),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps),this._fixVideoDevice(e.outbound.rtps)}_fixAudioDevice(e){!T.hasMicrophone()||!this._audioFix||!this.mediaSettings?.isAudioEnabled||this._audioFix.fix(e)}_fixVideoDevice(e){!T.hasCamera()||!this._audioFix||!this.mediaSettings?.isVideoEnabled||this._audioFix.fixVideo(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!==`CLOSE`||!1;e&&(this._debug.debug(`Toggle join availability`,{available:t,chatId:e}),L.onJoinStatus(t,e,this.id))}async _updateDisplayLayoutFromCache(e){if(this._transport?.getTopology()===J.SERVER&&e.length)try{await this.updateDisplayLayout(e)}catch(e){this._debug.warn(`_updateDisplayLayoutFromCache failed: ${e}`)}}_setParticipantsStatus(e,t,n=null){this._updateParticipantsStatus(e,e=>e.isOnHold&&![N.ONHOLD,N.HANGUP,N.ERROR].includes(t)?null:this._setTransportStatus(e,t),n)}_setParticipantsStalled(e,t){this._updateParticipantsStatus(e,e=>io.setStalled(e.connectionStatus,t))}_updateParticipantsStatus(e,t,n=null){let r=e.reduce((e,n)=>{let r=t(n);if(r?.shouldNotify){var i;(e[i=r.status]??(e[i]=[])).push(n.externalId)}return e},{});for(let[e,t]of Object.entries(r))L.onRemoteStatus(t,e,n,this.id)}_onJoinLinkChanged(e){this._conversation&&e.joinLink&&(this._conversation.joinLink=e.joinLink),L.onJoinLinkChanged(e.joinLink,this.id)}_onRoomsUpdated(e){if(this._isCalledState())return;let t={},n=[],r=[];for(let i of Object.keys(Qa)){let a=e.updates[i];a&&(a?.rooms?.forEach(e=>{let{room:t,missingParticipantIds:i}=this._convertRoomToExternal(e);t&&n.push(t),r.push(...i)}),t[i]={rooms:n,roomIds:a?.roomIds,deactivated:a?.deactivated})}this._reportMissingExternalIds(r,`ROOMS_UPDATED`),L.onRoomsUpdated(t,this.id)}_onRoomUpdated(e){let{room:t,missingParticipantIds:n}=this._convertRoomToExternal(e.room||null);e.events.some(e=>e===Qa.UPDATE)&&(e.muteStates!==void 0&&this._setMuteStatesForRoomId(e.muteStates,e.roomId),e.recordInfo!==void 0&&this._conversation?.recordsInfoByRoom.set(e.roomId,e.recordInfo),e.asrInfo!==void 0&&this._conversation?.asrInfoByRoom.set(e.roomId,e.asrInfo)),this._isCalledState()||(this._reportMissingExternalIds(n,`ROOM_UPDATED`),L.onRoomUpdated(e.events,e.roomId,t,e.deactivate||null,this.id))}_convertRoomToExternal(e){if(!e)return{room:null,missingParticipantIds:[]};let t=[],{externalIds:n,missingIds:r}=this._getExternalIdsByParticipantIds(e.participantIds??[]),{externalIds:i,missingIds:a}=this._getExternalIdsByParticipantIds(e.addParticipantIds??[]),{externalIds:o,missingIds:s}=this._getExternalIdsByParticipantIds(e.removeParticipantIds??[]);t.push(...r,...a,...s);let c;if(e.pinnedParticipantId){let n=this._getExternalIdByParticipantId(e.pinnedParticipantId);n?c=n:t.push(e.pinnedParticipantId)}return{room:{id:e.id,name:e.name,participantCount:e.participantCount,participantIds:n,addParticipantIds:i,removeParticipantIds:o,participants:e.participants?.participants?this._participantListChunkToExternalChunk(e.participants):void 0,active:e.active,muteStates:e.muteStates,pinnedParticipantId:c,countdownSec:e.countdownSec,timeoutMs:e.timeoutMs},missingParticipantIds:t}}async _onRoomParticipantsUpdated(e){let t=this._transport?.getState(),n=e.roomId??null,r=[],{externalIds:i,missingIds:a}=this._getExternalIdsByParticipantIds(e.addedParticipantIds??[]);r.push(...a);let o=e.addedParticipants;if(i.length&&o?.length!==i.length&&!this._isCalledState()){let e=this._convertExternalIdsToServerExternalIds(i);o=(await this._signaling.getParticipants(e)).participants}let s=o?.map(e=>{let r=j.composeId(e);return this._createParticipant({id:r,externalId:Z.fromSignalingParticipant(e,!0,!0),mediaSettings:E(e.mediaSettings),participantState:j.mapParticipantState(e),state:e.state,roles:e.roles||[],connectionStatus:this._buildConnectionStatus(r,e.sessionState,t,e.onHold),isOnHold:!!e.onHold,muteStates:e.muteStates||{},unmuteOptions:e.unmuteOptions||[],observedIds:e.observedIds||[],markers:this._denormalizeMarkers(r,e.markers),isInRoom:n!==null},j.composeDecorativeId(e))})||[],c=!1;for(let e of s)e.id===this._conversation?.compositeUserId&&(c=!0),this._registerParticipantInCache(e);this._transport?.getState()===q.IDLE&&!this._isCalledState()&&this._openTransport(s,!0);let l=[];if(e?.removedParticipantMarkers){for(let t of e.removedParticipantMarkers)if(t.GRID?.id){let e=this._getExternalIdByParticipantId(t.GRID.id);e?l.push(e):r.push(t.GRID.id)}}if(this._reportMissingExternalIds(r,`ROOM_PARTICIPANTS_UPDATED`),c&&await this._onRoomSwitched(n),l){let e=this._conversation?.pinnedParticipantIdByRoom.get(n);if(e){let t=this._getExternalIdByParticipantId(e);if(t){for(let e of l)if(Z.compare(t,e)){this._conversation?.pinnedParticipantIdByRoom.delete(n);break}}}}let u={roomId:n,participantCount:e.participantCount,addedParticipantIds:i,addedParticipants:j.mapSharedParticipants(s),removedParticipantMarkers:e?.removedParticipantMarkers,removedParticipantIds:l};this._isCalledState()||L.onRoomParticipantsUpdated(u,this.id)}async _onRoomSwitched(e,t=!1){if(!this._conversation||this._conversation.roomId===e)return;let n=this._conversation.roomId;if(this._conversation.roomId=e,t&&!this._isCalledState()){L.onRoomStart(e,this.id);return}this._isCalledState()||L.onRoomSwitched(e,this.id),e!==null&&!this._isCallAdmin()&&await this._refreshRooms(!1),this._changePinnedParticipantForRoom(),this._changeRecordInfoForRoom(),this._changeMuteStatesForRoom(e,n),this._changeAsrInfoForRoom(),this._changeUrlSharingInfoForRoom()}async _refreshRooms(e){let t;this._isCalledState()||(t=await this._signaling.getRooms(e));let n=t?.rooms?.rooms??[],r=[];for(let t of n){let n=t.id??null;if(this._setMuteStatesForRoomId(t.muteStates,n),this._conversation?.recordsInfoByRoom.set(n,t.recordInfo??null),this._conversation?.pinnedParticipantIdByRoom.set(n,t.pinnedParticipantId??null),t.asrInfo&&this._conversation?.asrInfoByRoom.set(n,t.asrInfo),t.urlSharingInfo?this._conversation?.urlSharingInfoByRoom.set(n,t.urlSharingInfo):this._conversation?.urlSharingInfoByRoom.delete(n),e){let e=this._participants;await this._registerParticipants(t?.participants?.participants?.filter(t=>!e[j.composeId(t)])||[],!0);let{room:n}=this._convertRoomToExternal(t);n&&r.push(n)}}r.length&&!this._isCalledState()&&L.onRoomsUpdated({[Qa.UPDATE]:{rooms:r}},this.id)}_onFeedback(e){let t=[];for(let n of e.feedback){let e={...n,items:[]};for(let t of n.items){let n=this._getExternalIdByParticipantId(t.participantId);n?e.items.push({...t,participantId:n}):this._warnParticipantNotInConversation(t.participantId)}t.push(e)}L.onFeedback(t,e.roomId,this.id)}_onDecorativeParticipantIdChanged(e){if(!this._conversation||!e.decorativeParticipantId||!e.decorativeExternalParticipantId)return;let{participantId:t,decorativeParticipantId:n,decorativeExternalParticipantId:r}=e,i=this._isMe(t);this._debug.debug(`Decorative participant id changed [${t}]`,e);let a=this._getExternalIdByParticipantId(t);if(!a){this._warnParticipantNotInConversation(t);return}let o=Z.fromSignaling(r,a.deviceIdx);L.onParticipantIdChanged(a,o,this.id);let s=j.compose(n,a.deviceIdx),c=j.compose(t,a.deviceIdx);if(this._api.cacheExternalId(s,o),this._api.mapDecorativeId(s,c),i)this._conversation.externalId=o;else{let e=this._participants;e[t].externalId=o}}_onVideoSuspendSuggest(e){!this._conversation||this._conversation.topology!==J.SERVER||(this._debug.debug(`Video suspend suggested`,e),L.onVideoSuspendSuggest(e.bandwidth,this.id))}async _onParticipantHold(e){this._debug.debug(`Participant hold suggested`,e);let t=this._getParticipant(e.participantId);if(!t){this._warnParticipantNotInConversation(e.participantId);return}if(t.isOnHold=e.hold,this._specListener?.onParticipantHoldChanged(),this._transport?.setRemoteHold(e.hold),e.hold)this._setParticipantsStatus([t],N.ONHOLD);else{let e=this._transport?.getTopology()===J.DIRECT?N.CONNECTING:N.CONNECTED;this._setParticipantsStatus([t],e)}}_isMe(e){return e===this._conversation?.compositeUserId}_getMuteStatesForRoomId(e=null){return this._conversation?.muteStates.get(e)??{}}_getMuteStatesForCurrentRoom(){return this._getMuteStatesForRoomId(this._conversation?.roomId)}_setMuteStatesForRoomId(e={},t=null){this._conversation?.muteStates.set(t,e)}_forceOpenTransportForAloneInCall(){this._transport?.getTopology()===J.SERVER&&this._transport?.getState()===q.IDLE&&!this._isCalledState()&&this._transport.open(this._transport.allocated(),null,!!this._conversation?.observer,!0)}_registerParticipant(e,t){let n=this._createParticipant(e,t);this._registerParticipantInCache(n)}_getParticipant(e){return this._participants[e]}},nc=null,rc=class e extends Error{constructor(t,n){super(t),h(this,`participantErrors`,void 0),Object.setPrototypeOf(this,e.prototype),this.participantErrors=n}},ic=class{constructor(){h(this,`_abortSignal`,void 0),h(this,`_apiCallStats`,null)}setApiCallStats(e){this._apiCallStats=e}setAbortSignal(e){this._abortSignal=e}async createJoinLink(e){return{join_link:`nop`}}async removeJoinLink(e){return{success:!0}}async getAnonymTokenByLink(e,t){return``}log(e){}logClientStats(e){return Promise.resolve()}logClientStatsWith(e,t){return Promise.resolve()}getCachedParticipantIdByExternalId(e){return null}getCachedExternalIdByParticipantId(e){return null}cacheExternalId(e,t){}mapDecorativeId(e,t){}unmapDecorativeId(e){}getDecorativeIdByInitialId(e){}hangupConversation(e,t=D.HUNGUP,n){}async removeHistoryRecords(e){}async getServerTime(){return Date.now()}cleanup(){}async getInbounds(){return[]}},ac=class e{constructor(){h(this,`_participantIdToExternalId`,new Map),h(this,`_externalIdToParticipantId`,new Map),h(this,`_decorativeIdToInitialId`,new Map),h(this,`_initialIdToDecorativeId`,new Map)}static _normalizeType(e){return e.type===ao.GROUP?{...e,type:ao.USER}:e}getExternalId(e){let t=this._initialIdToDecorativeId.get(e)??e,n=this._participantIdToExternalId.get(t);return n==null?null:Z.fromString(n)}getParticipantId(t){let n=Z.toString(e._normalizeType(t)),r=this._externalIdToParticipantId.get(n);return r==null?null:this._decorativeIdToInitialId.get(r)??r}cache(t,n){let r=e._normalizeType(n),i=Z.toString(r);this._participantIdToExternalId.set(t,i),this._externalIdToParticipantId.set(i,t)}mapDecorativeId(e,t){this._decorativeIdToInitialId.set(e,t),this._initialIdToDecorativeId.set(t,e)}unmapDecorativeId(e){let t=this._initialIdToDecorativeId.get(e);t&&this._decorativeIdToInitialId.delete(t),this._initialIdToDecorativeId.delete(e)}getDecorativeIdByInitialId(e){return this._initialIdToDecorativeId.get(e)}clear(){this._participantIdToExternalId.clear(),this._externalIdToParticipantId.clear(),this._decorativeIdToInitialId.clear(),this._initialIdToDecorativeId.clear()}},oc=`anonymLogin:`,sc=700,cc=3e3;function lc(e){let t=e.error_code;switch(t){case 2:return uc(D.SERVICE_UNAVAILABLE,t,`service-unavailable`);case 4:return e.error_msg.includes(`participants.limit.exceeded`)?uc(D.PARTICIPANT_LIMIT_REACHED,t,`participants-limit-exceeded`):uc(x.API,t,`request-error`);case 300:return uc(D.NOT_FOUND,t,`not-found`);case 1101:return uc(D.SERVICE_DISABLED,t,`vchat-service-disabled`);case 1102:return uc(D.CALLEE_IS_OFFLINE,t,`target-user-unavailable`);case 1103:return uc(D.NOT_FRIENDS,t,`friendship-required`);case 1104:return fc(t,`youla-api-error`);case 1106:return fc(t,`vk-api-error`);case 1113:return uc(D.CALLER_IS_REJECTED,t,`caller-is-rejected`);case 1114:{let n=e.custom_error?.vchat_detailed_api_error?.code,r=n?.startsWith(`obsolete_client`);return uc(r?D.OBSOLETE_CLIENT:D.VCHAT_DETAILED_ERROR,t,n??`detailed-error`,r?n:void 0)}default:return uc(x.API,t,`api-error`)}}function uc(e,t,n,r){return{type:e,callError:{scope:`server`,source:`api`,code:t,description:n},message:r}}function dc(e){return e?.error_code===void 0?e instanceof O&&e.callError&&`code`in e.callError?String(e.callError.code):e instanceof Error?e.name:`network`:String(e.error_code)}function fc(e,t){return{type:D.EXTERNAL_API_ERROR,callError:{scope:`external`,source:`api`,code:e,description:t}}}var pc=class extends ic{constructor(...e){super(...e),h(this,`_uuid`,void 0),h(this,`_idCache`,new ac)}async _callUnsafe(e,t={},n=!1){let r=async i=>{let a=performance.now();try{let r=await is(e,t,n);return this._apiCallStats?.log(e,performance.now()-a),r}catch(t){if(this._apiCallStats?.log(e,performance.now()-a,dc(t)),!t||typeof t!=`object`||!Object.hasOwn(t,`error_msg`)){i++;let n=t&&(typeof t==`object`||typeof t==`function`)?Object.getOwnPropertyNames(t).map(e=>`${e}: ${JSON.stringify(t[e])}`):[String(t)];if(R.debug(`${e} network error, attempt ${i}: ${n.join(`
|
|
14
|
+
`)}`),this._abortSignal?.aborted&&(R.debug(`${e} aborted`),this._abortSignal.throwIfAborted()),i<M.apiMaxAttempt)return await j.delay(Math.min(i*sc,cc),{signal:this._abortSignal}),r(i)}throw R.warn(e,`error`,t),t}};return r(0)}async _call(e,t={},n=!1,r=!0){try{return await this._callUnsafe(e,t,n)}catch(i){if(R.warn(`Api call error`,i),i instanceof O)throw i;if(Bo(i?.error_code)&&r)return await this._reauthorize(),this._call(e,t,n,!1);let a={message:i?.error_msg,code:i?.error_code};if(i.custom_error&&(a.custom_error=i.custom_error),mc(i)){let e=lc(i);throw a.callError=e.callError,a.message=e.message??a.message,new O(e.type,a)}throw new O(x.API,a)}}userId(e){if(y.isEmpty()){let{compositeUserId:t}=j.decomposeParticipantId(e),{id:n}=j.decomposeId(t);return Z.fromId(String(n))}return this._idCache.getExternalId(e)}async authorize(){if(this._ensureUuid(),!M.apiKey)throw new O(x.API,{message:`Required argument apiAppKey not passed`,callError:{scope:`internal`,code:`configuration`,description:`api-key-missing`}});let e=this._getCachedAnonymLogin();if(e){this._applyAnonymLogin(e);return}return this._anonymLogin(M.authToken).then(e=>{this._applyAnonymLogin(e),this._setCachedAnonymLogin(e)}).catch(e=>{throw e instanceof O?e:(e?.error_code===zo.AUTH_LOGIN&&(this._removeCachedAnonymLogin(),L.onTokenExpired()),new O(x.AUTH,{message:e?.error_msg,code:e?.error_code,callError:{scope:`server`,source:`api`,code:e?.error_code??`authentication`,description:`authentication-failed`}}))})}_anonymLogin(e){let t={session_data:{version:2,device_id:this._uuid,client_version:M.apiClientVersion,client_type:`SDK_JS`}};return e&&(t.session_data.auth_token=e,t.session_data.version=3),this._callUnsafe(`auth.anonymLogin`,t,!0)}_getAnonymLoginCacheKey(){return M.authToken?`${oc}${M.authToken}`:null}_getCachedAnonymLogin(){let e=this._getAnonymLoginCacheKey();if(!e)return null;let t=st.get(e);return hc(t)?t:(t&&st.remove(e),null)}_setCachedAnonymLogin(e){let t=this._getAnonymLoginCacheKey();!t||!hc(e)||st.set(t,{session_key:e.session_key,session_secret_key:e.session_secret_key,uid:e.uid})}_removeCachedAnonymLogin(){let e=this._getAnonymLoginCacheKey();e&&st.remove(e)}_reauthorize(){return this._removeCachedAnonymLogin(),y.reauthorize(()=>this.authorize())}_applyAnonymLogin(e){e.uid&&(y.userId=Number(e.uid)),y.sessionKey=e.session_key,y.sessionSecretKey=e.session_secret_key,M.statQueueEnabled&&e.uid&&fs.remember(Number(e.uid),{sessionKey:e.session_key,endpoint:fs.currentEndpoint()})}_buildClientStatsData(e){let t={app_version:M.appVersion,sdk_type:`WEB`,sdk_version:M.sdkVersion,version:1,items:e};return M.clientStatsPlatform&&(t.platform=M.clientStatsPlatform),{data:JSON.stringify(t)}}_reportClientStatsItemErrors(e){e?.items_responses?.forEach(e=>{e.errors&&R.error(`[vchat.clientStats]`,e)})}async _sendClientStatsWith(e,t){let n=await is(`vchat.clientStats`,{...t,session_key:e},!0);this._reportClientStatsItemErrors(n)}async _sendClientStats(e,t,n=!0){try{let n=t?await as(`vchat.clientStats`,e):await is(`vchat.clientStats`,e);this._reportClientStatsItemErrors(n)}catch(r){if(!n||!Bo(r?.error_code))throw r;await this._reauthorize(),await this._sendClientStats(e,t,!1)}}async logClientStats(e){let t=this._buildClientStatsData(e);if(!M.statQueueEnabled){this._sendClientStats(t,!0).catch(e=>R.error(`[vchat.clientStats]`,e));return}await this._sendClientStats(t,!1)}async logClientStatsWith(e,t){await this._sendClientStatsWith(e,this._buildClientStatsData(t))}async uploadDebugLogs(e,t,n,r){let i={conversationId:e,webrtcPlatform:M.platform,startTime:t,endTime:n},a=await this._callUnsafe(`vchat.getLogUploadUrl`,i),o=new FormData,s=new Blob([r],{type:`application/json`});o.append(`file`,s,`log.json`);let c=new URL(a.upload_url);return c.searchParams.append(`size`,s.size.toString()),cs(c.toString(),o)}async joinConversation(e,t=!1,n){let r={conversationId:e,isVideo:t,protocolVersion:M.protocolVersion,capabilities:wa.getFlags()};return n&&(r.chatId=n),this._call(`vchat.joinConversation`,r)}async createConversation(e,t=``,n=!1,{onlyAdminCanShareMovie:r,audienceMode:i,audioOnly:a,waitForAdmin:o,closedConversation:s}={},c){let l=this._preareStartConversationData({conversationId:e,isVideo:!1,joiningAllowed:!0,payload:t,requireAuthToJoin:n,onlyAdminCanShareMovie:r,waitForAdmin:o,closedConversation:s,audienceMode:i,audioOnly:a,externalIds:c});return this._startConversation(l)}async startConversation(e,t,n,r=!1,i=``,a=!1,o=!1,{onlyAdminCanShareMovie:s,waitForAdmin:c}={},l){let u=this._preareStartConversationData({conversationId:e,isVideo:r,joiningAllowed:a,payload:i,requireAuthToJoin:o,onlyAdminCanShareMovie:s,waitForAdmin:c,externalIds:l});if(t&&t.length)switch(n){case Ga.USER:u.uids=t.join(`,`);break;case Ga.GROUP:u.gid=t[0];break;case Ga.CHAT:u.chatId=t[0];break}return this._startConversation(u)}_ensureUuid(){if(!this._uuid){let e=st.get(`uuid`);e||(e=j.uuid(),st.set(`uuid`,e)),this._uuid=String(e)}}deviceId(){return this._ensureUuid(),this._uuid}_preareStartConversationData({conversationId:e,isVideo:t,payload:n=``,joiningAllowed:r=!1,requireAuthToJoin:i=!1,onlyAdminCanShareMovie:a,waitForAdmin:o,audienceMode:s=!1,audioOnly:c=!1,closedConversation:l=!1,externalIds:u}){let d={conversationId:e,isVideo:t,protocolVersion:M.protocolVersion};return r&&(d.createJoinLink=!0),n&&(d.payload=n),M.domain&&(d.domainId=M.domain),M.externalDomain&&(d.externalDomain=M.externalDomain),i&&(d.requireAuthToJoin=!0),a!==void 0&&(d.onlyAdminCanShareMovie=a),o!==void 0&&(d.waitForAdmin=o),s&&(d.audienceMode=s),c&&(d.audioOnly=c),l&&(d.closed=l),u&&(d.externalIds=u.map(Z.toSignaling).join(`,`)),d}async _startConversation(e){return this._call(`vchat.startConversation`,e)}async createJoinLink(e){return this._call(`vchat.createJoinLink`,{conversationId:e})}async removeJoinLink(e){return this._call(`vchat.removeJoinLink`,{conversationId:e})}async getAnonymTokenByLink(e,t){let n={joinLink:e};t&&(n.anonymName=t);let r=await this._call(`vchat.getAnonymTokenByLink`,n);return y.userId=Number(r.uid),r.token}async joinConversationByLink(e,t=!1,n,r){let i={joinLink:e,isVideo:t,protocolVersion:M.protocolVersion,capabilities:wa.getFlags()};return n?.length&&(i.observedIds=n.join(`,`)),M.anonymToken&&(i.anonymToken=M.anonymToken),r&&(i.payload=r),this._call(`vchat.joinConversationByLink`,i)}getCachedParticipantIdByExternalId(e){return this._idCache.getParticipantId(e)}getCachedExternalIdByParticipantId(e){return this._idCache.getExternalId(e)}cacheExternalId(e,t){this._idCache.cache(e,t)}mapDecorativeId(e,t){this._idCache.mapDecorativeId(e,t)}unmapDecorativeId(e){this._idCache.unmapDecorativeId(e)}getDecorativeIdByInitialId(e){return this._idCache.getDecorativeIdByInitialId(e)}async getConversationParams(e){let t={};return M.anonymToken&&(t.anonymToken=M.anonymToken),e&&(t.conversationId=e),this._call(`vchat.getConversationParams`,t)}getUserId(){return y.userId}setUserId(e){y.userId=e,M.statQueueEnabled&&y.sessionKey&&fs.remember(Number(e),{sessionKey:y.sessionKey,endpoint:fs.currentEndpoint()})}hangupConversation(e,t=D.HUNGUP,n){let r={conversationId:e,reason:t};M.anonymToken&&(r.anonymToken=M.anonymToken),n?.peerId&&(r.peerId=n.peerId),rs(`vchat.hangupConversation`,r)}async removeHistoryRecords(e){await this._call(`vchat.removeHistoryRecords`,{recordIds:e.join(`,`)})}cleanup(){this._idCache.clear()}async getServerTime(){return(M.statQueueEnabled?await this._call(`system.getInfo`,{},!1,!1):await this._call(`system.getInfo`)).serverTime}async getInbounds(){let e=await this._call(`vchat.getInbounds`);return Array.isArray(e?.inbounds)?e.inbounds:[]}};function mc(e){return typeof e==`object`&&!!e&&`error_code`in e&&`error_msg`in e}function hc(e){return typeof e==`object`&&!!e&&`session_key`in e&&`session_secret_key`in e&&typeof e.session_key==`string`&&e.session_key.length>0&&typeof e.session_secret_key==`string`&&e.session_secret_key.length>0}var gc=function(e){return e.KING=`KING`,e.PAWN=`PAWN`,e}(gc||{}),_c=function(e){return e.OFF=`0`,e.ON=`1`,e}({}),vc=class{constructor(e){h(this,`_queue`,void 0),h(this,`_readCursor`,void 0),h(this,`_writeCursor`,void 0),h(this,`_moveReadCursor`,void 0),h(this,`_left`,void 0),this._queue=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),e}},yc=class{constructor(e,t,n,r=null){h(this,`_uuid`,void 0),h(this,`_apiKey`,void 0),h(this,`_callToken`,void 0),h(this,`_apiEnv`,void 0),h(this,`_baseApiUrl`,void 0),h(this,`_sessionKey`,void 0),this._uuid=j.uuid(),this._apiKey=t,this._callToken=n,this._apiEnv=e,this._baseApiUrl=r}async authorize(){let e=await is(`auth.anonymLogin`,{session_data:{device_id:this._uuid,client_version:M.apiClientVersion,client_type:`SDK_JS`,auth_token:this._callToken,version:3},application_key:this._apiKey},!0,await ts(this._baseApiUrl,this._apiEnv));return j.isObject(e)&&!(`error_msg`in e)?(this._sessionKey=e.session_key,!0):!1}async hangupConversation(e,t){let n={conversationId:e,reason:D.HUNGUP,application_key:this._apiKey,session_key:this._sessionKey};t?.peerId&&(n.peerId=t.peerId),await is(`vchat.hangupConversation`,n,!0,await ts(this._baseApiUrl,this._apiEnv))}},bc,xc=null,Sc=!1,Cc={getCameras:T.getCameras,getMicrophones:T.getMicrophones,getOutput:T.getOutput,getVideoFacingMode:T.getVideoFacingMode,hasCamera:T.hasCamera,hasMicrophone:T.hasMicrophone,getSavedCamera:T.getSavedCamera,getSavedMicrophone:T.getSavedMicrophone,getSavedOutput:T.getSavedOutput,hasCameraPermission:T.hasCameraPermission,hasMicrophonePermission:T.hasMicrophonePermission,hasPermissions:T.hasPermissions,getUserMedia:T.getUserMedia,getUserVideo:T.getUserVideo,getUserAudio:T.getUserAudio,setResolution:T.setResolution,isBrowserSupported:T.isBrowserSupported,isScreenCapturingSupported:T.isScreenCapturingSupported,os:T.os,isMobile:T.isMobile,browserName:T.browserName,browserVersion:T.browserVersion,baseChromeVersion:T.baseChromeVersion,getAudioContext:T.getAudioContext,isAudioShareSupported:T.isAudioShareSupported},wc={participantMarkerCompare:j.participantMarkerCompare};function Tc(e){xc=e}function Ec(e){M.videoEffects=e}function Dc(e){M.audioEffects=e}function Oc(e,t={}){M.vad=e,M.vadOptions=t}function kc(e,t=null,n={},r=1){M.vmoji=e,M.vmojiOptions={protocolVersion:r,renderingOptions:n},t&&e.setSDK(t)}async function Ac(e){M.set(e),bc||(bc=new pc),M.statQueueEnabled&&(ms.setApi(bc),M.autoStartStats&&Lc()),c.default.disableLog(!M.debug),R.toggle(M.debug),R.log(`Calls SDK ${M.sdkVersion}`,e),await T.init();let t=T.getBrowserSupportFailure();if(t)throw new O(x.UNSUPPORTED,{callError:{scope:`internal`,code:`environment`,description:t}});R.log(`UserAgent:`,navigator.userAgent),R.log(`Screen resolution:`,`${window.screen.width}x${window.screen.height}`),R.log(`Permissions:`,`Camera: ${T.hasCameraPermission()}, Mic: ${T.hasMicrophonePermission()}`),R.log(`Simulcast:`,`${e.simulcast} => ${M.simulcast}`)}async function jc(e,t=[S.AUDIO],n=``,r=!1,i=!1,a,o,s){let c=[];return Array.isArray(e)?c=e.length?e:[]:e&&(c=[e]),Nc([],Ga.USER,t,n,r,i,a,c,o,s)}function Mc(e,t=[]){let n=e.getIncomingCallerExternalId();return n?t.length===1&&t[0].id===n.id&&t[0].type===n.type:!1}async function Nc(e,t=Ga.USER,n,r=``,i=!1,a=!1,o,s,c,l){if(!M.hold&&z.getActive())throw R.error(`There is already active call`),new O(D.HAS_ACTIVE_CALL);let u=z.getAll().find(e=>e.isIncomingRinging);if(!M.hold&&u&&!Mc(u,s))throw R.error(`There is already incoming call`),new O(D.HAS_ACTIVE_CALL);return new $(new pc,xc).onStart({opponentIds:e,opponentType:t,mediaOptions:n,payload:r,joiningAllowed:i,requireAuthToJoin:a,onlyAdminCanShareMovie:o,externalIds:s,onFastStart:c,conversationId:l})}async function Pc(e,t){return Fc(e,A.USER,void 0,t)}async function Fc(e,t=A.USER,n,r,i,a){if(e===$.id())throw Error(`Push has already been processed`);return new $(new pc,xc).onPush(e,t,n,r,i,a)}async function Ic(){return bc.getInbounds()}function Lc(){if(M.statQueueEnabled){if(!bc){R.error(`[CallsSDK] startStats() called before init()`);return}Sc||(Sc=!0,ws.start(bc))}}async function Rc(e,t){return e&&(M.authToken=e),t!==void 0&&M.apiBaseUrl!==t&&(M.apiBaseUrl=t,$o()),bc.authorize()}async function zc(e=[S.AUDIO],t){return uu(t).accept(e)}async function Bc(e){let t=su(e?.conversationId);if(t)return t.decline(e)}async function Vc(e,t=[S.AUDIO]){return Hc(e,t)}async function Hc(e,t,n){if(!M.hold&&z.callsLength>0)throw R.error(`There is already active call`),new O(D.HAS_ACTIVE_CALL);return new $(new pc,xc).onJoin({conversationId:e,mediaOptions:t,chatId:n})}async function Uc(e,t=[S.AUDIO],n,r,i,a){if(!M.hold&&z.callsLength>0)throw R.error(`There is already active call`),new O(D.HAS_ACTIVE_CALL);return n&&(M.anonymToken=n),new $(new pc,xc).onJoin({joinLink:e,mediaOptions:t,observedIds:r,payload:i,onFastJoin:a,anonymous:!!M.anonymToken})}function Wc(e){let t=su(e?.conversationId);return t?t.hangup(e):($.hangupAfterInit(e?.onFastHangup),Promise.resolve())}async function Gc(e,t){let n=Array.isArray(e)?e:[e],r=$.current();r&&await r.addParticipant(n,t)}async function Kc(e,t){let n=$.current();if(n){let r=e.map(e=>j.composeUserId(e));await n.addParticipantLegacy(r,t)}}async function qc(e,t=!1){let n=du(e,`removeParticipant`);if(n)try{await n.conversation.removeParticipant(j.decomposeParticipantId(n.participantId).compositeUserId,t)}catch(e){R.warn(`Failed to remove participant ${n.participantId}. Perhaps he is no longer on the call. ${e}`)}}async function Jc(e,t=!1){let n=$.current();if(n)try{await n.removeParticipant(j.composeUserId(e),t)}catch(t){R.warn(`Failed to remove participant ${e}. Perhaps he is no longer on the call. ${t}`)}}async function Yc(e,t){let n=$.current();if(e===`videoinput`&&Nt.contains(t))return M.videoFacingMode=t,n?(T.isMobile()&&n.stopVideoTrack(),n.changeDevice(e)):void 0;if(!await T._saveDeviceId(e,t))throw Error(`Device not found: ${t}`);if(n)return n.changeDevice(e)}async function Xc(e,t){let n=typeof e==`object`?{...e,fastScreenSharing:e.captureScreen&&e.fastScreenSharing,captureAudio:e.captureScreen&&e.captureAudio&&M.audioShare}:{captureScreen:e,fastScreenSharing:!1,captureAudio:!1},r=su(t);return r?r.toggleScreenCapturing(n):Promise.reject()}function Zc(e){let t=$.current();t&&t.toggleAnimojiCapturing(e)}async function Qc(e,t=!1){let n=$.current();n&&await n.setVideoStream(e,t)}async function $c(e,t){let n=su(t);n&&await n.toggleLocalVideo(e)}async function el(e,t){let n=su(t);n&&await n.toggleLocalAudio(e)}async function tl(e){let t=$.current();if(t)return t.setLocalResolution(e)}async function nl(e){let t=$.current();t&&await t.changePriorities(e)}async function rl(e,t){let n=$.current();if(n){if(t){let r=n.getCachedParticipantIdByExternalId(t);if(!r){cu(t,`changeParticipantState`,n);return}await n.changeParticipantState(e,r);return}await n.changeParticipantState(e)}}async function il(){let e=$.current();e&&await e.putHandsDown()}async function al(e){let t=$.current();t&&await t.updateDisplayLayout(e)}async function ol(e){let t=$.current();t&&await t.requestDisplayLayout(e)}async function sl(e,t,n=!1){let r=du(e,`grantRoles`);r&&await r.conversation.grantRoles(r.participantId,t,n)}async function cl(e,t,n,r=!1){let i=$.current();i&&await i.grantRoles(j.composeParticipantId(e,A.USER,t),n,r)}async function ll({externalId:e=null,muteStates:t,requestedMedia:n=[],roomId:r=null}){if(e){let i=du(e,`muteParticipant`);return i?i.conversation.muteParticipant(i.participantId,t,n,r):void 0}let i=$.current();i&&await i.muteParticipant(null,t,n,r)}async function ul({uid:e=null,muteStates:t,requestedMedia:n=[],deviceIdx:r=0,roomId:i=null}){let a=$.current();if(a){let o=e?j.composeParticipantId(e,A.USER,r):null;await a.muteParticipant(o,t,n,i)}}async function dl(e,t=!1,n=null){let r=du(e,`pinParticipant`);r&&await r.conversation.pinParticipant(r.participantId,t,n)}async function fl(e,t=!1,n=0,r=null){let i=$.current();i&&await i.pinParticipant(j.composeParticipantId(e,A.USER,n),t,r)}async function pl(e){let t=$.current();t&&await t.updateMediaModifiers(e)}async function ml(e){let t=$.current();t&&await t.enableVideoSuspend(e)}async function hl(e){let t=$.current();t&&await t.enableVideoSuspendSuggest(e)}async function gl(e){let t=$.current();t&&await t.changeOptions(e)}async function _l(e,t=null){if(t){let n=du(t,`chatMessage`);return n?n.conversation.chatMessage(e,j.decomposeParticipantId(n.participantId).compositeUserId):void 0}let n=$.current();n&&await n.chatMessage(e,null)}async function vl(e,t=null){let n=$.current();if(n){let r=t?j.composeUserId(t):null;await n.chatMessage(e,r)}}async function yl(e=10){let t=$.current();if(t)return t.chatHistory(e)}async function bl(e,t=null){if(t){let n=du(t,`customData`);return n?n.conversation.customData(e,n.participantId):void 0}let n=$.current();n&&await n.customData(e,null)}async function xl(e,t=null,n=0){let r=$.current();if(r){let i=t?j.composeParticipantId(t,A.USER,n):null;await r.customData(e,i)}}async function Sl(e=``,t=!1,{onlyAdminCanShareMovie:n=!1,waitForAdmin:r=!1,closedConversation:i=!1}={},a){return(await bc.createConversation(a??j.uuid(),e,t,{onlyAdminCanShareMovie:n,waitForAdmin:r,closedConversation:i})).join_link}async function Cl(e=``,t=!1,{onlyAdminCanShareMovie:n=!1,audioOnly:r=!1}={},i){let a=i.map(e=>Z.fromId(e));return(await bc.createConversation(j.uuid(),e,t,{onlyAdminCanShareMovie:n,audienceMode:!0,audioOnly:r},a)).join_link}async function wl(){let e=$.current();return e?e.createJoinLink():Promise.reject()}async function Tl(){let e=$.current();return e?e.removeJoinLink():Promise.reject()}async function El(e,t){return bc.getAnonymTokenByLink(e,t)}function Dl(e){let t=$.current();t&&t.setVolume(e)}function Ol(e){M.forceRelayPolicy=e}async function kl(e=!1,t=null,n=null,r=`DIRECT_LINK`,i=null,a=null){let o=$.current();return o?o.startStream(e,t,n,r,i,a):Promise.reject()}async function Al(e=null,t){let n=$.current();return n?n.stopStream(e,t):Promise.reject()}async function jl(e=null){let t=$.current();return t?t.publishStream(e):Promise.reject()}async function Ml(){let e=$.current();return e?e.getStreamInfo():Promise.reject()}async function Nl(e){let t=$.current();return t?t.addMovie(e):Promise.reject()}async function Pl(e){let t=$.current();return t?t.updateMovie(e):Promise.reject()}async function Fl(e){let t=$.current();return t?t.removeMovie(e):Promise.reject()}async function Il(e,t){let n=$.current();if(n){let r=[],i=[];for(let t of e){let e,a;t.addParticipantIds&&(e=[],t.addParticipantIds.forEach(t=>{let r=n.getCachedParticipantIdByExternalId(t);r?e.push(j.decomposeParticipantId(r).compositeUserId):i.push(t.id)})),t.removeParticipantIds&&(a=[],t.removeParticipantIds.forEach(e=>{let t=n.getCachedParticipantIdByExternalId(e);t?a.push(j.decomposeParticipantId(t).compositeUserId):i.push(e.id)})),r.push({id:t.id,name:t.name,participantCount:t.participantCount,addParticipantIds:e,removeParticipantIds:a,countdownSec:t.countdownSec})}if(i.length){lu(i,`updateRooms`,n);return}return n.updateRooms(r,t)}return Promise.reject()}async function Ll(e,t){let n=$.current();return n?n.activateRooms(e,t):Promise.reject()}async function Rl(e=null,t=null){let n=$.current();if(!n)return Promise.reject();let r;if(t&&(r=n.getCachedParticipantIdByExternalId(t)??void 0,!r)){cu(t,`switchRoom`,n);return}return n.switchRoom(e,r)}async function zl(e){let t=$.current();return t?t.removeRooms(e):Promise.reject()}function Bl(e){M.statisticsInterval=e;let t=$.current();if(t)return t.updateStatisticsInterval()}function Vl(e){c.default.disableLog(!e),R.toggle(e)}function Hl(e,...t){M.debugLog&&($.debugMessage(e,`[external]`,...t)||R.send(e,`[external]`,...t))}function Ul(e,t,...n){M.debugLog&&($.debugMessageWithContext(e,t,`[external]`,...n)||R.send(e,`[external]`,...n))}var Wl={list:Fe,get:Ie,getJson:Le,download:Re,clear:ze,stats:Be};function Gl(){let e=[[`Calls SDK ${M.sdkVersion}`,M.toJSON()],[`UserAgent:`,navigator.userAgent],[`Screen resolution:`,`${window.screen.width}x${window.screen.height}`],[`Permissions:`,`Camera: ${T.hasCameraPermission()}, Mic: ${T.hasMicrophonePermission()}`]],t=new Date,n=t.getTime(),r=t.toLocaleString(`ru-RU`,{dateStyle:`short`,timeStyle:`long`});return e.map(e=>({h:r,t:n,l:wn.LOG,d:e}))}async function Kl(){let e=$.id(),t=$.debugSessionId();if(!t||!e)throw R.error(`[uploadDebugLogs]`,`No conversation id found`),Error(`No conversation id found`);let n=await Ie({sessionId:t});if(n.length===0)throw R.error(`[uploadDebugLogs]`,`No logs found`),Error(`No logs found`);let r=n[0].t,i=n[n.length-1].t;try{return bc?.uploadDebugLogs(e,r,i,JSON.stringify([...Gl(),...n]))}catch(e){throw R.error(`[uploadDebugLogs]`,`Error while uploading logs`,e),Error(`Error while uploading logs`,{cause:e})}}async function ql(e){let t=$.current();if(t)return t.videoEffect(e)}async function Jl(e,t){let n=$.current();if(n)return n.audioEffect(e.length>0?e:null,t)}async function Yl(e){let t=$.current();t&&await t.setAudioStream(e)}async function Xl(e,t=null,n=null){let r=$.current();if(!r)return;let i=n??t?.id,a=null;if(t&&(a=r.getCachedParticipantIdByExternalId(t),!a)){cu(t,`setVmojiSvg`,r);return}r.setAnimojiSvg(e,a,i)}function Zl(e){let t=$.current();t&&t.setAnimojiFill(e)}async function Ql(e=null,t,n=!1){return uu().getWaitingHall(e,t,n)}async function $l(){return uu().getAudienceModeHands()}async function eu(e,t=!1){let n=uu(),r;if(e){let t=n.getCachedParticipantIdByExternalId(e);if(!t){cu(e,`promoteParticipant`,n);return}r=j.decomposeParticipantId(t).compositeUserId}return n.promoteParticipant(r,t)}async function tu(e=!1){return uu().requestPromotion(e)}async function nu(e=!1){return uu().acceptPromotion(e)}async function ru(e){return uu().getParticipantListChunk(e)}async function iu(e){return uu().getParticipants(e)}async function au(e){return uu().feedback(e)}async function ou(e,t,n){return uu(n).enableFeatureForRoles(e,t)}function su(e){return e?z.get(e)??null:$.current()??z.getFirst()}function cu(e,t,n){L.onNonFatalError(Error(`Participant ID mapping not found for external ID "${e.id}" while handling ${t}`),n.id)}function lu(e,t,n){let r=Array.from(new Set(e));L.onNonFatalError(Error(`Participant ID mapping not found for external IDs "${r.join(`", "`)}" while handling ${t}`),n.id)}function uu(e){let t=su(e);if(!t)throw Error(`Conversation not found`);return t}function du(e,t){let n=$.current();if(!n)return null;let r=n.getCachedParticipantIdByExternalId(e);return r?{conversation:n,participantId:r}:(cu(e,t,n),null)}async function fu(e){await bc.removeHistoryRecords(e)}async function pu(e){let t=$.current()??z.getFirst();t&&await t.startAsr(e)}async function mu(e){let t=$.current()??z.getFirst();t&&await t.stopAsr(e)}async function hu(e){let t=$.current()??z.getFirst();t&&await t.requestAsr(e)}async function gu(e){let t=$.current();return t?t.startUrlSharing(e):Promise.reject()}async function _u(){let e=$.current();return e?e.stopUrlSharing():Promise.reject()}async function vu(e){await z.switchCall(e)}function yu(){return z.getActiveId()}function bu(){return $.getSyncedTime()}function xu(){return M.sdkVersion}typeof window<`u`&&(window.__CALLS_SDK=xn),exports.Api=pc,exports.ApiExternal=yc,exports.ArrayDequeue=vc,exports.AuthData=y,exports.BaseLogger=m,exports.CallDirection=Wa,exports.CallType=Ga,exports.ChatRoomEventType=Ka,exports.ConversationFeature=qa,exports.ConversationOption=Ja,exports.DebugMessageType=wn,exports.ExternalIdType=ao,Object.defineProperty(exports,"FacingMode",{enumerable:!0,get:function(){return Nt}}),exports.FatalError=x,exports.HangupReason=O,exports.HangupType=D,exports.MediaOption=S,exports.MediaTrackKind=k,exports.MediaType=V,exports.MuteState=Za,exports.ParticipantState=X,exports.ParticipantStateDataValue=_c,exports.ParticipantStatus=N,exports.RecordRole=gc,exports.RoomsEventType=Qa,exports.Signaling=Ua,exports.SignalingCommandType=B,exports.SignalingConnectionType=br,exports.SignalingNotification=K,exports.TransportTopology=J,exports.UserRole=to,exports.UserType=A,exports.VolumeDetector=ko,exports.acceptCall=zc,exports.acceptPromotion=nu,exports.activateRooms=Ll,exports.addMovie=Nl,exports.addParticipant=Gc,exports.addParticipantInternal=Kc,exports.authorize=Rc,exports.browser=Cc,exports.callInternal=Nc,exports.callTo=jc,exports.captureScreen=Xc,exports.captureVmoji=Zc,exports.changeAudioEffect=Jl,exports.changeConversationOptions=gl,exports.changeDevice=Yc,exports.changeParticipantState=rl,exports.changePriorities=nl,exports.changeVideoEffect=ql,exports.chatHistory=yl,exports.chatMessage=_l,exports.chatMessageInternal=vl,exports.createJoinLink=wl,exports.customData=bl,exports.customDataInternal=xl,exports.debug=Vl,exports.debugLogs=Wl,exports.debugMessage=Hl,exports.debugMessageWithContext=Ul,exports.declineCall=Bc,exports.enableFeatureForRoles=ou,exports.enableVideoSuspend=ml,exports.enableVideoSuspendSuggest=hl,exports.feedback=au,exports.forceRelayPolicy=Ol,exports.getActiveCallId=yu,exports.getAnonymTokenByLink=El,exports.getAudienceModeHands=$l,exports.getInbounds=Ic,exports.getParticipantListChunk=ru,exports.getParticipants=iu,exports.getStreamInfo=Ml,exports.getSyncedTime=bu,exports.getWaitingHall=Ql,exports.grantRoles=sl,exports.grantRolesInternal=cl,exports.hangup=Wc,exports.init=Ac,exports.joinCall=Vc,exports.joinCallByLink=Uc,exports.joinCallInternal=Hc,exports.muteParticipant=ll,exports.muteParticipantInternal=ul,exports.pinParticipant=dl,exports.pinParticipantInternal=fl,exports.processPush=Pc,exports.processPushInternal=Fc,exports.promoteParticipant=eu,exports.publishStream=jl,exports.putHandsDown=il,exports.removeHistoryRecords=fu,exports.removeJoinLink=Tl,exports.removeMovie=Fl,exports.removeParticipant=qc,exports.removeParticipantInternal=Jc,exports.removeRooms=zl,exports.requestAsr=hu,exports.requestDisplayLayout=ol,exports.requestPromotion=tu,exports.setAudioEffects=Dc,exports.setAudioStream=Yl,exports.setLocalResolution=tl,exports.setLogger=Tc,exports.setMediaModifiers=pl,exports.setStatisticsInterval=Bl,exports.setVad=Oc,exports.setVideoEffects=Ec,exports.setVideoStream=Qc,exports.setVmoji=kc,exports.setVmojiFill=Zl,exports.setVmojiSvg=Xl,exports.setVolume=Dl,exports.startAsr=pu,exports.startAudienceConversation=Cl,exports.startConversation=Sl,exports.startStats=Lc,exports.startStream=kl,exports.startUrlSharing=gu,exports.stopAsr=mu,exports.stopStream=Al,exports.stopUrlSharing=_u,exports.switchCall=vu,exports.switchRoom=Rl,exports.toggleLocalAudio=el,exports.toggleLocalVideo=$c,exports.updateDisplayLayout=al,exports.updateMovie=Pl,exports.updateRooms=Il,exports.uploadDebugLogs=Kl,exports.utils=wc,exports.version=xu;
|