@vkontakte/calls-sdk 2.8.11-dev.273c92c2.0 → 2.8.11-dev.37528a3e.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/calls-sdk.cjs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @vkontakte/calls-sdk v2.8.11-dev.273c92c2.0
3
- * Thu, 28 May 2026 09:31:29 GMT
2
+ * @vkontakte/calls-sdk v2.8.11-dev.37528a3e.0
3
+ * Thu, 28 May 2026 15:32:02 GMT
4
4
  * https://calls-sdk.cdn-vk.ru/doc/latest/index.html
5
5
  */
6
6
 
@@ -11,7 +11,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
11
11
  `)}e.patchLocalSDP=p;function m(e,n,r,i,a,s,c){n&&(e=e.replace(`m=application 9 UDP/DTLS/SCTP webrtc-datachannel`,`m=application 9 DTLS/SCTP 5000`).replace(`a=sctp-port:5000`,`a=sctpmap:5000 webrtc-datachannel 256`));let p=e.split(t);return i?o(p,`H264`):r&&u(p,r),s&&c?o(p,`VP9`):s?l(p,`VP9`,`remote`,`encoder`):c?l(p,`VP9`,`remote`,`decoder`):a&&d(p),f(p),p.join(`\r
12
12
  `)}e.patchRemoteSDP=m;function h(e){return e?`${e.type||`WEB_SOCKET`}_${e.id}`:`_`}e.getPeerIdString=h;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 g=/^[0-9]+$/,_=/^([gu])([0-9]+)$/;function v(e,t=S.USER){let n=String(e);return _.test(n)?(R.warn(`Already composite id [${e}] type supplied [${t}]`),n):t===S.GROUP?`g`+n:t===S.USER?`u`+n:(R.warn(`Unknown type [${t}] for id [${e}]`),n.match(g)?`u`+n:n)}e.composeUserId=v;function y(e,t,n=0){return b(v(e,t),n)}e.composeParticipantId=y;function b(e,t){return t?e+`:d`+t:e}e.compose=b;function x(e){return y(e.id,e.idType||S.USER,e.deviceIdx)}e.composeId=x;function ne(e){if(e.decorativeUserId)return y(e.decorativeUserId,e.idType||S.USER,e.deviceIdx)}e.composeDecorativeId=ne;function ie(e){return e.participant?x(e.participant):y(e.participantId,e.participantType||S.USER,e.deviceIdx)}e.composeMessageId=ie;function ae(e){return typeof e==`string`?oe(se(e).compositeUserId).id:e}e.extractOkId=ae;function oe(e){let t=String(e),n=t.match(_);return n?{id:Number(n[2]),type:n[1]===`g`?S.GROUP:S.USER}:(R.warn(`Unsupported compositeId [${e}]`),{id:Number(t),type:S.USER})}e.decomposeId=oe;function se(e){let t=e.split(`:d`);return{compositeUserId:t[0],deviceIdx:t.length>1?parseInt(t[1],10):0}}e.decomposeParticipantId=se;function de(){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=de;function he(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=he;function C(e){if(!window.BigInt)return null;let t=``,n=e.split(`
13
13
  `);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=C;async function ge(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=ge;function _e(e,t,n){let r=[];return e.getSenders().forEach(e=>ve(t,e,e.track,n,r)),r}e.applySettings=_e;function ve(e,t,n,r,i){if(!RTCRtpSender.prototype.getParameters||!RTCRtpSender.prototype.setParameters||!e||!n||n.kind!==k.video)return;let a=n.getSettings();if(!a)return;let o=e.maxBitrateK?e.maxBitrateK*1024:null,s=a.width,c=a.height,l=s&&c&&e.maxDimension?Math.max(1,Math.max(s,c)/e.maxDimension):null,u=e.maxFramerate||null;if(s&&c&&e.maxDimension&&e.maxDimension>Math.max(s,c)){let e=Math.round(s*c/256),t=(Math.round(e*fe/1e4)+1)*1e4;o=o===null?t:Math.min(t,o)}let d=e.degradationPreference||`balanced`,f=r[n.id];if(f&&f.bitrate===o&&f.scaleResolutionDownBy===l&&f.maxFramerate===u&&f.degradationPreference===d){i[n.id]=f;return}i[n.id]={bitrate:o,scaleResolutionDownBy:l,maxFramerate:u,degradationPreference:d};let p=t.getParameters();if(p.encodings||(p.encodings=[{}]),p.encodings.length>1&&s&&c&&e.maxDimension){let t=Math.round(e.maxDimension*1.35),n=Math.max(s,c),r=ce(s,c,e?.bitrates?.generic),i=r.streams.length;R.log(`applyVideoTrackSettings: maxDim=${e.maxDimension} targetDim=${t} track=${s}x${c} sim=${JSON.stringify(r)}`),p.encodings.forEach((e,a)=>{e.scaleResolutionDownBy=le(e.rid);let o=Math.round(n/e.scaleResolutionDownBy);a<i-1?e.active=o<t:a>=i?e.active=!1:e.active=!0,a<i?e.maxBitrate=r.streams[a].bitrate:e.maxBitrate=0,e.scalabilityMode=re})}else p.encodings.forEach(t=>{e?.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),o?t.maxBitrate=o:delete t.maxBitrate,l?t.scaleResolutionDownBy=l:delete t.scaleResolutionDownBy,u?t.maxFramerate=u:delete t.maxFramerate});if(p.degradationPreference=d,p.encodings.length>0){t.setParameters?.(p).catch(e=>{R.error(`Failed to set sender parameters`,p,e)});let e=t.getParameters();R.log(`applyVideoTrackSettings: actual encodings= ${JSON.stringify(e.encodings)}`)}}e.applyVideoTrackSettings=ve;function ye(e,t){Array.isArray(t)||(t=[t]);for(let n of t)if(e.includes(n))return!0;return!1}e.includesOneOf=ye;function be(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=be;function xe(e){let t=e.map(e=>({uid:e.externalId,mediaSettings:e.mediaSettings,status:e.status,muteStates:e.muteStates,unmuteOptions:e.unmuteOptions,participantState:e.participantState,markers:e.markers,movieShareInfos:e.movieShareInfos,roles:e.roles}));return w.filterObservers?t.filter(e=>!e.uid.observer):t}e.mapSharedParticipants=xe;function T(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=T;function Se(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&&O(r)&&O(a))return Se(r,a,n);if(r!==a)return!1}return!0}e.isObjectsEquals=Se;function Ce(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=Ce;function we(e){return!Object.keys(e).length}e.isEmptyObject=we;function Te(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={[S.USER]:0,[S.GROUP]:1},{compositeUserId:i,deviceIdx:a}=se(e.id),{compositeUserId:o,deviceIdx:s}=se(t.id),{id:c,type:l}=oe(i),{id:u,type:d}=oe(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=Te;function E(e,t){return ue(Object.entries(e).filter(([,e])=>Array.isArray(t)?!t.includes(e):e!==t))}e.objectFilterOutValues=E;function D(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=D,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 O(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}e.isObject=O;function Ee(e,n,r,i){function a(e,t){let n=0,r=e.length,i=!1;for(let a=0;a<e.length;a++)if(!i&&e[a].startsWith(`m=video`)&&(n=a),e[a].startsWith(`a=mid:`+t)&&(i=!0),i&&e[a].startsWith(`m=`)){r=a;break}return{start:n,end:r}}function o(e,t,n,r,i,a,o){let s=`a=rid:`+r+` send`;for(let r=t;r<n;r++)e[r]===s&&(e[r]=s+` max-width=`+a+`;max-height=`+o+`;max-br=`+i)}let s=n?.sender;if(s&&s.track&&n.mid){let c=e.split(t),{start:l,end:u}=a(c,n.mid),d=s.getParameters();if(d.encodings)return d.encodings.forEach(e=>{let t=e.rid,n=e.maxBitrate,a=e.scaleResolutionDownBy;r&&i&&a&&o(c,l,u,t,n,``+Math.round(r/a),``+Math.round(i/a))}),c.join(`\r
14
- `)}return e}e.patchSimulcastAnswerSdp=Ee})(he||(he={}));var C=he,ge=`__CALLS_SDK_DEVTOOLS_`,_e=class{set(e,t){try{this.getStorage().setItem(ge+e,JSON.stringify(t))}catch(t){R.warn(`DevTools: Failed to save option`,e,t)}}get(e){try{let t=this.getStorage().getItem(ge+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(ge+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(ge)&&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(ge)){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}},ve=class{constructor(e){g(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}},ye=class e{static getInstance(){return e.instance||(e.instance=new e),e.instance}constructor(){g(this,`params`,void 0),g(this,`storage`,void 0),this.storage=new _e,this.params=new ve(this.storage)}};g(ye,`instance`,null);var be=ye.getInstance(),w=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`)&&(x.accessToken=t.apiAuth.accessToken,x.sessionKey=t.apiAuth.sessionKey,x.sessionSecretKey=t.apiAuth.sessionSecretKey);let n=be.params.applyOverrides(t);Object.assign(e._params,C.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 1.1}static get sdkVersion(){return`2.8.11-dev.273c92c2.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 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://api-mames.calls-test.oneme.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 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||(I.isMobile()?dt.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 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 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 clientEventsLoggingEnabled(){return e._params.clientEventsLoggingEnabled}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 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 I.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 I.isSimulcastSupportedByBrowser()&&e._params.simulcast}static get webtransport(){return e._params.webtransport}static get webtransportFF(){return e._params.webtransportFF}static get transparentAudio(){return e._params.transparentAudio}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,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,consumerScreenDataChannelPacketSize:e._params.consumerScreenDataChannelPacketSize,switchVideoAtBadNetwork:e._params.switchVideoAtBadNetwork,simulcast:e._params.simulcast,webtransport:e._params.webtransport,webtransportFF:e._params.webtransportFF,transparentAudio:e._params.transparentAudio}}};g(w,`_params`,{platform:`WEB`,clientStatsPlatform:``,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,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,vmoji:null,vmojiOptions:null,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,clientEventsLoggingEnabled:!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,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,webtransportFF:!1,transparentAudio:!1});function xe(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 T(e){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,isFastScreenSharingEnabled:!1,isAudioSharingEnabled:!1,isAnimojiEnabled:!1},e||{})}var Se=e=>e.stop(),Ce=e=>e.getTracks().forEach(Se),we=e=>e.getVideoTracks().forEach(Se);async function Te(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 E=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.CALLER_IS_REJECTED=`CALLER_IS_REJECTED`,e.UNKNOWN_ERROR=`UNKNOWN_ERROR`,e.UNSUPPORTED=`UNSUPPORTED`,e.OLD_VERSION=`OLD_VERSION`,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}(E||{}),D=class e extends Error{constructor(t,n){super(),g(this,`message`,void 0),g(this,`hangup`,void 0),g(this,`error`,void 0),g(this,`code`,void 0),g(this,`remote`,void 0),g(this,`custom_error`,void 0),this.name=`HangupReason`,this.code=n&&n.code||0,this.remote=n&&n.remote||!1,this.custom_error=n?.custom_error??null,Object.values(E).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)}},O=class e extends m{static setConversationIdProvider(t){e._conversationIdProvider=t}static create(t,n){e._instance||(e._instance=new e(t,n))}static log(t,n,r=!1){e._instance&&e._instance.log(t,n,r)}static logClientStats(t,n=!1){e._instance&&e._instance.logClientStats(t,n)}static logClientEvent(t,n=!1){e._instance&&e._instance.logClientEvent(t,n)}static destroy(){e._instance&&e._instance.destroy(),e._instance=null}constructor(e,t){super(),g(this,`_externalLogger`,void 0),g(this,`_api`,void 0),g(this,`_batchInterval`,3e3),g(this,`_batchedClientStats`,[]),g(this,`_batchedClientEvents`,[]),g(this,`_batchTimeout`,null),g(this,`_serverTimeDelta`,0),this._api=e,this._externalLogger=t,this._calculateServerTimeDelta()}log(e,t,n=!1){this._externalLogger&&this._externalLogger.log(e,t,n)}logClientStats(e,t=!1){let n=Object.assign(e,{vcid:this._getConversationId(),timestamp:this._now()});Object.keys(n).forEach(e=>{n[e]===void 0&&delete n[e]}),this._batchedClientStats.push(n),(t||!this._batchTimeout)&&this._sendBatch()}logClientEvent(e,t=!1){let n=Object.assign(e,{vcid:this._getConversationId(),timestamp:this._now()});this._batchedClientEvents.push(n),(t||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}_getConversationId(){if(e._conversationIdProvider)try{return e._conversationIdProvider()}catch{return null}return null}_sendBatch(){this._stopTimeout();let e=!1;this._batchedClientStats.length>0&&(this._sendClientStats(this._batchedClientStats),this._batchedClientStats=[],e=!0),this._batchedClientEvents.length>0&&(this._sendClientEvents(this._batchedClientEvents),this._batchedClientEvents=[],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)}_sendClientEvents(e){this._api.logClientEvents(e)}async _calculateServerTimeDelta(){try{let e=await this._api.getServerTime();this._serverTimeDelta=Date.now()-e}catch{}}_now(){return Date.now()-this._serverTimeDelta}};g(O,`_instance`,void 0),g(O,`_conversationIdProvider`,null);var Ee=function(e){return e.FpsLimit=`fps-limit`,e}({}),De=class extends _{constructor(...e){super(...e),g(this,`FPS_LIMITS`,[13,20,Math.max(w.videoFrameRate,25)]),g(this,`THRESHOLD`,.8),g(this,`HISTORY_LENGTH`,10),g(this,`_fpsMeterUnsubscribe`,null),g(this,`_fpsHistory`,{cursor:0,arr:[]}),g(this,`_fpsLimitCursor`,this.FPS_LIMITS.length-1)}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){R.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()}},Oe=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}({}),ke=function(e){return e[e.CAMERA=1]=`CAMERA`,e[e.SCREEN=2]=`SCREEN`,e}({}),Ae=class extends _{constructor(){super(),g(this,`_stream`,null),g(this,`_screenTrack`,null),g(this,`_audioShareTrack`,null),g(this,`_screenShareTrack`,null),g(this,`_sendVideoTrack`,null),g(this,`_cameraVideoTrack`,null),g(this,`_micAudioTrack`,null),g(this,`_audioEffectsTrack`,null),g(this,`_mediaSettings`,T()),g(this,`_lastMediaSettings`,null),g(this,`_videoStatusOnScreenCapturingEnabled`,!1),g(this,`_effect`,null),g(this,`_audioEffectParams`,null),g(this,`_onDeviceChange`,void 0),g(this,`_animojiEnabled`,!1),g(this,`_videoEffectsFpsLimiter`,void 0),g(this,`videoTrackMuteHandler`,()=>{this._mediaSettings.isVideoEnabled&&this.toggleVideo(!0)}),this._initDeviceChangeListener(),w.audioShare&&(this._audioShareTrack=this.getSilentAudioShareTrack()),w.enableVideoEffectsFpsDegradation&&(this._videoEffectsFpsLimiter=new De,this._videoEffectsFpsLimiter.addEventListener(Ee.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._cameraVideoTrack.addEventListener(`mute`,this.videoTrackMuteHandler),w.consumerFastScreenShare&&(this._screenShareTrack=this.getBlackScreenShareTrack())}async request(e=[y.AUDIO],t=!0){if(this._stream)return;let n=e.includes(y.VIDEO),r=e.includes(y.AUDIO),i=e.includes(y.ANIMOJI);if(!I.isBrowserSupported())throw new D(v.UNSUPPORTED);try{this._stream=await I.getUserMedia(n,r,t),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 D(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(){return this._stream?.getAudioTracks().find(e=>!e.contentHint)||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(v.UNKNOWN)}}stopVideoTrack(){this._mediaSettings.isVideoEnabled&&(this._stopEffect(),this._stream&&we(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=I.getSavedMicrophone(),n=I.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{}},I.addEventListener(`devicechange`,this._onDeviceChange))}_destroyDeviceChangeListener(){this._onDeviceChange&&I.removeEventListener(`devicechange`,this._onDeviceChange)}async _changeVideoInput(e){try{let t=e?`stream`:`video`,n=e||await I._getUserVideo(!!this._effect,this._frameRate);if(this.cameraVideoTrack?.stop(),this.cameraVideoTrack=n.getVideoTracks()[0],!this._stream)Ce(n);else{let e=await this._setEffect(this._effect,this.cameraVideoTrack);O.log(b.DEVICE_CHANGED,t),R.log(`Video stream changed`),await this._replaceLocalTrack(e),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent(`SOURCE_CHANGED`,{kind:`video`})}}catch(e){throw O.log(b.ERROR,`change_video`),R.warn(`Camera change failed`,e),e}}async setAudioStream(e){return this._changeAudioInput(e)}async _changeAudioInput(e=null){try{let t=e||await I.getUserAudio();if(this._micAudioTrack?.stop(),this._micAudioTrack=t.getAudioTracks()[0],!this._stream)Ce(t);else{let e=await this._applyAudioEffect();O.log(b.DEVICE_CHANGED,`audio`),R.log(`Audio stream changed`,e),await this._replaceLocalTrack(e),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent(`SOURCE_CHANGED`,{kind:`audio`})}}catch(e){throw O.log(b.ERROR,`change_audio`),R.error(`Microphone change failed`,e),e}}async _changeScreen(e,t,n){try{if(n=n||await I.getScreenMedia(e,t),!this._stream)Ce(n);else{let r=n.getVideoTracks()[0];if(r.addEventListener(`ended`,()=>{this._mediaSettings.isScreenSharingEnabled&&this.disableScreenCapturing()},!1),O.log(b.DEVICE_CHANGED,`screen`),R.log(`Screen capturing started`),this._screenTrack=r,this._mediaSettings.isScreenSharingEnabled=!0,this._mediaSettings.isFastScreenSharingEnabled=e,w.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._replaceLocalTrack(e),this._mediaSettings.isAudioSharingEnabled=!0}t&&!this._mediaSettings.isAudioSharingEnabled&&R.debug(`Audio share requested but not captured`),this._triggerEvent(`SCREEN_STATUS`,{track:r}),this._triggerEvent(`SOURCE_CHANGED`,{kind:`screen`})}}catch(e){throw O.log(b.ERROR,`screen`),R.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){this._audioShareTrack.stop();let e=this.getSilentAudioShareTrack();await this._replaceLocalTrack(e),this._mediaSettings.isAudioSharingEnabled=!1}}async _applyAudioEffect(){if(!w.audioEffects||!this._audioEffectParams)return w.audioEffects?.pause(),this._micAudioTrack;w.audioEffects.isInitialized||await w.audioEffects.init(),w.audioEffects.resume(),w.audioEffects.setEffects(this._audioEffectParams.effects,this._audioEffectParams.isPreset),w.audioEffects.setSource(this._micAudioTrack);let e=w.audioEffects.outputStream.getAudioTracks()[0];return(!this._audioEffectsTrack||this._audioEffectsTrack.id!==e.id)&&(this._audioEffectsTrack=e),this._audioEffectsTrack}getSilentAudioShareTrack(){let e=I.getSilentMediaTrack();return e.contentHint=`music`,e.stop(),e}getBlackScreenShareTrack(){let e=I.getBlackMediaTrack();return e.contentHint=`motion`,e.stop(),e}async _replaceLocalTrack(e,t){if(!this._stream)return;let n=this._stream.getTracks().find(t=>t.kind===e.kind&&t.contentHint===e.contentHint);n?.id!==e.id&&(n?(n!==this._audioEffectsTrack&&n.stop(),this._stream?.removeTrack(n),this._stream?.addTrack(e),this._triggerEvent(`TRACK_REPLACED`,e,t)):(this._stream.addTrack(e),this._triggerEvent(`TRACK_REPLACED`,e,t)))}async _setEffect(e,t){if(this._videoEffectsFpsLimiter?.watch(w.videoEffects),!w.videoEffects)return t;try{return w.videoEffects.setEffect(e,t)}catch(e){return R.warn(`Video effect failed`,e),t}}_stopEffect(){if(w.videoEffects)try{w.videoEffects.stopEffect()}catch(e){R.warn(`Video effect failed`,e)}}destroy(){this._destroyDeviceChangeListener(),I.releaseFirefoxMicrophonePermissionWarmup(),w.videoEffects&&(this._effect=null,w.videoEffects.destroy()),w.audioEffects&&w.audioEffects.destroy(),this._stream&&(Ce(this._stream),this._stream=null),this.cameraVideoTrack?.stop(),this._micAudioTrack?.stop(),this._audioEffectsTrack?.stop(),this._disableScreenCapture(),I.getAudioContext()?.suspend().catch(e=>R.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(){if(!this._lastMediaSettings)return;let e=[];if(this._lastMediaSettings.isAudioEnabled&&(e.push(y.AUDIO),await this.toggleAudio(!0)),await this.request(e),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 I._getUserVideo(!!this._effect,this._frameRate);this.cameraVideoTrack=e.getVideoTracks()[0],t=await this._setEffect(this._effect,this.cameraVideoTrack)}else t=I.getBlackMediaTrack(w.videoMinWidth,w.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 I.getUserAudio();this._micAudioTrack=e.getAudioTracks()[0],t(await this._applyAudioEffect(),!0)}catch(e){throw w.audioEffects?.pause(),t(I.getSilentMediaTrack(),!1),typeof e==`string`?Error(e):e}else w.audioEffects?.pause(),t(I.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:w.noiseSuppression})}async videoEffect(e){if(!w.videoEffects)throw Error(`Video Effects library is not set`);if(O.log(b.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(!w.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||!C.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<w.videoFrameRate&&this._applyVideoConstraints(this.cameraVideoTrack).catch(e=>{R.warn(`MediaSource handleVideoEffectsLowFps error`,e)})}get _frameRate(){let e=this._videoEffectsFpsLimiter?.fpsLimit??w.videoFrameRate;return this._effect?Math.min(e,w.videoFrameRate):void 0}async _applyVideoConstraints(e,t){await Te(e,{width:this._effect?w.videoEffectMaxWidth:w.videoMaxWidth,height:this._effect?w.videoEffectMaxHeight:w.videoMaxHeight,...this._frameRate&&{frameRate:{ideal:this._frameRate}},...t})}getScreenShareTrack(){return this._screenShareTrack}},je=class{constructor(){g(this,`_cameraPermissionStatus`,void 0),g(this,`_microphonePermissionStatus`,void 0),g(this,`_listener`,void 0)}static isSupported(){return I.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){let t=null;switch(e){case`camera`:t=this._cameraPermissionStatus.state;break;case`microphone`:t=this._microphonePermissionStatus.state;break}return t}},A=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 j(e,...t){let n=w.get(e);typeof n==`function`&&setTimeout(n,0,...t)}function M(e,t,...n){if(w.filterObservers){if(Array.isArray(t)){if(t=t.filter(e=>!e.observer),!t.length)return}else if(t.observer)return}j(e,t,...n)}function N(e){return Object.assign({},e)}function Me(e){return e.slice()}var Ne;(function(e){function t(e,t,n){j(`onLocalStream`,e,N(t),n)}e.onLocalStream=t;function n(e,t){j(`onScreenStream`,e,N(t))}e.onScreenStream=n;function r(e,t){j(`onVmojiStream`,e,N(t))}e.onVmojiStream=r;function i(e){j(`onVmojiError`,e)}e.onVmojiError=i;function a(e,t){j(`onLocalStreamUpdate`,N(e),t)}e.onLocalStreamUpdate=a;function o(e,t){R.debug(`Local status:`,e),j(`onLocalStatus`,e,t)}e.onLocalStatus=o;function s(e,t,n){M(`onRemoteStream`,e,t,n)}e.onRemoteStream=s;function c(e,t){M(`onRemoteLive`,e,t)}e.onRemoteLive=c;function l(e,t){M(`onLocalLive`,e,t)}e.onLocalLive=l;function u(e,t){M(`onRemoteLiveUpdate`,e,t)}e.onRemoteLiveUpdate=u;function d(e,t){M(`onLocalLiveUpdate`,e,t)}e.onLocalLiveUpdate=d;function f(e,t,n){M(`onRemoteScreenStream`,e,t,n)}e.onRemoteScreenStream=f;function p(e,t){M(`onRemoteVmojiStream`,e,t)}e.onRemoteVmojiStream=p;function m(e,t,n){M(`onRemoteStreamSuspended`,e,t,n)}e.onRemoteStreamSuspended=m;function h(e,t,n,r,i,a){M(`onConversation`,e,N(t),N(n),r,i,a)}e.onConversation=h;function ee(e){e&&j(`onConversationParticipantListChunk`,e)}e.onConversationParticipantListChunk=ee;function te(e,t,n){M(`onRemoteMediaSettings`,e,N(t),n)}e.onRemoteMediaSettings=te;function g(e,t){M(`onLocalMediaSettings`,e,N(t))}e.onLocalMediaSettings=g;function _(e,t,n){M(`onRemoteSharedMovieInfo`,e,N(t),n)}e.onRemoteSharedMovieInfo=_;function v(e,t,n){M(`onRemoteSharedMovieStoppedInfo`,e,N(t),n)}e.onRemoteSharedMovieStoppedInfo=v;function y(e,t,n){M(`onLocalSharedMovieInfo`,e,N(t),n)}e.onLocalSharedMovieInfo=y;function b(e,t,n){M(`onLocalSharedMovieStoppedInfo`,e,N(t),n)}e.onLocalSharedMovieStoppedInfo=b;function x(e,t,n){M(`onRemoteSharedUrl`,e,t,n)}e.onRemoteSharedUrl=x;function S(e,t,n){M(`onParticipantAdded`,e,t,n)}e.onParticipantAdded=S;function ne(e,t,n){M(`onParticipantJoined`,e,t,n)}e.onParticipantJoined=ne;function re(e,t=!1){j(`onLocalParticipantState`,N(e),t)}e.onLocalParticipantState=re;function ie(e,t,n){M(`onRemoteParticipantState`,e,N(t),n)}e.onRemoteParticipantState=ie;function ae(e,t){j(`onRemoteParticipantsState`,e,t)}e.onRemoteParticipantsState=ae;function oe(e,t,n=null,r){R.debug(`Remote status:`,t,e),M(`onRemoteStatus`,e,t,n,r)}e.onRemoteStatus=oe;function se(){j(`onPermissionsRequested`)}e.onPermissionsRequested=se;function ce(e,t){j(`onPermissionsError`,e,t)}e.onPermissionsError=ce;function le(e,t,n){M(`onRemoteRemoved`,e,t,n)}e.onRemoteRemoved=le;function ue(e,t,n,r){j(`onCallState`,e,t,N(n),r)}e.onCallState=ue;function de(e,t,n){j(`onDeviceSwitched`,e,t,n)}e.onDeviceSwitched=de;function fe(e,t,n,r=!1,i=!1,a=null,o=null,s,c,l=null){let u=c?Me(c):void 0;j(`onMuteStates`,N(e),Me(t),Me(n),r,i,a,o,s,u,l)}e.onMuteStates=fe;function pe(e,t,n=!1){M(`onRolesChanged`,e,Me(t),n)}e.onRolesChanged=pe;function me(e,t=!1){j(`onLocalRolesChanged`,Me(e),t)}e.onLocalRolesChanged=me;function he(e,t,n,r){M(`onPinnedParticipant`,e,t,n,r)}e.onPinnedParticipant=he;function C(e,t){j(`onLocalPin`,e,t)}e.onLocalPin=C;function ge(e){j(`onOptionsChanged`,Me(e))}e.onOptionsChanged=ge;function _e(e){j(`onCallAccepted`,e)}e.onCallAccepted=_e;function ve(e){j(`onCallActive`,e)}e.onCallActive=ve;function ye(e,t,n){M(`onAcceptedCall`,e,t,n)}e.onAcceptedCall=ye;function be(){j(`onRateNeeded`)}e.onRateNeeded=be;function w(e,t){M(`onSpeakerChanged`,e,t)}e.onSpeakerChanged=w;function xe(e){j(`onVolumesDetected`,Me(e))}e.onVolumesDetected=xe;function T(e,t){j(`onLocalVolume`,e,t)}e.onLocalVolume=T;function Se(e,t){j(`onJoinStatus`,e,t)}e.onJoinStatus=Se;function Ce(e,t){j(`onHangup`,e,t)}e.onHangup=Ce;function we(e){j(`onMultipartyChatCreated`,N(e))}e.onMultipartyChatCreated=we;function Te(){j(`onDeviceChange`)}e.onDeviceChange=Te;function E(e){j(`onFingerprintChange`,e)}e.onFingerprintChange=E;function D(){j(`onTokenExpired`)}e.onTokenExpired=D;function O(e,t,n=!1){j(`onChatMessage`,e,t,n)}e.onChatMessage=O;function Ee(e,t,n=!1){j(`onCustomData`,e,t,n)}e.onCustomData=Ee;function De(e,t,n,r,i,a,o=null){j(`onRecordStarted`,e,t,n,r,i,a,o)}e.onRecordStarted=De;function Oe(e=null,t){j(`onRecordStopped`,e,t)}e.onRecordStopped=Oe;function k(e){j(`onLocalNetworkStatusChanged`,e)}e.onLocalNetworkStatusChanged=k;function ke(e){j(`onNetworkStatusChanged`,e)}e.onNetworkStatusChanged=ke;function Ae(e,...t){j(`onDebugMessage`,e,...t)}e.onDebugMessage=Ae;function je(e,t){j(`onStatistics`,Object.assign({},e,{memory:t}))}e.onStatistics=je;function A(){j(`onAutoplayError`)}e.onAutoplayError=A;function Ne(e,t,n,r,i){j(`onChatRoomUpdated`,e,t,n,r,i)}e.onChatRoomUpdated=Ne;function P(e){j(`onPromoted`,e)}e.onPromoted=P;function Pe(e){j(`onRemoteMixedAudioStream`,e)}e.onRemoteMixedAudioStream=Pe;function Fe(e){j(`onJoinLinkChanged`,e)}e.onJoinLinkChanged=Fe;function Ie(e){j(`onRoomsUpdated`,e)}e.onRoomsUpdated=Ie;function Le(e,t,n,r){j(`onRoomUpdated`,e,t,n,r)}e.onRoomUpdated=Le;function Re(e){j(`onRoomParticipantsUpdated`,e)}e.onRoomParticipantsUpdated=Re;function ze(e){j(`onRoomSwitched`,e)}e.onRoomSwitched=ze;function Be(e){j(`onRoomStart`,e)}e.onRoomStart=Be;function Ve(e,t=null){j(`onFeedback`,e,t)}e.onFeedback=Ve;function He(e){j(`onFeaturesPerRoleChanged`,e)}e.onFeaturesPerRoleChanged=He;function Ue(e){j(`onParticipantVmojiUpdate`,e)}e.onParticipantVmojiUpdate=Ue;function We(e,t){j(`onAsrSet`,e,t)}e.onAsrSet=We;function Ge(e,t,n){j(`onAsrStarted`,e,t,n)}e.onAsrStarted=Ge;function Ke(e){j(`onAsrStopped`,e)}e.onAsrStopped=Ke;function qe(e,t,n,r){j(`onAsrTranscription`,e,t,n,r)}e.onAsrTranscription=qe;function Je(e,t){j(`onParticipantIdChanged`,e,t)}e.onParticipantIdChanged=Je;function Ye(e){j(`onVideoSuspendSuggest`,e)}e.onVideoSuspendSuggest=Ye;function Xe(e){j(`onSignalingMessage`,typeof e==`string`?e:N(e))}e.onSignalingMessage=Xe;function Ze(e){j(`onPromotionApproved`,e)}e.onPromotionApproved=Ze;function Qe(){j(`onPeerRegistered`)}e.onPeerRegistered=Qe})(Ne||(Ne={}));var P=Ne,Pe=`_okcls_`,Fe=(()=>{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 Ie(e){let t=Fe?Fe.getItem(Pe+e):null;if(t===null)return null;try{return JSON.parse(t)}catch{return null}}function Le(e,t){try{Fe&&Fe.setItem(Pe+e,JSON.stringify(t))}catch{}}function Re(e){Fe&&Fe.removeItem(Pe+e)}var ze;(function(e){function t(e){return Ie(e)||null}e.get=t;function n(e,t){Le(e,t)}e.set=n;function r(e){Re(e)}e.remove=r})(ze||(ze={}));var Be=ze,Ve=null,He=null,Ue=null,We=[],Ge=[],Ke=[],qe=null,Je=null,Ye=null,Xe=!1,Ze=!1,Qe,$e,et,tt=null,nt=null,rt=``,it=null,at=[],ot=null,st=navigator.appVersion,ct=navigator.appName,lt=navigator.userAgent,ut={},dt=function(e){return e.USER=`user`,e.ENVIRONMENT=`environment`,e}({});(function(e){function t(e){return Object.values(dt).includes(e)}e.contains=t})(dt||(dt={}));var ft=class{constructor(e,t=!1,n=w.videoMaxWidth,r=w.videoMaxHeight,i=w.videoFrameRate){g(this,`audio`,void 0),g(this,`video`,void 0),g(this,`needVideo`,void 0),g(this,`lastSimplifyWasReached`,void 0),g(this,`supportedConstraints`,void 0),g(this,`isVideoRequested`,()=>this.needVideo),this.supportedConstraints=navigator.mediaDevices.getSupportedConstraints();let a=!1;if(e){a={noiseSuppression:w.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let t=F.getMicrophones(),n,r;if(Je&&(r=Je.groupId,n=Je.deviceId),typeof e==`string`)r=t.find(t=>t.deviceId===e)?.groupId,n=e;else if(!Je&&F.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:w.videoMinWidth,max:n,ideal:n},height:{min:w.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:w.videoAspectRatio},frameRate:{ideal:i}};let e=F.getCameras(),a,s;if(qe&&(s=qe.groupId,a=qe.deviceId),typeof t==`string`)s=e.find(e=>e.deviceId===t)?.groupId,a=t;else if(!qe&&F.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}),w.videoFacingMode&&(o.facingMode={ideal:w.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 ft{constructor(e,t,n,r){if(super(!1,!0),g(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):this.video={},this.video.cursor=`motion`,this.video.width=e,this.video.height=t,this.video.frameRate=n,this.video.displaySurface=w.displaySurface,F.browserName()===`Safari`){let n=Number(F.browserVersion());n===16?(this.video.width={max:e},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:w.audioShareSystemInclude?`include`:`exclude`,windowAudio:w.audioShareWindowInclude?`include`:`exclude`,controller:this.captureController})}},mt=class e{constructor(){g(this,`_lockId`,Math.round(Math.random()*99998)+1)}busy(){if(e._lockId)throw O.log(b.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)}};g(mt,`_lockId`,0);async function ht(){Ze=!1,Xe=!1,Ve=null;let e={camera:F.getSavedCamera(),microphone:F.getSavedMicrophone(),output:F.getSavedOutput()};await _t(),gt(`devicechange`,e),P.onDeviceChange()}function gt(e,...t){if(ut[e])for(let n of ut[e])n(...t)}async function _t(){return Ve||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!He&&navigator.mediaDevices.addEventListener&&(He=C.debounce(ht,w.enumerateDevicesDelay),navigator.mediaDevices.addEventListener(`devicechange`,He)),!Ue&&je.isSupported()&&(Ue=new je,await Ue.init((e,t)=>{switch(t){case`denied`:case`prompt`:He?.();break}})),Ve=navigator.mediaDevices.enumerateDevices().then(e=>{We=e.filter(e=>e.kind===`videoinput`?(e.label&&(Xe=!0),!0):!1),Ge=e.filter(e=>e.kind===`audioinput`?(e.label?Ze=!0:F.isMobile()&&F.browserName()===`Firefox`&&(Ze=Xe),!0):!1),Ke=e.filter(e=>e.kind===`audiooutput`);let t=qe?.deviceId??Be.get(`videoinput`),n=Je?.deviceId??Be.get(`audioinput`),r=Ye?.deviceId??Be.get(`audiooutput`);return qe=We.find(e=>e.deviceId===t)||null,Je=Ge.find(e=>e.deviceId===n)||null,Ye=Ke.find(e=>e.deviceId===r)||Ke[0]||null,Ve=Promise.resolve(e),e}).catch(()=>(Ve=null,[]))))}async function vt(){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]);it=isNaN(t)?null:t}catch(e){R.warn(`Failed to get OS version`,e)}}function yt(e){if(qe&&Je)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=>{!Je&&e.kind===k.audio?Je=t(F.getMicrophones(),e):!qe&&e.kind===k.video&&(qe=t(F.getCameras(),e))})}async function bt(e,t){R.debug(`Try to get media`,JSON.parse(JSON.stringify(e.getNative()))),F.releaseFirefoxMicrophonePermissionWarmup();let n=(!e.isVideo()||F.hasCameraPermission())&&(!e.isAudio()||F.hasMicrophonePermission());!n&&!t&&P.onPermissionsRequested();let r=new mt;try{r.busy();let t=await navigator.mediaDevices.getUserMedia(e.getNative());return r.free(),n||await ht(),yt(t),t}catch(n){switch(r.free(),R.error(`getUserMedia error`,n),n.name){case`PermissionDeniedError`:case`PermissionDismissedError`:case`NotAllowedError`:case`SecurityError`:case`DOMException`:case`NotFoundError`:t=e.isVideoRequested()?v.CAMERA_PERMISSION:v.MIC_PERMISSION;break;case`OverconstrainedError`:t=v.OVERCONSTRAINED;break;case`TypeError`:t=v.UNKNOWN;break;case`AbortError`:case`NotReadableError`:t=e.isVideoRequested()?v.CAMERA_ACCESS:v.MIC_ACCESS;break;case`Error`:if(n.message===`MediaSource is busy`){t=e.isVideoRequested()?v.CAMERA_ACCESS:v.MIC_ACCESS;break}}if(e.canSimplify())return bt(e.simplify(),t);let i=t||v.UNKNOWN;throw P.onPermissionsError(i,n),i}}async function xt(){if(!(tt||F.browserName()!==`Firefox`||!navigator.mediaDevices?.getUserMedia))try{F.hasMicrophonePermission()||P.onPermissionsRequested(),tt=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(e){R.warn(`Firefox microphone permission warmup failed`,e)}}async function St(e){R.debug(`Try to get screen`,JSON.parse(JSON.stringify(e.getNative())));let t=new mt;try{t.busy();let n=await navigator.mediaDevices.getDisplayMedia(e.getNative()),r=n?.getVideoTracks()[0];if(r){let t=r.getSettings()?.displaySurface;if(R.debug(`Got display media track: ${r.id} (${t})`),r.contentHint=`text`,e.captureController&&(t===`browser`||t===`window`))try{e.captureController.setFocusBehavior(`no-focus-change`)}catch(e){R.warn(`Failed to set focus behavior`,e)}}return n}catch(e){switch(e.name){case`PermissionDeniedError`:case`NotAllowedError`:case`SecurityError`:throw v.SCREEN_PERMISSION;default:throw v.SCREEN_ACCESS}}finally{t.free()}}function Ct(){return at.length||(at=(()=>{let e,t=!1,n=0,r=`0`,i=lt.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return e=/\brv[ :]+(\d+)/g.exec(lt),[`IE`,e&&e[1]||`Unknown`,t,n,r];if(i[1]===`Safari`){if(e=lt.match(/\bEdge\/(\d+)/),e)return[`Edge`,e[1]||`Unknown`,t,n,r];if(e=lt.match(/\bCriOS\/(\d+)/),e)return[`Chrome`,e[1],!0,Number(e[1]),r];if(e=lt.match(/\bFxiOS\/(\d+)/),e)return[`Firefox`,e[1],!1,n,r];if(e=lt.match(/\bYaBrowser\/(\d+)/),e)return[`Yandex`,e[1],!1,n,r];if(e=lt.match(/\bOPT\/(\d+)/),e)return[`Opera`,e[1],!1,n,r]}if(i[1]===`Chrome`){if(t=!0,n=Number(i[2]),e=lt.match(/\bOPR\/(\d+)/),e)return[`Opera`,e[1]||`Unknown`,t,n,r];if(e=lt.match(/\bYaBrowser\/(\d+)/),e)return[`Yandex`,e[1]||`Unknown`,t,n,r];if(e=lt.match(/\bSferum\/((\d+)(?:\.\d+)*)/),e)return[`Sferum`,e[1]||`Unknown`,t,n,r];if(e=lt.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=lt.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),e&&e[2]!==void 0&&(r=e[2]),[i[2]?i[1]:ct,e&&e[1]||i[2]||st,t,n,r]})()),at}var F;(function(e){async function t(){await _t(),await vt()}e.init=t;function n(){return We}e.getCameras=n;function r(){return Ge}e.getMicrophones=r;function i(){return Ke}e.getOutput=i;function a(){return We.length>0}e.hasCamera=a;function o(){return Ge.length>0}e.hasMicrophone=o;function s(){return qe}e.getSavedCamera=s;function c(){return Je}e.getSavedMicrophone=c;function l(){return Ye}e.getSavedOutput=l;function u(){return w.videoFacingMode}e.getVideoFacingMode=u;function d(){return Xe}e.hasCameraPermission=d;function f(){return Ze}e.hasMicrophonePermission=f;function p(){return Ue?.getPermissionState(`microphone`)??null}e.getMicrophonePermissionState=p;function m(e=!1){return f()?a()&&e?d():!0:!1}e.hasPermissions=m;function h(){tt&&(Ce(tt),tt=null)}e.releaseFirefoxMicrophonePermissionWarmup=h;async function ee(e=!1,t=!0,n=!0){!e&&!t?await xt():F.releaseFirefoxMicrophonePermissionWarmup();let r=o()&&t,i=a()&&e,s;if(!r&&!i)s=new MediaStream;else try{s=await bt(new ft(r,i))}catch{s=new MediaStream}return!s.getVideoTracks().length&&n&&s.addTrack(F.getBlackMediaTrack()),!s.getAudioTracks().length&&n&&s.addTrack(F.getSilentMediaTrack()),s}e.getUserMedia=ee;async function te(e,t){return St(new pt(e&&!w.consumerFastScreenShare?w.fastScreenShareWidth:window.screen.width,e&&!w.consumerFastScreenShare?w.fastScreenShareHeight:window.screen.height,w.getScreenFrameRate(e),t))}e.getScreenMedia=te;async function g(e=!1,t){return bt(new ft(!1,!0,e?w.videoEffectMaxWidth:w.videoMaxWidth,e?w.videoEffectMaxHeight:w.videoMaxHeight,t))}e._getUserVideo=g;async function _(e,t){let n=t?.width||w.videoMaxWidth,r=t?.height||w.videoMaxHeight;return bt(new ft(!1,e||!0,n,r))}e.getUserVideo=_;async function v(e){return bt(new ft(e||!0,!1))}e.getUserAudio=v;async function y(e,t){let[n]=e.getVideoTracks();if(!n)throw Error(`Video track not found in stream`);return Te(n,t)}e.setResolution=y;async function b(e,t){let n=(await _t()).find(n=>n.kind===e&&n.deviceId===t);return n?(e===`videoinput`?qe=n:e===`audioinput`?Je=n:e===`audiooutput`&&(Ye=n),Be.set(e,t),n):null}e._saveDeviceId=b;function x(){if(!et||et.readyState===`ended`){let e=F.getAudioContext(),t=e.createMediaStreamDestination(),n=e.createGain();n.gain.value=1e-5,n.connect(t),n.connect(e.destination);let r=e.createOscillator();r.type=`sine`,r.frequency.value=0,r.connect(n),r.start(),et=t.stream.getAudioTracks()[0]}return Object.assign(et.clone(),{enabled:!1})}e.getSilentMediaTrack=x;function S(e=w.videoMinWidth,t=w.videoMinHeight){$e||($e=document.createElement(`canvas`)),$e.width=e,$e.height=t;let n=$e.getContext(`2d`);return n.rect(0,0,e,t),n.fillStyle=`black`,n.fill(),(!Qe||Qe.readyState===`ended`)&&(Qe=$e.captureStream(w.videoFrameRate).getVideoTracks()[0]),Object.assign(Qe.clone(),{enabled:!1})}e.getBlackMediaTrack=S;function ne(){if(pe()===`Edge`&&Number(me())<70)return!1;try{let e=window;return`mediaDevices`in e.navigator&&`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 navigator&&!0||!1}catch{return!1}}e.isBrowserSupported=ne;function re(){return!!navigator.mediaDevices.getDisplayMedia}e.isScreenCapturingSupported=re;function ie(){let e=F.browserName()===`Safari`&&F.browserVersion()===`15`&&F.browserSubVersion()===`1`,t=F.browserName()===`Opera`,n=F.browserName()===`Yandex`;return e||t||n}e.isBrokenH264Decoder=ie;function ae(){return F.browserName()===`Yandex`&&F.os()===`Windows`||w.simulcast}e.isBrokenVP9Encoder=ae;function oe(){let e=F.browserName()===`Safari`&&Number(F.browserVersion())===17&&[4,5,6].includes(Number(F.browserSubVersion())),t=F.os()===`Windows`&&F.osVersion()===10;return e||t}e.isBrokenVP9Decoder=oe;function se(){return F.browserName()===`Firefox`&&Number(F.browserVersion())<60}e.isOldDataChannelDescription=se;function ce(){return!(F.baseChromeVersion()&&F.isMobile())}e.canPreferH264=ce;function le(){return!(F.browserName()===`Firefox`||F.browserName()===`Safari`)}e.isSimulcastSupportedByBrowser=le;function ue(){return rt||(rt=(()=>{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(lt))return t;return`Unknown`})()),rt}e.os=ue;function de(){return it}e.osVersion=de;function fe(){return nt===null&&(nt=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(st)),nt}e.isMobile=fe;function pe(){return Ct()[0]}e.browserName=pe;function me(){return Ct()[1]}e.browserVersion=me;function he(){return Ct()[3]}e.baseChromeVersion=he;function C(){return ot||(ot=new(window.AudioContext||window.webkitAudioContext)),ot.resume().catch(()=>{R.warn(`Failed to resume AudioContext`)}),ot}e.getAudioContext=C;function ge(){return Ct()[4]}e.browserSubVersion=ge;function _e(){return F.baseChromeVersion()>=105&&!F.isMobile()}e.isAudioShareSupported=_e;function ve(e,t){ut[e]||(ut[e]=[]),ut[e].push(t)}e.addEventListener=ve;function ye(e,t){if(ut[e])if(!t)delete ut[e];else{let n=ut[e].indexOf(t);n>-1&&ut[e].splice(n,1)}}e.removeEventListener=ye})(F||(F={}));var I=F,wt=class e{static get startTime(){return e._list[0]?.t||0}static get endTime(){let t=e._list;return t[t.length-1]?.t||0}static startSession(){e._list=[]}static get conversationId(){return e._conversationId}static set conversationId(t){e._conversationId=t}static add(t){e._list.push(t)}static _createContextLogs(){let e=[[`Calls SDK ${w.sdkVersion}`,w.toJSON()],[`UserAgent:`,navigator.userAgent],[`Screen resolution:`,`${window.screen.width}x${window.screen.height}`],[`Permissions:`,`Camera: ${I.hasCameraPermission()}, Mic: ${I.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:`LOG`,d:e}))}static collectLogs(){let t=e._list;return t.length===0?[]:[...e._createContextLogs(),...t]}};g(wt,`_list`,[]),g(wt,`_conversationId`,null);var Tt=class{constructor(){g(this,`_items`,[])}get length(){return this._items.length}push(...e){this._items.push(...e)}merge(e){this._items.push(...e._items)}shift(){return this._items.shift()||null}bisect(){let e=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(e)}head(){return this._items[0]||null}tail(){let e=this._items.length;return e?this._items[e-1]:null}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(e,t)=>t instanceof Error?String(t):t):``}},Et=2*1024*1024,Dt=512*1024,Ot=100*1024,kt=5,At=`_okcls_logs_session_`,jt=3e4,Mt=class{constructor(){g(this,`_items`,[]),g(this,`_itemsSize`,0),g(this,`_storageSize`,Et);try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(At)!==0)continue;let n=e.getItem(t);if(!n){Ft(t);continue}let r=Pt(n);this.add(t,r)}}catch(e){console.error(`Storage is blocked`,e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(Ot)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=Math.min(e,this._storageSize,Et)}add(e,t){let n=parseInt(e.replace(At,``),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:n})}deleteOldestItem(){let e=this._items.shift();e&&(Ft(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>Et||this.length>kt-1||this.size+e>this.available);)this.deleteOldestItem()}};function Nt(){return`${At}${Date.now()}`}function Pt(e){return new Blob([e]).size}function Ft(e){try{window.localStorage.removeItem(e)}catch(e){console.error(`Failed to remove log from storage`,e)}}function It(){let e=Ht.toString();if(!L.available||!e)return;let t=Pt(e);if(t>Dt){Ht.bisect(),It();return}L.cleanup(Ot+t);try{window.localStorage.setItem(Ut,e)}catch(e){if(console.warn(`Failed to write log to storage`,e),L.storageSize=L.size+t,L.cleanup(Ot+t),L.available>=Ot+t){It();return}if(t>Ot){Ht.bisect(),It();return}L.storageSize=0;return}t>Dt&&(L.add(Ut,t),Ut=Nt(),Ht.clear(),L.cleanup(Ot))}function Lt(){!L.available||!Ht.length||It()}function Rt(e=!1){let t=[];try{let e=window.localStorage;for(let n of L.items){let r=e.getItem(n.key);t.push(r)}let n=Ht.toString();n&&t.push(n)}catch(e){console.error(`Storage is blocked`,e)}let n=`[${t.join(`,`)}]`;if(e)return n;let r=`logs_${Date.now()}.json`;return zt(n,r),r}function zt(e,t){let n=document.createElement(`a`),r=new Blob([e],{type:`text/json`});n.href=URL.createObjectURL(r),n.download=t,n.click()}function Bt(e,t){if(!L.available)return;let n=new Date,r={t:n.getTime(),l:e,d:t,h:n.toLocaleString(`ru-RU`,{dateStyle:`short`,timeStyle:`long`})};Ht.push(r),wt.add(r),Wt||(Wt=window.setTimeout(()=>{Wt=null,Lt()},jt))}function Vt(){L||(L=new Mt,Ht=new Tt,Ut=Nt(),window.addEventListener(`beforeunload`,Lt))}var L,Ht,Ut,Wt=null;window.__VKCallsSDKLogs__=(e=!1)=>(L||Vt(),Lt(),Rt(e));var Gt=function(e){return e.DEBUG=`DEBUG`,e.LOG=`LOG`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),Kt;(function(e){let t=`📞`,n=(e,...t)=>{P.onDebugMessage(e,...t)},r=!1,i=(e,t)=>(...n)=>{e(...n),Bt(t,n)},a=console.debug.bind(console,t),o=console.log.bind(console,t),s=console.warn.bind(console,t),c=console.error.bind(console,t),l=n.bind(null,`DEBUG`),u=n.bind(null,`LOG`),d=n.bind(null,`WARN`),f=n.bind(null,`ERROR`),p=l,m=u,h=d,ee=f;function te(...e){p(...e)}e.debug=te;function g(...e){m(...e)}e.log=g;function _(...e){h(...e)}e.warn=_;function v(...e){ee(...e)}e.error=v;function y(){return r}e.enabled=y;function b(e){r=e,w.debugLog&&Vt(),e?(p=w.debugLog?i(a,`DEBUG`):a,m=w.debugLog?i(o,`LOG`):o,h=w.debugLog?i(s,`WARN`):s,ee=w.debugLog?i(c,`ERROR`):c):(p=w.debugLog?i(l,`DEBUG`):l,m=w.debugLog?i(u,`LOG`):u,h=w.debugLog?i(d,`WARN`):d,ee=w.debugLog?i(f,`ERROR`):f)}e.toggle=b;function x(e,...t){switch(e){case`DEBUG`:te(...t);break;case`LOG`:g(...t);break;case`WARN`:_(...t);break;case`ERROR`:v(...t);break}}e.send=x;function S(e,...t){}e.test=S})(Kt||(Kt={}));var R=Kt,z=new class{constructor(){g(this,`_conversations`,new Map),g(this,`_activeId`,null),g(this,`_mutex`,!1)}add(e){if(this._conversations.has(e.id))throw Error(`CallRegistry: conversation ${e.id} already exists`);this._conversations.set(e.id,e)}remove(e){e&&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}getActiveId(){return this._activeId}has(e){return this._conversations.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();if(t)try{await t.hold(!0)}catch(e){throw R.error(`Can't hold previous active, error: ${e}`),Error(`Cannot switch call: hold failed`)}this._activeId=e,P.onCallActive(e);let n=this._conversations.get(e);if(n&&n?.isCallHeld)try{await n.hold(!1)}catch(e){throw R.error(`Can't hold next active, error: ${e}`),Error(`Cannot switch call: hold failed`)}}finally{this._mutex=!1}}}clear(){this._conversations.clear(),this._activeId=null}},qt=class extends _{constructor(...e){super(...e),g(this,`_abortSignal`,void 0)}setAbortSignal(e){this._abortSignal=e}get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setWebTransportEndpoint(e){}setConversationId(e){}readyToSend(e=!0){}cleanup(){}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 Jt(e){return e.stopStream}function Yt(e){return e.keyFrameRequested}function Xt(e){if(Jt(e))return`ss`;if(Yt(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}({}),Zt=`s`,Qt=`m`;function $t(e){return e.participantId+(e.mediaType?`:`+Zt+e.mediaType:``)+(e.streamName?`:`+Qt+e.streamName:``)}function en(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 Zt:r=tn(n.slice(1));break;case Qt: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:C.compose(n,a),mediaType:r,streamName:i}}function tn(e){for(let t of Object.keys(V))if(t===e)return V[t];return null}function nn(){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 an(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 on=0,sn=1,cn=2,ln=3,un=4,dn=5,fn=6,pn=7,mn=0,hn=1,gn=2,_n=0,vn=0,yn=0,bn=1,xn=class{constructor(){g(this,`participantIdRegistry`,null)}setParticipantIdRegistry(e){this.participantIdRegistry=e}serializeUpdateDisplayLayout(e,t){let n=nn();l.Int.enc(n,on),l.Int.enc(n,_n),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=nn();if(this.writeStreamDesc(t,i),Jt(r))l.Int.enc(i,hn);else if(Yt(r))l.Int.enc(i,gn);else if(l.Int.enc(i,mn),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,yn);break;case`cn`:l.Int.enc(i,bn);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=nn();return l.Int.enc(n,sn),l.Int.enc(n,_n),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=nn();return l.Int.enc(n,cn),l.Int.enc(n,_n),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=nn();return l.Int.enc(n,ln),l.Int.enc(n,_n),l.Int.enc(n,e),l.Bool.enc(n,t.request),n.ui8array().buffer}serializeNetworkStatReport(e,t){let n=nn();return l.Int.enc(n,un),l.Int.enc(n,_n),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=nn();return l.Int.enc(n,dn),l.Int.enc(n,_n),l.Int.enc(n,e),l.Bool.enc(n,t.enabled),n.ui8array().buffer}serializeEnableVideoSuspendSuggest(e,t){let n=nn();return l.Int.enc(n,fn),l.Int.enc(n,_n),l.Int.enc(n,e),l.Bool.enc(n,t.enabled),n.ui8array().buffer}serializeChangeSimulcast(e,t){let n=nn();l.Int.enc(n,pn),l.Int.enc(n,_n),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?an(`arrayBuffer`in Blob.prototype?await e.arrayBuffer():await de(e)):an(e);let n=l.Int.dec(t),r=l.Int.dec(t);if(r!==_n){R.warn(`Unsupported version for command type: `+n+`, version `+r);return}if(l.Int.dec(t)!==vn){R.warn(`Error code: `+n+`received for command type: `+n+`, version `+r);return}switch(n){case on:return this.deserializeUpdateDisplayLayoutResponse(t);case sn:return this.deserializeReportPerfStatResponse(t);default:R.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=an(e),n=l.Any.dec(t);if(typeof n==`string`)r[n]=l.Int.dec(t);else{let e=n,i=$t(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_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.CALL_START=`call_start`,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}(H||{}),Sn=1e3;function U(e,t,n=0){return t in e&&e[t]?e[t]:n}function Cn(...e){return t=>{for(let n of e)if(n(t))return!0;return!1}}function wn(e,t){return n=>n[e]===t}function Tn(e){return(t,n)=>n[e]-t[e]}function En(e,t){return t.reduce((t,n)=>(t[n[e]]=n,t),{})}function Dn(e){let t={},n=[];for(let r of e)t[r.id]||(t[r.id]=!0,n.push(r));return n}function On(e){return Object.keys(e).filter(t=>e[t]!==void 0).map(t=>[t,e[t]]).reduce((e,t)=>(e[t[0]]=C.isObject(t[1])?On(t[1]):t[1],e),{})}function kn(e){let t=[];for(let n of e)n.forEach(e=>t.push(e));return t}async function An(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(kn).then(Dn)}function jn(e){let t=e.filter(wn(`type`,`candidate-pair`)).sort(Tn(`priority`)).find(Cn(wn(`nominated`,!0),wn(`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(wn(`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(wn(`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}}),On(n)}function Mn(e,t,n=!1){let r=En(`id`,e),i=n?e.filter(Cn(wn(`type`,`remote-inbound-rtp`))):e.filter(Cn(wn(`type`,`inbound-rtp`),wn(`type`,`outbound-rtp`)));return I.browserName()===`Firefox`&&(i=Object.values(i.reduce((e,t)=>{if(!e[t.ssrc])e[t.ssrc]=t;else{let n=Object.assign({},e[t.ssrc],t),r=e[t.ssrc].isRemote?t:e[t.ssrc];n.id=r.id,n.type=r.type,delete n.isRemote,delete n.remoteId,e[n.ssrc]=n}return e},{}))),i.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 On(c)}).filter(e=>!!e)}function Nn(e,t,n=!1){if(!t||!t.rtps||!e.rtps)return e;let r,i;n&&(r=En(`ssrc`,e?.remoteRtps||[]),i=En(`ssrc`,t?.remoteRtps||[]));let a=En(`ssrc`,e.rtps),o=En(`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 Pn(e,t,n={},r=!1){let i=await An(e),a={timestamp:Date.now(),transport:jn(i),rtps:Mn(i,n)};return r&&(a.remoteRtps=Mn(i,n,!0)),t?Nn(a,t,r):(await C.delay(Sn),Pn(e,a,n,r))}function Fn(e){performance.clearMarks(e),performance.mark(e)}function In(e){performance.clearMarks(e)}function Ln(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 Rn(e){return`${H.SCREENSHARE_FIRST_FRAME}_${zn(e)}`}function zn(e){return typeof e==`string`?e:JSON.stringify(e)}var W={distinctById:Dn,rtcStatsToArray:kn,extractTransport:jn,extractRtps:Mn,delta:Nn,collectStats:Pn,setMark:Fn,clearMark:In,measureMark:Ln,getMarkNameScreenshareFirstFrame:Rn},Bn=class e{constructor(){g(this,`_eventualLogs`,new Set)}static create(){e._instance=new e}static logCallStat(t){if(e._instance?._eventualLogs.size){for(let n of e._instance._eventualLogs)Object.assign(n,{call_topology:t.call_topology,local_address:t.local_address,local_connection_type:t.local_connection_type,network_type:t.network_type,remote_address:t.remote_address,remote_connection_type:t.remote_connection_type,transport:t.transport}),O.logClientStats(n);e._instance._eventualLogs.clear()}O.logClientStats(t)}static logEventualStat(t){t.value===void 0&&(t.value=W.measureMark(t.name)),t.value!==null&&e._instance?._eventualLogs.add(t)}static destroy(){e._instance?._destroy(),e._instance=null}_destroy(){this._eventualLogs.clear()}};g(Bn,`_instance`,null);var Vn=function(e){return e.WEBSOCKET=`ws`,e.WEBTRANSPORT=`wt`,e}({}),Hn=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}({}),Un={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}},Wn=class{constructor(e){if(g(this,`q`,void 0),g(this,`inits`,[]),g(this,`n`,[1,2,3,4,5]),g(this,`np`,[1,1,1,1,1]),g(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]}},Gn=class{constructor(){g(this,`n`,0),g(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}},Kn=class{constructor(){g(this,`count`,0),g(this,`minVal`,1/0),g(this,`maxVal`,-1/0),g(this,`mean`,new Gn),g(this,`p50`,new Wn(.5)),g(this,`p95`,new Wn(.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}},qn=function(e){return e.NOTIFICATION=`NOTIFICATION`,e.FAILED=`FAILED`,e.RECONNECT=`RECONNECT`,e}(qn||{}),G=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.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}(G||{}),Jn=function(e){return e.producerNotification=`producerNotification`,e.producerCommand=`producerCommand`,e.consumerScreenShare=`consumerScreenShare`,e.producerScreenShare=`producerScreenShare`,e.asr=`asr`,e.animoji=`animoji`,e}(Jn||{}),{isObject:Yn,isObjectsEquals:Xn}=C;function Zn(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||Yn(e.bitrates)&&Yn(t.bitrates)&&!Xn(e.bitrates,t.bitrates,!0)?!1:e.bitrates===t.bitrates}var Qn=function(e){return e.L1T1=`L1T1`,e.L1T2=`L1T2`,e.L1T3=`L1T3`,e}({});function $n(e,t){return!(!Zn(e.camera,t.camera)||!Zn(e.screenSharing,t.screenSharing)||!Zn(e.fastScreenSharing,t.fastScreenSharing))}function er(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 tr(){return{camera:null,screenSharing:null,fastScreenSharing:null}}var nr=class e{constructor(){g(this,`_codecUsages`,new Map),g(this,`getCurrentTransportTopology`,()=>void 0)}static create(t){let n=new e;n.getCurrentTransportTopology=t,e._instance=n}static reportUsage(t){let n=e._instance,r=n?.getCurrentTransportTopology();if(!n||!r)return;let i=t.rtps.filter(e=>e.type===`outbound-rtp`&&!e.mid?.endsWith(`s`));w.simulcast&&(i=i.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},[])),i.forEach(e=>{let t=e.kind,i=e.mimeType;if((t===`audio`||t===`video`)&&i){let a=[i,`encoder`,e.encoderImplementation].filter(Boolean).join(`/`);n.saveUsage({kind:t,codecName:a,totalEncodeTime:(e.totalEncodeTime??0)*1e3,audioCodecParams:e.sdpFmtpLine,topology:r})}})}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:e.totalEncodeTime,call_topology:e.topology===J.DIRECT?`D`:`S`};e.audioCodecParams&&(t.string_value=e.audioCodecParams),O.logClientStats(t)}static destroy(){e._instance?._destroy(),e._instance=null}_destroy(){this._codecUsages.forEach(e=>{this.report(e)}),this._codecUsages.clear()}};g(nr,`_instance`,null);var rr=class extends _{constructor(e,t){super(),g(this,`_signaling`,void 0),g(this,`_mediaSource`,void 0),g(this,`_state`,q.IDLE),g(this,`_pc`,null),this._signaling=e,this._mediaSource=t}getState(){return this._state||q.IDLE}},ir=`videochat-epi`,ar=5e3,or=500,sr=class extends _{constructor(e,t,n=!1){super(),g(this,`_previousPerfStatReportTimestamp`,0),g(this,`_previousNetworkStatReportTimestamp`,Date.now()),g(this,`_previousCallStatReportTimestamp`,Date.now()),g(this,`_previousCallStatReport`,null),g(this,`_screenShareStats`,[]),g(this,`_signaling`,void 0),g(this,`_directTopology`,void 0),g(this,`_handleScreenSharingStat`,e=>{this._screenShareStats.push(e)}),g(this,`_handleTransportStateChanged`,e=>{(this._directTopology&&e===q.CONNECTED||!this._directTopology&&e===q.OPENED)&&(this._previousNetworkStatReportTimestamp=Date.now(),this._previousCallStatReportTimestamp=Date.now())}),this._signaling=t,this._directTopology=n,this.subscribe(e,K.REMOTE_DATA_STATS,this._handleStats.bind(this)),this.subscribe(e,K.SCREEN_SHARING_STAT,this._handleScreenSharingStat.bind(this)),this.subscribe(e,K.STATE_CHANGED,this._handleTransportStateChanged.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(ir)||``,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&&w.perfStatReportEnabled&&this._previousPerfStatReportTimestamp+ar<=t&&(await this.reportPerfStats(e),this._previousPerfStatReportTimestamp=t);let n=e.outbound.transport.local?.protocol===`tcp`;!this._directTopology&&n&&this._previousNetworkStatReportTimestamp+or<=t&&(await this.reportNetworkStats(e),this._previousNetworkStatReportTimestamp=t),w.callStatReportEnabled&&this._previousCallStatReportTimestamp+w.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(ir,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,packets_lost_video:0,packets_sent_video:0,packets_lost_audio:0,packets_sent_audio: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:lr(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:lr(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.packets_sent_video+=t.packetsSent):e.packets_sent_audio+=t.packetsSent,e),t),e.remoteInbound.rtps.reduce((e,t)=>(t.kind===`video`?e.packets_lost_video+=t.packetsLost:e.packets_lost_audio+=t.packetsLost,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(w.simulcast&&(i.is_simulcast=!0),navigator.hardwareConcurrency&&(i.cpu_hardware_concurrency=navigator.hardwareConcurrency),n&&!ur(t.jitter_video)&&(i.jitter_video=Math.round(t.jitter_video)),r&&!ur(t.jitter_audio)&&(i.jitter_audio=Math.round(t.jitter_audio)),n&&!ur(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&&!ur(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=dr(n/e*1e3),i.removed_audio_samples_for_acceleration=dr(r/e*1e3),i.concealed_audio_samples=dr(a/e*1e3),i.concealed_silent_audio_samples=dr(o/e*1e3),i.concealment_audio_avg_size=dr(a/s),i.total_audio_energy=t.total_audio_energy}cr(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),cr(t,`remote_address`,`remote_connection_type`)&&(i.remote_address=t.remote_address,i.remote_connection_type=t.remote_connection_type);let a=Math.max(0,t.packets_sent_video-this._previousCallStatReport.packets_sent_video),o=Math.max(0,t.packets_sent_audio-this._previousCallStatReport.packets_sent_audio);a>0&&(i.video_loss=dr(Math.max(0,t.packets_lost_video-this._previousCallStatReport.packets_lost_video)/a*100)),o>0&&(i.audio_loss=dr(Math.max(0,t.packets_lost_audio-this._previousCallStatReport.packets_lost_audio)/o*100)),Bn.logCallStat(i),w.enableLogPerfStatReport&&R.log(`Sent call stats`,i),this._previousCallStatReport=t}};function cr(e,...t){for(let n of t)if(!Object.hasOwn(e,n)||e[n]===void 0)return!1;return!0}function lr(e,t=!1){if(e?.address)return e.address+(t?`:${e.port}`:``)}function ur(e){return e===void 0}function dr(e){return Number.isNaN(e)?0:e}var fr=class{constructor(e,t=null){g(this,`weightUp`,void 0),g(this,`weightDown`,void 0),g(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}},pr=.25,mr=.35,hr=85,gr=.1,_r=1.5,vr=.1,yr=1,br=.6,xr=.3,Sr=class extends _{constructor(e){super(),g(this,`_signaling`,void 0),g(this,`_localNetworkStat`,void 0),g(this,`_remoteNetworkStat`,void 0),g(this,`_lastNetworkStat`,void 0),g(this,`_networkLimits`,{badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}}),g(this,`_lastStatSentTimestamp`,0),g(this,`_currentState`,`good`),this._signaling=e,this._localNetworkStat={rtt:new fr(pr,pr),loss:new fr(mr,mr),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)/hr);for(let e=0;e<r;e++)n*=1-gr;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)/_r);for(let e=0;e<r;e++)n*=1-vr;return n}_calcBitrateRating(e,t){if(!e||!t)return 1;let n=1-(1-Math.min(e,t)/Math.max(e,t))*yr;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>=br?`good`:e>=xr?`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>w.networkStatisticsInterval)&&(this._lastStatSentTimestamp=a,this._signaling.customData({sdk:Object.assign({type:`bad-net`},i)},null).catch(e=>{R.warn(`Unable to send [bad-net]`,e)})),this._currentState=c,this._triggerEvent(K.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}},Cr=30*1e3,wr=class e extends rr{constructor(e,t,n,r,i){super(n,r),g(this,`_participantId`,void 0),g(this,`_isMaster`,void 0),g(this,`_remoteSDP`,{}),g(this,`_remoteCandidates`,{}),g(this,`_lastRemoteSDP`,null),g(this,`_animojiDataChannel`,null),g(this,`_animojiReceiver`,null),g(this,`_animojiSender`,null),g(this,`_remoteAnimojiVersion`,1),g(this,`_isOpen`,!1),g(this,`_remotePeerId`,null),g(this,`_statInterval`,null),g(this,`_settingsInterval`,null),g(this,`_failedOnCreate`,null),g(this,`_remoteStream`,null),g(this,`_iceRestartTimeout`,null),g(this,`_reconnectionTimeout`,null),g(this,`_reconnectionPrevented`,!1),g(this,`_lastStat`,void 0),g(this,`_fingerprint`,null),g(this,`_neverConnected`,!0),g(this,`_serverSettings`,void 0),g(this,`_prevConsumerSettings`,{}),g(this,`_networkLimitsForVideo`,{bad:{loss:4,rtt:1e3},good:{loss:2,rtt:700}}),g(this,`_videoMaxDimensionsForNet`,{worst:320,bad:640,good:1280}),g(this,`_lastVideoMaxDimension`,this._videoMaxDimensionsForNet.good),g(this,`_lastBadConnection`,0),g(this,`_perfStatReporter`,void 0),g(this,`_directStatReporter`,void 0),this._participantId=e,this._isMaster=t,this._serverSettings=i,this._perfStatReporter=new sr(this,n,!0),this._directStatReporter=new Sr(n),this.subscribe(this._signaling,qn.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Oe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Oe.SOURCE_CHANGED,this._applySettings.bind(this)),this.subscribe(this._directStatReporter,K.NETWORK_STATUS,this._onNetworkStatus.bind(this));try{this._pc=new RTCPeerConnection({iceServers:w.iceServers,iceTransportPolicy:w.forceRelayPolicy?`relay`:`all`})}catch(e){R.error(`Failed to create RTCPeerConnection:`,e),this.close(e);return}if(this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},w.vmoji&&this._createDataChannel(this._pc,Jn.animoji,e=>{this._animojiDataChannel=e,this._animojiDataChannel.binaryType=`arraybuffer`,this._animojiReceiver?.setDataChannel(this._animojiDataChannel),this._animojiSender?.setDataChannel(this._animojiDataChannel)}),this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(e){O.log(b.ERROR,`addTrack-direct`),R.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[q.IDLE,q.CLOSED,q.FAILED].includes(this.getState())}async open(e=null){if(this._isOpen){R.warn(`DirectTransport: Already opened`,{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(R.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){O.log(b.ERROR,`addTrack-direct`),R.error(`DirectTransport: Unable to add media source tracks`,e,{participantId:this._participantId}),this.close(e);return}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){$n(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}setAnimojiTransport(e,t){if(w.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._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(e=>{e.stop(),this._triggerEvent(K.REMOTE_TRACK_REMOVED,this._remoteStream,e)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._animojiDataChannel&&(this._animojiDataChannel.onopen=null,this._animojiDataChannel.onmessage=null,this._animojiDataChannel.onerror=null,this._animojiDataChannel.close()),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),this._onNetworkStatus(1),this.unsubscribe(),e?(R.error(`DirectTransport: Closed`,e,{participantId:this._participantId}),this._setState(q.FAILED)):(R.debug(`DirectTransport: Closed`,{participantId:this._participantId}),this._setState(q.CLOSED)),this._triggerEvent(K.PEER_CONNECTION_CLOSED))}_setState(e){this._state!==e&&(R.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(K.STATE_CHANGED,e))}_onSignalingNotification(e){switch(e.notification){case G.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case G.SETTINGS_UPDATE:this._directStatReporter.updateSettings(e.settings);break;case G.CUSTOM_DATA:Object.hasOwn(e.data,`sdk`)&&this._directStatReporter.reportRemote(e.data?.sdk);break}}_handleTransmittedData(e){let t=e.data,n=C.getPeerIdString(e.peerId);C.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){R.debug(`Add remote ice candidate`,{participantId:this._participantId,candidate:t});try{await this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(e){throw O.log(b.ERROR,`addIceCandidate-direct`),R.error(`Unable to add remote ice candidate`,e,{participantId:this._participantId,candidate:t}),e}}else R.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]){R.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),R.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 O.log(b.ERROR,`setRemoteDescription-direct`),R.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,w.vmojiOptions?.protocolVersion||1);this._animojiSender?.setProtocolVersion(t)}_onAddTrack(e){R.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(K.REMOTE_TRACK_REMOVED,this._remoteStream,e.track)}),this._triggerEvent(K.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}async _handleIceCandidate(e){e.candidate&&this._signaling.ready&&(R.debug(`Local ice candidate`,{participantId:this._participantId,candidate:e.candidate}),await this._signaling.sendCandidate(this._participantId,e.candidate))}_onSignalingStateChange(){R.debug(`DirectTransport: Signaling state changed to ${this._pc?.signalingState}`,{participantId:this._participantId});let e={animojiVersion:w.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(R.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`:I.browserName()===`Safari`&&this._pc?.connectionState!==`connected`&&this._markConnected();break}}_markConnected(){this._neverConnected=!1,this._setState(q.CONNECTED),this._stopReconnection(),this._pc&&C.getPeerConnectionHostInfo(this._pc).then(e=>{e?.local&&(O.log(b.ICE_CONNECTION_TYPE,e.local.type),R.debug(`Selected ICE candidates`,e))}),this._startStatInterval()}_onConnectionStateChange(){switch(R.debug(`DirectTransport: Connection state changed to ${this._pc?.connectionState}`,{participantId:this._participantId}),O.log(b.ICE_CONNECTION_STATE,this._pc?.connectionState),this._pc?.connectionState){case`connected`:this._markConnected();break;case`failed`:case`disconnected`:this._reconnectionPrevented?this.close(Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(q.RECONNECTING),this._startReconnection());break;case`closed`:this.close(Error(`Ice connection closed`));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(R.log(`Waiting for reconnection...`,{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},w.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(R.log(`Switch topology DIRECT to SERVER`,{participantId:this._participantId}),this._signaling.switchTopology(J.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(O.log(b.ICE_RESTART),R.log(`Ice restart`,{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):R.debug(`Waiting for ice restart...`,{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,R.error(`Ice restart failed`,{participantId:this._participantId}),O.log(b.ERROR,`iceRestart-direct`),this._requestTopologySwitch()},w.iceRestartWaitTime)}async _createOffer(t){let n={iceRestart:t,offerToReceiveAudio:!0,offerToReceiveVideo:!0};R.debug(`Create offer`,{participantId:this._participantId,options:n});let r;try{r=await this._pc?.createOffer(n),R.debug(`Created offer`,{participantId:this._participantId,offer:r}),r=e._patchLocalDescription(r)}catch(e){throw R.error(`Unable to create offer`,e,{participantId:this._participantId}),O.log(b.ERROR,`createOffer-direct`),e}try{return R.debug(`Set local description`,{participantId:this._participantId,offer:r}),this._calcFingerprint(r.sdp),await this._pc?.setLocalDescription(r),r}catch(e){throw R.error(`Unable to set local description`,e,{participantId:this._participantId}),O.log(b.ERROR,`setLocalDescription-direct`),e}}async _createAnswer(){R.debug(`Create answer`,{participantId:this._participantId});let t;try{t=await this._pc?.createAnswer(),R.debug(`Created answer`,{participantId:this._participantId,answer:t}),t=e._patchLocalDescription(t)}catch(e){throw R.error(`Unable to create answer`,e,{participantId:this._participantId}),O.log(b.ERROR,`createAnswer-direct`),e}try{return R.debug(`Set local description`,{participantId:this._participantId,answer:t}),this._calcFingerprint(t.sdp),await this._pc?.setLocalDescription(t),t}catch(e){throw R.error(`Unable to set local description`,e,{participantId:this._participantId}),O.log(b.ERROR,`setLocalDescription-direct`),e}}static _patchLocalDescription(e){let t=!!I.baseChromeVersion();return e.sdp=C.patchLocalSDP(e.sdp,w.preferH264&&I.canPreferH264(),I.isBrokenH264Decoder(),w.preferVP9,t&&w.audioNack),e}static _patchRemoteDescription(e){return e.sdp=C.patchRemoteSDP(e.sdp,!1,!1,!1,w.preferVP9,I.isBrokenVP9Encoder(),I.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=>{R.error(`DirectTransport: Unable to replace track`,e,{participantId:this._participantId}),O.log(b.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,nr.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(K.REMOTE_DATA_STATS,n),this._statInterval=window.setTimeout(e,w.statisticsInterval)})};this._statInterval=window.setTimeout(e,w.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:I.browserName()===`Firefox`?`transmission`:`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 R.warn(`Failed to get encodingInfo`,a,e),!1}}async _checkPPTNetwork(e){if(!w.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=Qn.L1T1;if(r?(this._lastBadConnection=Date.now(),i?(a=this._videoMaxDimensionsForNet.bad,o=Qn.L1T2):(a=this._videoMaxDimensionsForNet.worst,o=Qn.L1T3)):n&&(a=this._videoMaxDimensionsForNet.good,o=Qn.L1T1),!(a<this._lastVideoMaxDimension||Date.now()-this._lastBadConnection>Cr)||this._lastVideoMaxDimension===a)return;let s=this._serverSettings.camera;if(!s||!await this._isSVCSupported(e,o))return;R.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(K.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=C.sdpFingerprint(e);if(t===null){R.warn(`Fingerprint calculation is unsupported`);return}this._fingerprint===null?this._fingerprint=t:(P.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=C.applySettings(this._pc,e,this._prevConsumerSettings))}_createDataChannel(e,t,n){R.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{negotiated:!0,id:1});r.onopen=()=>{let e=r.readyState;e===`open`?(R.debug(`[${t}] data channel opened`),r.onerror=e=>{R.error(`[${t}] data channel error`,e)},n(r)):R.error(`[${t}] data channel open failed, state [${e}]`)}}},Tr=function(e){return e.AUDIO_MIX=`audio-mix`,e.PARTICIPANT_AGNOSTIC_TRACK_PREFIX=`pat`,e.TRANSPARENT_AUDIO_TRACK_PREFIX=`ta`,e}({}),Er;(function(e){function t(){return{estimatedPerformanceIndex:sr.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:8,producerCommandDataChannelVersion:3,consumerScreenDataChannelVersion:1,producerScreenDataChannelVersion:1,asrDataChannelVersion:+!!w.asrDataChannel,animojiDataChannelVersion:w.vmoji?w.vmojiOptions.protocolVersion:1,animojiBackendRender:!w.vmojiOptions.renderingOptions.useFullClientRendering,onDemandTracks:!0,unifiedPlan:!0,singleSession:!0,videoTracksCount:w.videoTracksCount,red:!0,audioShare:w.audioShare,fastScreenShare:w.fastScreenShare,videoSuspend:w.videoSuspend,simulcast:w.simulcast,consumerFastScreenShare:w.consumerFastScreenShare,consumerFastScreenShareQualityOnDemand:w.consumerFastScreenShareQualityOnDemand,transparentAudio:w.transparentAudio}}e.get=t})(Er||(Er={}));var Dr=Er,Or=16,kr=class e{constructor(e,t,n){g(this,`_datachannel`,void 0),g(this,`_participantIdRegistry`,void 0),g(this,`_asrCallback`,void 0),g(this,`_textDecoder`,void 0),R.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(Or)}}_onDataChannelMessage(t){let n=e.parse(t),r=this._participantIdRegistry?.getStreamDescription(n.ssrc)?.participantId;if(!r){R.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}},Ar,jr=class{constructor(){g(this,`_value`,1)}get value(){return this._value}set value(e){this._value=e}};Ar=jr,g(jr,`_instance`,null),g(jr,`getInstance`,()=>(Ar._instance||(Ar._instance=new Ar),Ar._instance));var Mr=class{constructor(){g(this,`streamDescriptionByCompactId`,new Map),g(this,`compactIdByStreamDescription`,new Map)}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=en(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:G.AUDIO_ACTIVITY,activeParticipants:i}:{type:`notification`,notification:G.STALLED_ACTIVITY,stalledParticipants:i};case 3:let a=(0,l.decode)(r);return{type:`notification`,notification:G.SPEAKER_CHANGED,speaker:this.getStreamDescription(a)?.participantId};case 5:let o=(0,l.decode)(r);return{type:`notification`,notification:G.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:G.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:G.MOVIE_UPDATE_NOTIFICATION,data:e}}case 9:let u=(0,l.decode)(r);return{type:`notification`,notification:G.VIDEO_SUSPEND_SUGGEST,bandwidth:u};default:return R.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){R.error(`could not uncompress participant ID ${t}`);continue}}else c=null;if(a===null){R.error(`unexpected null sequenceNumber`,e,r);continue}let l=Tr.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:G.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:n}}},Nr=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}({}),Pr=class{constructor(){g(this,`_worker`,null)}async _createWorker(e,t,n=[],r={},i=[]){return new Promise((a,o)=>{let s=n.join(`,`),c=new Blob([e,`exports.default(${s});`],{type:`application/javascript; charset=utf-8`}),l=window.URL.createObjectURL(c);this._worker=new Worker(l),this._worker.onmessage=e=>{switch(e.data.type){case Nr.READY:a();break;case Nr.ERROR:o(e.data.error);break;case Nr.FRAME:t(e.data);break;case Nr.DEBUG:R.debug(e.data.message);break;case Nr.LOG_ERROR:O.log(b.ERROR,e.data.message);break}},this._sendToWorker(Nr.INIT,r,i)})}_removeWorker(){this._worker?.terminate(),this._worker=null}_sendToWorker(e,t={},n=[]){this._worker?.postMessage(Object.assign({type:e},t),n)}static isBrowserSupported(){throw Error(`Not implemented`)}},Fr=class extends Pr{async init(e,t,n){R.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?(R.warn(`LibVPxDecoder`,r.error),t(r.error)):r.requestKeyFrame?(R.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(Nr.FRAME,{timestamp:e,data:t.buffer,isVP9:n,keyFrame:r,debug:R.enabled()},[t.buffer])}destroy(){this._removeWorker(),R.debug(`LibVPxDecoder destroyed`)}static isBrowserSupported(){return`WebAssembly`in window&&`Worker`in window}},Ir=class extends Pr{async init(e,t,n){R.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(){self.postMessage({type:t.READY})}function d(e,n,r,i=!1){c={timestamp:e,data:n,isVP9:r,keyFrame:i};let a=p(r);if(o&&!i){self.postMessage({type:t.FRAME,error:`WebCodecsDecoder waiting for keyframe`}),f();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});try{a.decode(l)}catch(e){m(`because failed call decode: ${e.message}`);return}h(i)}self.onmessage=e=>{switch(e.data.type){case t.INIT:u();break;case t.FRAME:d(e.data.timestamp,e.data.data,e.data.isVP9,e.data.keyFrame);break}};function f(){s||(self.postMessage({type:t.FRAME,requestKeyFrame:!0}),s=!0)}function p(e){return a!==e&&(a=e,m(`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=>{g();let r=n?[e]:[];self.postMessage({type:t.FRAME,data:e},r),e.close()},error:e=>{g(),m(`because error during decoding: ${e.message}`),i===`prefer-software`?self.postMessage({type:t.FRAME,error:`WebCodecsDecoder failed, reinitialize: `+String(e)}):(i=`prefer-software`,c&&c.keyFrame&&d(c.timestamp,c.data,c.isVP9,c.keyFrame),self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec switch to prefer-software because decoding issue: ${e.message}`}))}}),r.configure(_(a,i))),r}function m(e){if(r){try{r&&r.state!==`closed`&&r.close()}catch{}r=null,self.postMessage({type:t.FRAME,error:`WebCodecsDecoder reset ${e}`})}}function h(e=!1){l=setTimeout(()=>{m(`because of decode timeout`)},3e3)}function g(){l&&clearTimeout(l),l=null}function _(t,n){return{codec:t?e.VP9:e.VP8,hardwareAcceleration:n}}}})(),exports={default:workerExports};",r=>{r.error?(R.warn(`WebCodecsDecoder`,r.error),t(r.error)):r.requestKeyFrame?(R.debug(`WebCodecsDecoder requests key frame`),n()):(e(r.data),r.data.close())},[I.baseChromeVersion()>=92||I.browserName()===`Safari`])}decodeFrame(e,t,n,r=!1){this._sendToWorker(Nr.FRAME,{timestamp:e,data:t.buffer,isVP9:n,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),R.debug(`WebCodecsDecoder destroyed`)}static isBrowserSupported(){return`VideoDecoder`in window&&`Worker`in window&&`VideoFrame`in window&&!I.isBrokenVP9Decoder()&&I.browserName()!==`Firefox`}},Lr=class{constructor(e=null,t=0){g(this,`_counter`,0),g(this,`_interval`,0),g(this,`_lastCalculationTime`,Date.now()),g(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}},Rr=class{constructor(e){g(this,`_participantId`,void 0),g(this,`_firstFrameReceived`,!1),this._participantId=e}measure(e,t){if(this._firstFrameReceived)return;this._firstFrameReceived=!0;let n=W.getMarkNameScreenshareFirstFrame(this._participantId),r=W.measureMark(n);r!==null&&Bn.logEventualStat({name:H.SCREENSHARE_FIRST_FRAME,value:r,width:e,height:t})}},zr=65536,Br=`MARK_SCREENSHARE_FREEZE_DURATION`,Vr=class e{constructor(e,t,n,r){g(this,`_participantId`,void 0),g(this,`_onStream`,void 0),g(this,`_onStat`,void 0),g(this,`_onKeyFrameRequested`,void 0),g(this,`_statScreenShareFirstFrame`,void 0),g(this,`_chunks`,[]),this._participantId=e,this._onStream=t,this._onStat=n,this._onKeyFrameRequested=r,this._statScreenShareFirstFrame=new Rr(e)}appendChunk(t){let n=this._chunks.length;if(t.start)this._measureFreezeDuration(!1),this._measureFreezeDuration(!0),n&&(R.warn(`[FrameBuilder] Cleanup buffer`,Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!n||(this._chunks[n-1].sequence+1)%zr!==t.sequence){R.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(Br),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(Br);return}let t=W.measureMark(Br);t!==null&&t>1e3&&this._onStat({freeze_duration:t})}},Hr=class{constructor(e){g(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")}},Ur=class extends Hr{constructor(e){super(e),g(this,`_useImageBitmap`,void 0),g(this,`_canvas`,null),g(this,`_canvasContext`,null),g(this,`_stream`,null),g(this,`_track`,null),R.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){R.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){R.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(),R.debug(`CanvasRenderer destroyed`)}static isBrowserSupported(){return(`CanvasCaptureMediaStream`in window||`CanvasCaptureMediaStreamTrack`in window)&&!(I.browserName()===`Safari`&&Number(I.browserVersion())===15)&&!(I.browserName()===`Firefox`&&Number(I.browserVersion())<60)}},Wr=class extends Hr{constructor(e){super(e),g(this,`_generator`,void 0),g(this,`_writer`,void 0),g(this,`_stream`,void 0),R.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()),R.debug(`TrackGeneratorRenderer destroyed`)}static isBrowserSupported(){return`VideoFrame`in window&&`MediaStreamTrackGenerator`in window&&Ir.isBrowserSupported()}},Gr=class extends Vr{constructor(e,t,n,r){super(e,t,n,r),g(this,`_renderer`,void 0),g(this,`_decoder`,void 0),g(this,`_decoderReady`,!1),g(this,`_decoderBusy`,!1),g(this,`_decoderQueue`,[]),g(this,`_fpsMeter`,void 0),R.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 Lr(e=>R.log(`[StreamBuilder][${this._participantId}] fps: ${e}`),2e4)}_initRenderer(e=!1){e||!Wr.isBrowserSupported()?this._renderer=new Ur(this._onStream):this._renderer=new Wr(this._onStream)}_initDecoder(e=!1){e||!Ir.isBrowserSupported()?this._decoder=new Fr:this._decoder=new Ir,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=>{this._decoderBusy=!1,this._decodeQueue(),this._decoder instanceof Ir&&typeof e==`string`&&e.includes(`EncodingError`)&&this._switchToLibVPXDecoder()},this._onKeyFrameRequested).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_switchToLibVPXDecoder(){R.warn(`StreamBuilder switch to LibVPX decoder`),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)}_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(),R.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return Ur.isBrowserSupported()||Wr.isBrowserSupported()}},Kr=1,qr=1,Jr=2,Yr=0,Xr=1,Zr=2,Qr=4,$r=8;function ei(e,t,n,r,i,a,o){let s=0;t&&(s|=Xr),n&&(s|=Zr),r&&(s|=Qr),o||(s|=$r);let c=new ArrayBuffer(11),l=new DataView(c);if(l.setUint8(0,Kr),l.setUint16(1,i),l.setUint32(3,e),l.setUint8(7,+!!a),l.setUint16(8,Yr),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&Xr),l=!!(s&Zr),u=!!(s&Qr),d=!!(s&$r);if(n!==Kr)throw Error(`Unexpected protocol version. Got ${n}, expected ${Kr}`);return{timestamp:i,start:c,end:l,keyframe:u,sequence:r,isVP9:a,ssrc:o,eos:d,data:e.slice(11)}}function ni(e){if(!e||!e.byteLength||e.byteLength!==4)return!1;let t=new DataView(e);return!(t.getUint8(0)!==Kr||t.getUint8(1)!==qr||t.getUint16(2)!==Yr)}function ri(e){if(!e||!e.byteLength||e.byteLength!==10)return null;let t=new DataView(e);return t.getUint8(0)!==Kr||t.getUint8(1)!==Jr||t.getUint16(2)!==Yr?null:{seq:t.getUint16(4),ts2:t.getUint32(6)}}function ii(e){let t=new ArrayBuffer(4),n=new DataView(t);return n.setUint8(0,Kr),n.setUint8(1,qr),n.setUint16(2,e),t}var ai=2**15-1,oi=1,si=5,ci=5,li=class e{constructor(e){g(this,`_mediaSource`,void 0),g(this,`_codec`,void 0),g(this,`_sourceBuffer`,null),g(this,`_queue`,[]),g(this,`_clearBufferTill`,0),this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener(`sourceopen`,t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener(`sourceopen`,t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let e=this._sourceBuffer.buffered.start(0);e<this._clearBufferTill&&(this._sourceBuffer.remove(e,this._clearBufferTill),R.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)-si);r-n>ci&&(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}},ui=class e extends Vr{constructor(e,t,n){super(e,t,n),g(this,`_mediaBuffer`,null),g(this,`_video`,null),g(this,`_stream`,null),g(this,`_earliestTimestamp`,0),g(this,`_clusterStartTime`,0),g(this,`_lastFrameTimestamp`,0),R.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 li(e),this._video=document.createElement(`video`),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents=`none`,this._video.style.visibility=`hidden`,this._video.style.position=`absolute`,this._video.style.width=`160px`,this._video.style.height=`90px`,this._video.style.bottom=`0`,this._video.style.right=`0`,this._video.style.zIndex=`5000`,this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video?.src){R.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=()=>R.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,R.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(),R.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>ai&&(this._clusterStartTime=r,i=0),i===0){R.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),R.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"`)}},di=class{constructor(e,t,n,r,i){g(this,`_datachannel`,void 0),g(this,`_participantIdRegistry`,null),g(this,`_streamBuilders`,{}),g(this,`_onStream`,()=>{}),g(this,`_onEos`,()=>{}),g(this,`_onStat`,void 0),R.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){R.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=w.screenShareWebmBuilder&&ui.isBrowserSupported()?new ui(n,e,this._onStat):new Gr(n,e,this._onStat,()=>{this._requestKeyFrame(t.ssrc)}),this._streamBuilders[n]=r}r.appendChunk(t)}_requestKeyFrame(e){if(!(!this._datachannel||this._datachannel.readyState!==`open`))try{let t=ii(e);this._datachannel.send(t),R.debug(`ScreenCaptureReceiver request for keyframe for ssrc ${e}`)}catch(e){R.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,R.debug(`ScreenCaptureReceiver destroyed`)}},fi=class{constructor(e,t,n){g(this,`_prev`,void 0),g(this,`_next`,void 0),g(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}},pi=class{constructor(){g(this,`_head`,null),g(this,`_tail`,null),g(this,`_length`,0)}get length(){return this._length}push(...e){for(let t of e)this._tail=new fi(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):``}},mi=1e3,hi=class extends Pr{constructor(e,t,n,r){super(),g(this,`_sourceTrack`,void 0),g(this,`_onFrame`,void 0),g(this,`_useCongestionControl`,void 0),g(this,`_maxBitrate`,void 0),g(this,`_useImageCapture`,void 0),g(this,`_video`,null),g(this,`_imageCapture`,null),g(this,`_canvas`,null),g(this,`_canvasCtx`,null),g(this,`_frameReadTimeout`,0),g(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;R.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(Nr.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)},mi),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(Nr.SET_BITRATE,{bitrate:e,useCbr:t})}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),R.debug(`LibVPxEncoder destroyed`)}},gi=class extends Pr{constructor(e,t,n,r,i,a){super(),g(this,`_sourceTrack`,void 0),g(this,`_trackProcessor`,void 0),g(this,`_onFrame`,void 0),g(this,`_useCongestionControl`,void 0),g(this,`_maxBitrate`,void 0),g(this,`_useCbr`,void 0),g(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;R.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;function g(e){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),y(),self.postMessage({type:t.READY})}function _(e){e&&!h&&(h=!0),self.clearTimeout(l),l=self.setTimeout(()=>{c&&v(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(!x){r.releaseLock(),n.cancel();return}c=t,v(t,h)}}))}function v(e,t){(e.codedWidth!==i||e.codedHeight!==a)&&(i=e.codedWidth,a=e.codedHeight,y(),h=!0),x.encode(e,{keyFrame:t}),t&&(h=!1)}function y(){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),x.configure(t)}function b(e,t,n){d=e,m=t,s=n,y()}let x=new VideoEncoder({output:e=>{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])},error:e=>{self.postMessage({type:t.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case t.INIT:g(e.data);break;case t.FRAME:_(e.data.keyFrame);break;case t.SET_BITRATE:b(e.data.bitrate,e.data.useCbr,e.data.fps);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})},[],{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(Nr.FRAME,{keyFrame:e})}setBitrate(e,t,n){this._sendToWorker(Nr.SET_BITRATE,{bitrate:e,useCbr:t,fps:n})}isVP9(){return!0}destroy(){this._removeWorker(),R.debug(`WebCodecsEncoder destroyed`)}static isBrowserSupported(){return`VideoEncoder`in window&&`Worker`in window&&`EncodedVideoChunk`in window&&`MediaStreamTrackProcessor`in window}},_i=2100,vi=600,yi=1.2,bi=.8,xi=2e3,Si=8e3,Ci=8e3,wi=16e3,Ti=4,Ei=2e3,Di=function(e){return e[e.NONE=0]=`NONE`,e[e.UP=1]=`UP`,e[e.DOWN=2]=`DOWN`,e}(Di||{}),Oi=class{constructor(e,t,n,r,i,a,o){g(this,`_onCongestion`,void 0),g(this,`_ccEnabled`,void 0),g(this,`_fastSharing`,void 0),g(this,`_trendDelayThreshold`,void 0),g(this,`_highDelayThreshold`,void 0),g(this,`_targetFps`,void 0),g(this,`_minBitrate`,void 0),g(this,`_maxBitrate`,void 0),g(this,`_targetBitrate`,void 0),g(this,`_lastDown`,void 0),g(this,`_lastUp`,void 0),g(this,`_lastProbing`,void 0),g(this,`_lastCheckDelay`,void 0),g(this,`_upPenalty`,0),g(this,`_probing`,void 0),g(this,`_delayAvgShort`,-1),g(this,`_delayAvgLong`,-1),g(this,`_minDelay`,Number.MAX_VALUE),g(this,`_maxDelay`,0),g(this,`_largeDelayDuration`,0),g(this,`_lastFpsCalcMs`,void 0),g(this,`_frames`,0),g(this,`_fps`,0),this._onCongestion=e,this._ccEnabled=r,this._minBitrate=t,this._maxBitrate=n,this._fastSharing=i,this._targetFps=o,a>0?this._highDelayThreshold=a:this._highDelayThreshold=_i,i&&(this._highDelayThreshold=vi),this._trendDelayThreshold=Math.round(this._highDelayThreshold/3),this._targetBitrate=this._maxBitrate,this._probing=!1;let s=Date.now();this._lastDown=0,this._lastUp=s,this._lastProbing=s,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&&R.debug(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Di[i]} tr=${l} br=${n}`);let d=r-this._lastDown;if(i===2&&d>xi){this._probing&&(this._upPenalty=Math.min(++this._upPenalty,Ti),this._probing=!1);let n=bi*u*1e3;if(n>=this._targetBitrate&&(n=this._targetBitrate*bi),n=Math.max(n,this._minBitrate),n<this._targetBitrate){let r=Math.round(n/1e3),s=Math.round(this._upPenalty*Ci/1e3);R.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Di[i]}`),R.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=Si+this._upPenalty*Ci;if(i===1&&f>p&&d>p){let n=Math.min(this._targetBitrate*yi,this._maxBitrate);if(n>this._targetBitrate){let s=Math.round(n/1e3),c=Math.round(this._targetBitrate/1e3),l=Math.round(this._upPenalty*Ci/1e3);R.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Di[i]}`),R.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>wi&&(this._probing=!1);let h=r-this._lastDown;this._upPenalty>0&&h>3*p&&(R.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>Ei){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&&R.log(`cc: fps=${this._fps}`)}}},ki=class{constructor(e){g(this,`_maxSize`,void 0),g(this,`_size`,0),g(this,`_buffer`,void 0),g(this,`_head`,0),g(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}},Ai=65536,ji=50,Mi=400,Ni=1e6,Pi=3e5,Fi=3e4,Ii=2e3,Li=5,Ri=0,zi=class{constructor(e,t,n,r){g(this,`_encoder`,void 0),g(this,`_datachannel`,void 0),g(this,`_signaling`,void 0),g(this,`_fastSharing`,void 0),g(this,`_destroyed`,!1),g(this,`_needKeyframe`,!0),g(this,`DATA_SIZE`,void 0),g(this,`_congestionControl`,void 0),g(this,`_frameNum`,0),g(this,`_width`,void 0),g(this,`_height`,void 0),g(this,`_feedback`,new ki(1024)),g(this,`_lastSentFrameSeq`,0),g(this,`_lastDeliveredFrameSeq`,0),g(this,`_lastFrameDelay`,0),g(this,`_lastFramerateReduced`,Date.now()),g(this,`_lastSharingStat`,Date.now()),g(this,`_congestionControlEnabled`,void 0),g(this,`_queue`,new pi),g(this,`_fpsMeter`,void 0),g(this,`_maxFrameDelay`,void 0),R.debug(`ScreenCaptureSender started`),this.DATA_SIZE=w.consumerScreenDataChannelPacketSize-11,this._datachannel=t,this._signaling=n,this._fastSharing=r,this._congestionControlEnabled=w.screenShareCongestionControl||this._fastSharing,this._width=e.getSettings().width,this._height=e.getSettings().height,this._maxFrameDelay=this._fastSharing?w.screenShareCongestionControlThreshold:w.screenShareCongestionControlThreshold*2;let i=w.getScreenFrameRate(this._fastSharing),{minBitrate:a,maxBitrate:o}=this._calcMinMaxBitrate(this._width,this._height),s=this._onCongestionCallback.bind(this);R.log(`ScreenCaptureSender: CongestionControl: enabled=${this._congestionControlEnabled} minBitrate=${Math.round(a/1e3)}k maxBitrate=${Math.round(o/1e3)}k delayThreshold=${w.screenShareCongestionControlThreshold}`),this._congestionControl=new Oi(s,a,o,this._congestionControlEnabled,this._fastSharing,w.screenShareCongestionControlThreshold,i);let c=(e,t)=>{if(this._destroyed)return;if(!e){R.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(gi.isBrowserSupported()){let t=this._fastSharing;this._encoder=new gi(e,c,this._congestionControlEnabled,o,t,i)}else this._encoder=new hi(e,c,this._congestionControlEnabled,o);this._datachannel.onmessage=e=>{ni(e.data)&&(R.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0);let t=ri(e.data);t!==null&&this._checkCcFeedback(t)},this._encoder.init().then(()=>this._handleQueue()).catch(e=>R.warn(`ScreenCaptureSender init failed`,e)),this._fpsMeter=new Lr(e=>R.log(`[ScreenCaptureSender] fps: ${e}`),5e3)}_handleQueue(){if(this._destroyed)return;let e=this._queue.shift();if(!e){if((this._lastSentFrameSeq-this._lastDeliveredFrameSeq+Ai)%Ai>Li&&this._lastFrameDelay>this._maxFrameDelay){let e=Date.now();e-this._lastFramerateReduced>Ii&&(this._lastFramerateReduced=e,R.debug(`[ScreenCaptureSender] reduce framerate: delay=${this._lastFrameDelay} maxDelay=${this._maxFrameDelay}`))}else this._requestFrame();return}if(!this._sendFrameChunk(e)){this._needKeyframe=this._needKeyframe||!this._cleanupQueue(),C.setImmediate(()=>this._handleQueue());return}if(e.isLast){this._frameNum++,this._fpsMeter.increment(),e.isKey&&R.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 C.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 pi;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=ei(e,t,n,r,Ri,this._encoder.isVP9(),i),o={sequence:Ri,data:a};return Ri=(Ri+1)%Ai,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 R.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(),R.debug(`ScreenCaptureSender destroyed`)}static isBrowserSupported(){return gi.isBrowserSupported()||hi.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);R.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(Pi,Math.min(Ni,Math.round(n*ji))),maxBitrate:Math.round(n*Mi)}}_checkCcFeedback(e){let t=this._feedback.update(e.seq,e.ts2);if(t===null)R.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>Fi){let t=this._congestionControl.getStat();t!==null&&(R.debug(`cc: send stats: ${JSON.stringify(t)}`),this._signaling.reportSharingStat(t)),this._lastSharingStat=e}}},Bi=90,Vi=4294967295,Hi=class e extends rr{constructor(e,t,n){super(e,t),g(this,`_producerNotification`,null),g(this,`_producerCommand`,null),g(this,`_producerScreen`,null),g(this,`_consumerScreen`,null),g(this,`_asr`,null),g(this,`_animojiDataChannel`,null),g(this,`_animojiReceiver`,null),g(this,`_animojiSender`,null),g(this,`_isOpen`,!1),g(this,`_observer`,!1),g(this,`_reconnectionPrevented`,!1),g(this,`_statInterval`,null),g(this,`_settingsInterval`,null),g(this,`_monitorRtpShareInterval`,null),g(this,`_statBytes`,{}),g(this,`_ssrcMap`,{}),g(this,`_ssrcMapUpdated`,!1),g(this,`_perfStatReporter`,void 0),g(this,`_producerOfferIsProcessing`,!1),g(this,`_producerNextOffer`,null),g(this,`_producerNextSessionId`,null),g(this,`_lastStat`,null),g(this,`_serverSettings`,void 0),g(this,`_prevConsumerSettings`,{}),g(this,`_prevConsumerFastSharingSettings`,{}),g(this,`_asrTrack`,null),g(this,`_captureSender`,null),g(this,`_captureReceiver`,null),g(this,`_participantIdRegistry`,null),g(this,`_disabledSenders`,new Set),g(this,`_rtpReceiversByStreamId`,{}),g(this,`_producerSessionId`,``),g(this,`_newAudioShareTrack`,null),g(this,`_simulcastInfo`,null),this.subscribe(this._signaling,qn.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Oe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Oe.SOURCE_CHANGED,this._onSourcesChanged.bind(this)),this.subscribe(this._mediaSource,Oe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._createPerfStatsReporter(),this._serverSettings=n,R.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){R.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?(R.error(`ServerTransport: Closed`,e),this._setState(q.FAILED)):(R.debug(`ServerTransport: Closed`),this._setState(q.CLOSED)))}removeParticipant(e){this._captureReceiver?.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){$n(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}setAnimojiTransport(e,t){if(w.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(){w.simulcast&&await this._changeSimulcastInfo(!0,!1)}_createPerfStatsReporter(){this._perfStatReporter?.destroy(),this._perfStatReporter=new sr(this,this._signaling)}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._stopMonitorRtpShareInterval(),this._removeAsrTrack(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._simulcastInfo=null,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(K.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,n){R.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let e=r.readyState;e===`open`?(R.debug(`[${t}] data channel opened`),n(r)):R.error(`[${t}] data channel open failed, state [${e}]`)},r.onerror=e=>{let n=e.error;R.error(`[${t}] data channel error`,n?.errorDetail,n?.message)}}_openConnection(t=!1){R.debug(`ServerTransport: Open single connection`);try{this._pc=new RTCPeerConnection}catch(e){R.error(`Failed to create RTCPeerConnection:`,e),this.close(e);return}this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=C.debounce(e=>{this._pc&&this._onConnectionStateChange(this._pc,e)},500),this._pc.onsignalingstatechange=e._onSignalingStateChange.bind(this,this._pc),this._participantIdRegistry=new Mr,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._createDataChannel(this._pc,Jn.producerNotification,e=>{this._producerNotification=e,this._producerNotification.binaryType=`arraybuffer`,this._signaling.setProducerNotificationDataChannel(e)}),this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,Jn.producerCommand,e=>{this._producerCommand=e,this._signaling.setProducerCommandDataChannel(e)}),this._createDataChannel(this._pc,Jn.producerScreenShare,e=>{this._producerScreen=e,this._producerScreen.binaryType=`arraybuffer`,this._createCaptureReceiver()}),w.asrDataChannel&&this._createDataChannel(this._pc,Jn.asr,e=>{this._asr=e,this._asr.binaryType=`arraybuffer`,this._removeAsrTrack(),this._asrTrack=new kr(e,this._participantIdRegistry,e=>{this._onAsrTranscription(e)})}),w.vmoji&&this._createDataChannel(this._pc,Jn.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(w.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){R.error(`ServerTransport: Unable to add media source tracks`,e),O.log(b.ERROR,`addTrack-single`),this.close(e);return}this._createDataChannel(this._pc,Jn.consumerScreenShare,e=>{this._consumerScreen=e,this._consumerScreen.binaryType=`arraybuffer`;let t=this._mediaSource.getScreenTrack();t&&(!w.consumerFastScreenShare||!this._mediaSource.mediaSettings.isFastScreenSharingEnabled)&&this._createCaptureSender(t)}),t||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(K.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(K.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(K.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(K.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
14
+ `)}return e}e.patchSimulcastAnswerSdp=Ee})(he||(he={}));var C=he,ge=`__CALLS_SDK_DEVTOOLS_`,_e=class{set(e,t){try{this.getStorage().setItem(ge+e,JSON.stringify(t))}catch(t){R.warn(`DevTools: Failed to save option`,e,t)}}get(e){try{let t=this.getStorage().getItem(ge+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(ge+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(ge)&&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(ge)){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}},ve=class{constructor(e){g(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}},ye=class e{static getInstance(){return e.instance||(e.instance=new e),e.instance}constructor(){g(this,`params`,void 0),g(this,`storage`,void 0),this.storage=new _e,this.params=new ve(this.storage)}};g(ye,`instance`,null);var be=ye.getInstance(),w=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`)&&(x.accessToken=t.apiAuth.accessToken,x.sessionKey=t.apiAuth.sessionKey,x.sessionSecretKey=t.apiAuth.sessionSecretKey);let n=be.params.applyOverrides(t);Object.assign(e._params,C.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 1.1}static get sdkVersion(){return`2.8.11-dev.37528a3e.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 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://api-mames.calls-test.oneme.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 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||(I.isMobile()?dt.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 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 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 clientEventsLoggingEnabled(){return e._params.clientEventsLoggingEnabled}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 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 I.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 I.isSimulcastSupportedByBrowser()&&e._params.simulcast}static get webtransport(){return e._params.webtransport}static get webtransportFF(){return e._params.webtransportFF}static get transparentAudio(){return e._params.transparentAudio}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,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,consumerScreenDataChannelPacketSize:e._params.consumerScreenDataChannelPacketSize,switchVideoAtBadNetwork:e._params.switchVideoAtBadNetwork,simulcast:e._params.simulcast,webtransport:e._params.webtransport,webtransportFF:e._params.webtransportFF,transparentAudio:e._params.transparentAudio}}};g(w,`_params`,{platform:`WEB`,clientStatsPlatform:``,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,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,vmoji:null,vmojiOptions:null,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,clientEventsLoggingEnabled:!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,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,webtransportFF:!1,transparentAudio:!1});function xe(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 T(e){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,isFastScreenSharingEnabled:!1,isAudioSharingEnabled:!1,isAnimojiEnabled:!1},e||{})}var Se=e=>e.stop(),Ce=e=>e.getTracks().forEach(Se),we=e=>e.getVideoTracks().forEach(Se);async function Te(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 E=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.CALLER_IS_REJECTED=`CALLER_IS_REJECTED`,e.UNKNOWN_ERROR=`UNKNOWN_ERROR`,e.UNSUPPORTED=`UNSUPPORTED`,e.OLD_VERSION=`OLD_VERSION`,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}(E||{}),D=class e extends Error{constructor(t,n){super(),g(this,`message`,void 0),g(this,`hangup`,void 0),g(this,`error`,void 0),g(this,`code`,void 0),g(this,`remote`,void 0),g(this,`custom_error`,void 0),this.name=`HangupReason`,this.code=n&&n.code||0,this.remote=n&&n.remote||!1,this.custom_error=n?.custom_error??null,Object.values(E).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)}},O=class e extends m{static setConversationIdProvider(t){e._conversationIdProvider=t}static create(t,n){e._instance||(e._instance=new e(t,n))}static log(t,n,r=!1){e._instance&&e._instance.log(t,n,r)}static logClientStats(t,n=!1){e._instance&&e._instance.logClientStats(t,n)}static logClientEvent(t,n=!1){e._instance&&e._instance.logClientEvent(t,n)}static destroy(){e._instance&&e._instance.destroy(),e._instance=null}constructor(e,t){super(),g(this,`_externalLogger`,void 0),g(this,`_api`,void 0),g(this,`_batchInterval`,3e3),g(this,`_batchedClientStats`,[]),g(this,`_batchedClientEvents`,[]),g(this,`_batchTimeout`,null),g(this,`_serverTimeDelta`,0),this._api=e,this._externalLogger=t,this._calculateServerTimeDelta()}log(e,t,n=!1){this._externalLogger&&this._externalLogger.log(e,t,n)}logClientStats(e,t=!1){let n=Object.assign(e,{vcid:this._getConversationId(),timestamp:this._now()});Object.keys(n).forEach(e=>{n[e]===void 0&&delete n[e]}),this._batchedClientStats.push(n),(t||!this._batchTimeout)&&this._sendBatch()}logClientEvent(e,t=!1){let n=Object.assign(e,{vcid:this._getConversationId(),timestamp:this._now()});this._batchedClientEvents.push(n),(t||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}_getConversationId(){if(e._conversationIdProvider)try{return e._conversationIdProvider()}catch{return null}return null}_sendBatch(){this._stopTimeout();let e=!1;this._batchedClientStats.length>0&&(this._sendClientStats(this._batchedClientStats),this._batchedClientStats=[],e=!0),this._batchedClientEvents.length>0&&(this._sendClientEvents(this._batchedClientEvents),this._batchedClientEvents=[],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)}_sendClientEvents(e){this._api.logClientEvents(e)}async _calculateServerTimeDelta(){try{let e=await this._api.getServerTime();this._serverTimeDelta=Date.now()-e}catch{}}_now(){return Date.now()-this._serverTimeDelta}};g(O,`_instance`,void 0),g(O,`_conversationIdProvider`,null);var Ee=function(e){return e.FpsLimit=`fps-limit`,e}({}),De=class extends _{constructor(...e){super(...e),g(this,`FPS_LIMITS`,[13,20,Math.max(w.videoFrameRate,25)]),g(this,`THRESHOLD`,.8),g(this,`HISTORY_LENGTH`,10),g(this,`_fpsMeterUnsubscribe`,null),g(this,`_fpsHistory`,{cursor:0,arr:[]}),g(this,`_fpsLimitCursor`,this.FPS_LIMITS.length-1)}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){R.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()}},Oe=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}({}),ke=function(e){return e[e.CAMERA=1]=`CAMERA`,e[e.SCREEN=2]=`SCREEN`,e}({}),Ae=class extends _{constructor(){super(),g(this,`_stream`,null),g(this,`_screenTrack`,null),g(this,`_audioShareTrack`,null),g(this,`_screenShareTrack`,null),g(this,`_sendVideoTrack`,null),g(this,`_cameraVideoTrack`,null),g(this,`_micAudioTrack`,null),g(this,`_audioEffectsTrack`,null),g(this,`_mediaSettings`,T()),g(this,`_lastMediaSettings`,null),g(this,`_videoStatusOnScreenCapturingEnabled`,!1),g(this,`_effect`,null),g(this,`_audioEffectParams`,null),g(this,`_onDeviceChange`,void 0),g(this,`_animojiEnabled`,!1),g(this,`_videoEffectsFpsLimiter`,void 0),g(this,`videoTrackMuteHandler`,()=>{this._mediaSettings.isVideoEnabled&&this.toggleVideo(!0)}),this._initDeviceChangeListener(),w.audioShare&&(this._audioShareTrack=this.getSilentAudioShareTrack()),w.enableVideoEffectsFpsDegradation&&(this._videoEffectsFpsLimiter=new De,this._videoEffectsFpsLimiter.addEventListener(Ee.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._cameraVideoTrack.addEventListener(`mute`,this.videoTrackMuteHandler),w.consumerFastScreenShare&&(this._screenShareTrack=this.getBlackScreenShareTrack())}async request(e=[y.AUDIO],t=!0){if(this._stream)return;let n=e.includes(y.VIDEO),r=e.includes(y.AUDIO),i=e.includes(y.ANIMOJI);if(!I.isBrowserSupported())throw new D(v.UNSUPPORTED);try{this._stream=await I.getUserMedia(n,r,t),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 D(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(){return this._stream?.getAudioTracks().find(e=>!e.contentHint)||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(v.UNKNOWN)}}stopVideoTrack(){this._mediaSettings.isVideoEnabled&&(this._stopEffect(),this._stream&&we(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=I.getSavedMicrophone(),n=I.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{}},I.addEventListener(`devicechange`,this._onDeviceChange))}_destroyDeviceChangeListener(){this._onDeviceChange&&I.removeEventListener(`devicechange`,this._onDeviceChange)}async _changeVideoInput(e){try{let t=e?`stream`:`video`,n=e||await I._getUserVideo(!!this._effect,this._frameRate);if(this.cameraVideoTrack?.stop(),this.cameraVideoTrack=n.getVideoTracks()[0],!this._stream)Ce(n);else{let e=await this._setEffect(this._effect,this.cameraVideoTrack);O.log(b.DEVICE_CHANGED,t),R.log(`Video stream changed`),await this._replaceLocalTrack(e),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent(`SOURCE_CHANGED`,{kind:`video`})}}catch(e){throw O.log(b.ERROR,`change_video`),R.warn(`Camera change failed`,e),e}}async setAudioStream(e){return this._changeAudioInput(e)}async _changeAudioInput(e=null){try{let t=e||await I.getUserAudio();if(this._micAudioTrack?.stop(),this._micAudioTrack=t.getAudioTracks()[0],!this._stream)Ce(t);else{let e=await this._applyAudioEffect();O.log(b.DEVICE_CHANGED,`audio`),R.log(`Audio stream changed`,e),await this._replaceLocalTrack(e),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent(`SOURCE_CHANGED`,{kind:`audio`})}}catch(e){throw O.log(b.ERROR,`change_audio`),R.error(`Microphone change failed`,e),e}}async _changeScreen(e,t,n){try{if(n=n||await I.getScreenMedia(e,t),!this._stream)Ce(n);else{let r=n.getVideoTracks()[0];if(r.addEventListener(`ended`,()=>{this._mediaSettings.isScreenSharingEnabled&&this.disableScreenCapturing()},!1),O.log(b.DEVICE_CHANGED,`screen`),R.log(`Screen capturing started`),this._screenTrack=r,this._mediaSettings.isScreenSharingEnabled=!0,this._mediaSettings.isFastScreenSharingEnabled=e,w.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._replaceLocalTrack(e),this._mediaSettings.isAudioSharingEnabled=!0}t&&!this._mediaSettings.isAudioSharingEnabled&&R.debug(`Audio share requested but not captured`),this._triggerEvent(`SCREEN_STATUS`,{track:r}),this._triggerEvent(`SOURCE_CHANGED`,{kind:`screen`})}}catch(e){throw O.log(b.ERROR,`screen`),R.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){this._audioShareTrack.stop();let e=this.getSilentAudioShareTrack();await this._replaceLocalTrack(e),this._mediaSettings.isAudioSharingEnabled=!1}}async _applyAudioEffect(){if(!w.audioEffects||!this._audioEffectParams)return w.audioEffects?.pause(),this._micAudioTrack;w.audioEffects.isInitialized||await w.audioEffects.init(),w.audioEffects.resume(),w.audioEffects.setEffects(this._audioEffectParams.effects,this._audioEffectParams.isPreset),w.audioEffects.setSource(this._micAudioTrack);let e=w.audioEffects.outputStream.getAudioTracks()[0];return(!this._audioEffectsTrack||this._audioEffectsTrack.id!==e.id)&&(this._audioEffectsTrack=e),this._audioEffectsTrack}getSilentAudioShareTrack(){let e=I.getSilentMediaTrack();return e.contentHint=`music`,e.stop(),e}getBlackScreenShareTrack(){let e=I.getBlackMediaTrack();return e.contentHint=`motion`,e.stop(),e}async _replaceLocalTrack(e,t){if(!this._stream)return;let n=this._stream.getTracks().find(t=>t.kind===e.kind&&t.contentHint===e.contentHint);n?.id!==e.id&&(n?(n!==this._audioEffectsTrack&&n.stop(),this._stream?.removeTrack(n),this._stream?.addTrack(e),this._triggerEvent(`TRACK_REPLACED`,e,t)):(this._stream.addTrack(e),this._triggerEvent(`TRACK_REPLACED`,e,t)))}async _setEffect(e,t){if(this._videoEffectsFpsLimiter?.watch(w.videoEffects),!w.videoEffects)return t;try{return w.videoEffects.setEffect(e,t)}catch(e){return R.warn(`Video effect failed`,e),t}}_stopEffect(){if(w.videoEffects)try{w.videoEffects.stopEffect()}catch(e){R.warn(`Video effect failed`,e)}}destroy(){this._destroyDeviceChangeListener(),I.releaseFirefoxMicrophonePermissionWarmup(),w.videoEffects&&(this._effect=null,w.videoEffects.destroy()),w.audioEffects&&w.audioEffects.destroy(),this._stream&&(Ce(this._stream),this._stream=null),this.cameraVideoTrack?.stop(),this._micAudioTrack?.stop(),this._audioEffectsTrack?.stop(),this._disableScreenCapture(),I.getAudioContext()?.suspend().catch(e=>R.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(){if(!this._lastMediaSettings)return;let e=[];if(this._lastMediaSettings.isAudioEnabled&&(e.push(y.AUDIO),await this.toggleAudio(!0)),await this.request(e),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 I._getUserVideo(!!this._effect,this._frameRate);this.cameraVideoTrack=e.getVideoTracks()[0],t=await this._setEffect(this._effect,this.cameraVideoTrack)}else t=I.getBlackMediaTrack(w.videoMinWidth,w.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 I.getUserAudio();this._micAudioTrack=e.getAudioTracks()[0],t(await this._applyAudioEffect(),!0)}catch(e){throw w.audioEffects?.pause(),t(I.getSilentMediaTrack(),!1),typeof e==`string`?Error(e):e}else w.audioEffects?.pause(),t(I.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:w.noiseSuppression})}async videoEffect(e){if(!w.videoEffects)throw Error(`Video Effects library is not set`);if(O.log(b.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(!w.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||!C.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<w.videoFrameRate&&this._applyVideoConstraints(this.cameraVideoTrack).catch(e=>{R.warn(`MediaSource handleVideoEffectsLowFps error`,e)})}get _frameRate(){let e=this._videoEffectsFpsLimiter?.fpsLimit??w.videoFrameRate;return this._effect?Math.min(e,w.videoFrameRate):void 0}async _applyVideoConstraints(e,t){await Te(e,{width:this._effect?w.videoEffectMaxWidth:w.videoMaxWidth,height:this._effect?w.videoEffectMaxHeight:w.videoMaxHeight,...this._frameRate&&{frameRate:{ideal:this._frameRate}},...t})}getScreenShareTrack(){return this._screenShareTrack}},je=class{constructor(){g(this,`_cameraPermissionStatus`,void 0),g(this,`_microphonePermissionStatus`,void 0),g(this,`_listener`,void 0)}static isSupported(){return I.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){let t=null;switch(e){case`camera`:t=this._cameraPermissionStatus.state;break;case`microphone`:t=this._microphonePermissionStatus.state;break}return t}},A=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 j(e,...t){let n=w.get(e);typeof n==`function`&&setTimeout(n,0,...t)}function M(e,t,...n){if(w.filterObservers){if(Array.isArray(t)){if(t=t.filter(e=>!e.observer),!t.length)return}else if(t.observer)return}j(e,t,...n)}function N(e){return Object.assign({},e)}function Me(e){return e.slice()}var Ne;(function(e){function t(e,t,n){j(`onLocalStream`,e,N(t),n)}e.onLocalStream=t;function n(e,t,n){j(`onScreenStream`,e,N(t),n)}e.onScreenStream=n;function r(e,t,n){j(`onVmojiStream`,e,N(t),n)}e.onVmojiStream=r;function i(e,t){j(`onVmojiError`,e,t)}e.onVmojiError=i;function a(e,t,n){j(`onLocalStreamUpdate`,N(e),t,n)}e.onLocalStreamUpdate=a;function o(e,t){R.debug(`Local status:`,e),j(`onLocalStatus`,e,t)}e.onLocalStatus=o;function s(e,t,n){M(`onRemoteStream`,e,t,n)}e.onRemoteStream=s;function c(e,t,n){M(`onRemoteLive`,e,t,n)}e.onRemoteLive=c;function l(e,t,n){M(`onLocalLive`,e,t,n)}e.onLocalLive=l;function u(e,t,n){M(`onRemoteLiveUpdate`,e,t,n)}e.onRemoteLiveUpdate=u;function d(e,t,n){M(`onLocalLiveUpdate`,e,t,n)}e.onLocalLiveUpdate=d;function f(e,t,n){M(`onRemoteScreenStream`,e,t,n)}e.onRemoteScreenStream=f;function p(e,t,n){M(`onRemoteVmojiStream`,e,t,n)}e.onRemoteVmojiStream=p;function m(e,t,n,r){M(`onRemoteStreamSuspended`,e,t,n,r)}e.onRemoteStreamSuspended=m;function h(e,t,n,r,i,a){M(`onConversation`,e,N(t),N(n),r,i,a)}e.onConversation=h;function ee(e,t){e&&j(`onConversationParticipantListChunk`,e,t)}e.onConversationParticipantListChunk=ee;function te(e,t,n,r){M(`onRemoteMediaSettings`,e,N(t),n,r)}e.onRemoteMediaSettings=te;function g(e,t,n){M(`onLocalMediaSettings`,e,N(t),n)}e.onLocalMediaSettings=g;function _(e,t,n,r){M(`onRemoteSharedMovieInfo`,e,N(t),n,r)}e.onRemoteSharedMovieInfo=_;function v(e,t,n,r){M(`onRemoteSharedMovieStoppedInfo`,e,N(t),n,r)}e.onRemoteSharedMovieStoppedInfo=v;function y(e,t,n,r){M(`onLocalSharedMovieInfo`,e,N(t),n,r)}e.onLocalSharedMovieInfo=y;function b(e,t,n,r){M(`onLocalSharedMovieStoppedInfo`,e,N(t),n,r)}e.onLocalSharedMovieStoppedInfo=b;function x(e,t,n,r){M(`onRemoteSharedUrl`,e,t,n,r)}e.onRemoteSharedUrl=x;function S(e,t,n){M(`onParticipantAdded`,e,t,n)}e.onParticipantAdded=S;function ne(e,t,n){M(`onParticipantJoined`,e,t,n)}e.onParticipantJoined=ne;function re(e,t=!1,n){j(`onLocalParticipantState`,N(e),t,n)}e.onLocalParticipantState=re;function ie(e,t,n,r){M(`onRemoteParticipantState`,e,N(t),n,r)}e.onRemoteParticipantState=ie;function ae(e,t,n){j(`onRemoteParticipantsState`,e,t,n)}e.onRemoteParticipantsState=ae;function oe(e,t,n=null,r){R.debug(`Remote status:`,t,e),M(`onRemoteStatus`,e,t,n,r)}e.onRemoteStatus=oe;function se(e){j(`onPermissionsRequested`,e)}e.onPermissionsRequested=se;function ce(e,t,n){j(`onPermissionsError`,e,t,n)}e.onPermissionsError=ce;function le(e,t,n){M(`onRemoteRemoved`,e,t,n)}e.onRemoteRemoved=le;function ue(e,t,n,r){j(`onCallState`,e,t,N(n),r)}e.onCallState=ue;function de(e,t,n){j(`onDeviceSwitched`,e,t,n)}e.onDeviceSwitched=de;function fe(e,t,n,r=!1,i=!1,a=null,o=null,s,c,l=null,u){let d=c?Me(c):void 0;j(`onMuteStates`,N(e),Me(t),Me(n),r,i,a,o,s,d,l,u)}e.onMuteStates=fe;function pe(e,t,n=!1,r){M(`onRolesChanged`,e,Me(t),n,r)}e.onRolesChanged=pe;function me(e,t=!1,n){j(`onLocalRolesChanged`,Me(e),t,n)}e.onLocalRolesChanged=me;function he(e,t,n,r,i){M(`onPinnedParticipant`,e,t,n,r,i)}e.onPinnedParticipant=he;function C(e,t,n){j(`onLocalPin`,e,t,n)}e.onLocalPin=C;function ge(e,t){j(`onOptionsChanged`,Me(e),t)}e.onOptionsChanged=ge;function _e(e){j(`onCallAccepted`,e)}e.onCallAccepted=_e;function ve(e){j(`onCallActive`,e)}e.onCallActive=ve;function ye(e,t,n){M(`onAcceptedCall`,e,t,n)}e.onAcceptedCall=ye;function be(e){j(`onRateNeeded`,e)}e.onRateNeeded=be;function w(e,t){M(`onSpeakerChanged`,e,t)}e.onSpeakerChanged=w;function xe(e,t){j(`onVolumesDetected`,Me(e),t)}e.onVolumesDetected=xe;function T(e,t,n){j(`onLocalVolume`,e,t,n)}e.onLocalVolume=T;function Se(e,t,n){j(`onJoinStatus`,e,t,n)}e.onJoinStatus=Se;function Ce(e,t){j(`onHangup`,e,t)}e.onHangup=Ce;function we(e,t){j(`onMultipartyChatCreated`,N(e),t)}e.onMultipartyChatCreated=we;function Te(e){j(`onDeviceChange`,e)}e.onDeviceChange=Te;function E(e,t){j(`onFingerprintChange`,e,t)}e.onFingerprintChange=E;function D(e){j(`onTokenExpired`,e)}e.onTokenExpired=D;function O(e,t,n=!1,r){j(`onChatMessage`,e,t,n,r)}e.onChatMessage=O;function Ee(e,t,n=!1,r){j(`onCustomData`,e,t,n,r)}e.onCustomData=Ee;function De(e,t,n,r,i,a,o=null,s){j(`onRecordStarted`,e,t,n,r,i,a,o,s)}e.onRecordStarted=De;function Oe(e=null,t,n){j(`onRecordStopped`,e,t,n)}e.onRecordStopped=Oe;function k(e,t){j(`onLocalNetworkStatusChanged`,e,t)}e.onLocalNetworkStatusChanged=k;function ke(e,t){j(`onNetworkStatusChanged`,e,t)}e.onNetworkStatusChanged=ke;function Ae(e,...t){j(`onDebugMessage`,e,...t)}e.onDebugMessage=Ae;function je(e,t,n){j(`onStatistics`,Object.assign({},e,{memory:t}),n)}e.onStatistics=je;function A(e){j(`onAutoplayError`,e)}e.onAutoplayError=A;function Ne(e,t,n,r,i,a){j(`onChatRoomUpdated`,e,t,n,r,i,a)}e.onChatRoomUpdated=Ne;function P(e,t){j(`onPromoted`,e,t)}e.onPromoted=P;function Pe(e,t){j(`onRemoteMixedAudioStream`,e,t)}e.onRemoteMixedAudioStream=Pe;function Fe(e,t){j(`onJoinLinkChanged`,e,t)}e.onJoinLinkChanged=Fe;function Ie(e,t){j(`onRoomsUpdated`,e,t)}e.onRoomsUpdated=Ie;function Le(e,t,n,r,i){j(`onRoomUpdated`,e,t,n,r,i)}e.onRoomUpdated=Le;function Re(e,t){j(`onRoomParticipantsUpdated`,e,t)}e.onRoomParticipantsUpdated=Re;function ze(e,t){j(`onRoomSwitched`,e,t)}e.onRoomSwitched=ze;function Be(e,t){j(`onRoomStart`,e,t)}e.onRoomStart=Be;function Ve(e,t=null,n){j(`onFeedback`,e,t,n)}e.onFeedback=Ve;function He(e,t){j(`onFeaturesPerRoleChanged`,e,t)}e.onFeaturesPerRoleChanged=He;function Ue(e,t){j(`onParticipantVmojiUpdate`,e,t)}e.onParticipantVmojiUpdate=Ue;function We(e,t,n){j(`onAsrSet`,e,t,n)}e.onAsrSet=We;function Ge(e,t,n,r){j(`onAsrStarted`,e,t,n,r)}e.onAsrStarted=Ge;function Ke(e,t){j(`onAsrStopped`,e,t)}e.onAsrStopped=Ke;function qe(e,t,n,r,i){j(`onAsrTranscription`,e,t,n,r,i)}e.onAsrTranscription=qe;function Je(e,t,n){j(`onParticipantIdChanged`,e,t,n)}e.onParticipantIdChanged=Je;function Ye(e,t){j(`onVideoSuspendSuggest`,e,t)}e.onVideoSuspendSuggest=Ye;function Xe(e,t){j(`onSignalingMessage`,typeof e==`string`?e:N(e),t)}e.onSignalingMessage=Xe;function Ze(e,t){j(`onPromotionApproved`,e,t)}e.onPromotionApproved=Ze;function Qe(e){j(`onPeerRegistered`,e)}e.onPeerRegistered=Qe})(Ne||(Ne={}));var P=Ne,Pe=`_okcls_`,Fe=(()=>{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 Ie(e){let t=Fe?Fe.getItem(Pe+e):null;if(t===null)return null;try{return JSON.parse(t)}catch{return null}}function Le(e,t){try{Fe&&Fe.setItem(Pe+e,JSON.stringify(t))}catch{}}function Re(e){Fe&&Fe.removeItem(Pe+e)}var ze;(function(e){function t(e){return Ie(e)||null}e.get=t;function n(e,t){Le(e,t)}e.set=n;function r(e){Re(e)}e.remove=r})(ze||(ze={}));var Be=ze,Ve=null,He=null,Ue=null,We=[],Ge=[],Ke=[],qe=null,Je=null,Ye=null,Xe=!1,Ze=!1,Qe,$e,et,tt=null,nt=null,rt=``,it=null,at=[],ot=null,st=navigator.appVersion,ct=navigator.appName,lt=navigator.userAgent,ut={},dt=function(e){return e.USER=`user`,e.ENVIRONMENT=`environment`,e}({});(function(e){function t(e){return Object.values(dt).includes(e)}e.contains=t})(dt||(dt={}));var ft=class{constructor(e,t=!1,n=w.videoMaxWidth,r=w.videoMaxHeight,i=w.videoFrameRate){g(this,`audio`,void 0),g(this,`video`,void 0),g(this,`needVideo`,void 0),g(this,`lastSimplifyWasReached`,void 0),g(this,`supportedConstraints`,void 0),g(this,`isVideoRequested`,()=>this.needVideo),this.supportedConstraints=navigator.mediaDevices.getSupportedConstraints();let a=!1;if(e){a={noiseSuppression:w.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let t=F.getMicrophones(),n,r;if(Je&&(r=Je.groupId,n=Je.deviceId),typeof e==`string`)r=t.find(t=>t.deviceId===e)?.groupId,n=e;else if(!Je&&F.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:w.videoMinWidth,max:n,ideal:n},height:{min:w.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:w.videoAspectRatio},frameRate:{ideal:i}};let e=F.getCameras(),a,s;if(qe&&(s=qe.groupId,a=qe.deviceId),typeof t==`string`)s=e.find(e=>e.deviceId===t)?.groupId,a=t;else if(!qe&&F.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}),w.videoFacingMode&&(o.facingMode={ideal:w.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 ft{constructor(e,t,n,r){if(super(!1,!0),g(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):this.video={},this.video.cursor=`motion`,this.video.width=e,this.video.height=t,this.video.frameRate=n,this.video.displaySurface=w.displaySurface,F.browserName()===`Safari`){let n=Number(F.browserVersion());n===16?(this.video.width={max:e},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:w.audioShareSystemInclude?`include`:`exclude`,windowAudio:w.audioShareWindowInclude?`include`:`exclude`,controller:this.captureController})}},mt=class e{constructor(){g(this,`_lockId`,Math.round(Math.random()*99998)+1)}busy(){if(e._lockId)throw O.log(b.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)}};g(mt,`_lockId`,0);async function ht(){Ze=!1,Xe=!1,Ve=null;let e={camera:F.getSavedCamera(),microphone:F.getSavedMicrophone(),output:F.getSavedOutput()};await _t(),gt(`devicechange`,e),P.onDeviceChange()}function gt(e,...t){if(ut[e])for(let n of ut[e])n(...t)}async function _t(){return Ve||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!He&&navigator.mediaDevices.addEventListener&&(He=C.debounce(ht,w.enumerateDevicesDelay),navigator.mediaDevices.addEventListener(`devicechange`,He)),!Ue&&je.isSupported()&&(Ue=new je,await Ue.init((e,t)=>{switch(t){case`denied`:case`prompt`:He?.();break}})),Ve=navigator.mediaDevices.enumerateDevices().then(e=>{We=e.filter(e=>e.kind===`videoinput`?(e.label&&(Xe=!0),!0):!1),Ge=e.filter(e=>e.kind===`audioinput`?(e.label?Ze=!0:F.isMobile()&&F.browserName()===`Firefox`&&(Ze=Xe),!0):!1),Ke=e.filter(e=>e.kind===`audiooutput`);let t=qe?.deviceId??Be.get(`videoinput`),n=Je?.deviceId??Be.get(`audioinput`),r=Ye?.deviceId??Be.get(`audiooutput`);return qe=We.find(e=>e.deviceId===t)||null,Je=Ge.find(e=>e.deviceId===n)||null,Ye=Ke.find(e=>e.deviceId===r)||Ke[0]||null,Ve=Promise.resolve(e),e}).catch(()=>(Ve=null,[]))))}async function vt(){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]);it=isNaN(t)?null:t}catch(e){R.warn(`Failed to get OS version`,e)}}function yt(e){if(qe&&Je)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=>{!Je&&e.kind===k.audio?Je=t(F.getMicrophones(),e):!qe&&e.kind===k.video&&(qe=t(F.getCameras(),e))})}async function bt(e,t){R.debug(`Try to get media`,JSON.parse(JSON.stringify(e.getNative()))),F.releaseFirefoxMicrophonePermissionWarmup();let n=(!e.isVideo()||F.hasCameraPermission())&&(!e.isAudio()||F.hasMicrophonePermission());!n&&!t&&P.onPermissionsRequested();let r=new mt;try{r.busy();let t=await navigator.mediaDevices.getUserMedia(e.getNative());return r.free(),n||await ht(),yt(t),t}catch(n){switch(r.free(),R.error(`getUserMedia error`,n),n.name){case`PermissionDeniedError`:case`PermissionDismissedError`:case`NotAllowedError`:case`SecurityError`:case`DOMException`:case`NotFoundError`:t=e.isVideoRequested()?v.CAMERA_PERMISSION:v.MIC_PERMISSION;break;case`OverconstrainedError`:t=v.OVERCONSTRAINED;break;case`TypeError`:t=v.UNKNOWN;break;case`AbortError`:case`NotReadableError`:t=e.isVideoRequested()?v.CAMERA_ACCESS:v.MIC_ACCESS;break;case`Error`:if(n.message===`MediaSource is busy`){t=e.isVideoRequested()?v.CAMERA_ACCESS:v.MIC_ACCESS;break}}if(e.canSimplify())return bt(e.simplify(),t);let i=t||v.UNKNOWN;throw P.onPermissionsError(i,n),i}}async function xt(){if(!(tt||F.browserName()!==`Firefox`||!navigator.mediaDevices?.getUserMedia))try{F.hasMicrophonePermission()||P.onPermissionsRequested(),tt=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(e){R.warn(`Firefox microphone permission warmup failed`,e)}}async function St(e){R.debug(`Try to get screen`,JSON.parse(JSON.stringify(e.getNative())));let t=new mt;try{t.busy();let n=await navigator.mediaDevices.getDisplayMedia(e.getNative()),r=n?.getVideoTracks()[0];if(r){let t=r.getSettings()?.displaySurface;if(R.debug(`Got display media track: ${r.id} (${t})`),r.contentHint=`text`,e.captureController&&(t===`browser`||t===`window`))try{e.captureController.setFocusBehavior(`no-focus-change`)}catch(e){R.warn(`Failed to set focus behavior`,e)}}return n}catch(e){switch(e.name){case`PermissionDeniedError`:case`NotAllowedError`:case`SecurityError`:throw v.SCREEN_PERMISSION;default:throw v.SCREEN_ACCESS}}finally{t.free()}}function Ct(){return at.length||(at=(()=>{let e,t=!1,n=0,r=`0`,i=lt.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return e=/\brv[ :]+(\d+)/g.exec(lt),[`IE`,e&&e[1]||`Unknown`,t,n,r];if(i[1]===`Safari`){if(e=lt.match(/\bEdge\/(\d+)/),e)return[`Edge`,e[1]||`Unknown`,t,n,r];if(e=lt.match(/\bCriOS\/(\d+)/),e)return[`Chrome`,e[1],!0,Number(e[1]),r];if(e=lt.match(/\bFxiOS\/(\d+)/),e)return[`Firefox`,e[1],!1,n,r];if(e=lt.match(/\bYaBrowser\/(\d+)/),e)return[`Yandex`,e[1],!1,n,r];if(e=lt.match(/\bOPT\/(\d+)/),e)return[`Opera`,e[1],!1,n,r]}if(i[1]===`Chrome`){if(t=!0,n=Number(i[2]),e=lt.match(/\bOPR\/(\d+)/),e)return[`Opera`,e[1]||`Unknown`,t,n,r];if(e=lt.match(/\bYaBrowser\/(\d+)/),e)return[`Yandex`,e[1]||`Unknown`,t,n,r];if(e=lt.match(/\bSferum\/((\d+)(?:\.\d+)*)/),e)return[`Sferum`,e[1]||`Unknown`,t,n,r];if(e=lt.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=lt.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),e&&e[2]!==void 0&&(r=e[2]),[i[2]?i[1]:ct,e&&e[1]||i[2]||st,t,n,r]})()),at}var F;(function(e){async function t(){await _t(),await vt()}e.init=t;function n(){return We}e.getCameras=n;function r(){return Ge}e.getMicrophones=r;function i(){return Ke}e.getOutput=i;function a(){return We.length>0}e.hasCamera=a;function o(){return Ge.length>0}e.hasMicrophone=o;function s(){return qe}e.getSavedCamera=s;function c(){return Je}e.getSavedMicrophone=c;function l(){return Ye}e.getSavedOutput=l;function u(){return w.videoFacingMode}e.getVideoFacingMode=u;function d(){return Xe}e.hasCameraPermission=d;function f(){return Ze}e.hasMicrophonePermission=f;function p(){return Ue?.getPermissionState(`microphone`)??null}e.getMicrophonePermissionState=p;function m(e=!1){return f()?a()&&e?d():!0:!1}e.hasPermissions=m;function h(){tt&&(Ce(tt),tt=null)}e.releaseFirefoxMicrophonePermissionWarmup=h;async function ee(e=!1,t=!0,n=!0){!e&&!t?await xt():F.releaseFirefoxMicrophonePermissionWarmup();let r=o()&&t,i=a()&&e,s;if(!r&&!i)s=new MediaStream;else try{s=await bt(new ft(r,i))}catch{s=new MediaStream}return!s.getVideoTracks().length&&n&&s.addTrack(F.getBlackMediaTrack()),!s.getAudioTracks().length&&n&&s.addTrack(F.getSilentMediaTrack()),s}e.getUserMedia=ee;async function te(e,t){return St(new pt(e&&!w.consumerFastScreenShare?w.fastScreenShareWidth:window.screen.width,e&&!w.consumerFastScreenShare?w.fastScreenShareHeight:window.screen.height,w.getScreenFrameRate(e),t))}e.getScreenMedia=te;async function g(e=!1,t){return bt(new ft(!1,!0,e?w.videoEffectMaxWidth:w.videoMaxWidth,e?w.videoEffectMaxHeight:w.videoMaxHeight,t))}e._getUserVideo=g;async function _(e,t){let n=t?.width||w.videoMaxWidth,r=t?.height||w.videoMaxHeight;return bt(new ft(!1,e||!0,n,r))}e.getUserVideo=_;async function v(e){return bt(new ft(e||!0,!1))}e.getUserAudio=v;async function y(e,t){let[n]=e.getVideoTracks();if(!n)throw Error(`Video track not found in stream`);return Te(n,t)}e.setResolution=y;async function b(e,t){let n=(await _t()).find(n=>n.kind===e&&n.deviceId===t);return n?(e===`videoinput`?qe=n:e===`audioinput`?Je=n:e===`audiooutput`&&(Ye=n),Be.set(e,t),n):null}e._saveDeviceId=b;function x(){if(!et||et.readyState===`ended`){let e=F.getAudioContext(),t=e.createMediaStreamDestination(),n=e.createGain();n.gain.value=1e-5,n.connect(t),n.connect(e.destination);let r=e.createOscillator();r.type=`sine`,r.frequency.value=0,r.connect(n),r.start(),et=t.stream.getAudioTracks()[0]}return Object.assign(et.clone(),{enabled:!1})}e.getSilentMediaTrack=x;function S(e=w.videoMinWidth,t=w.videoMinHeight){$e||($e=document.createElement(`canvas`)),$e.width=e,$e.height=t;let n=$e.getContext(`2d`);return n.rect(0,0,e,t),n.fillStyle=`black`,n.fill(),(!Qe||Qe.readyState===`ended`)&&(Qe=$e.captureStream(w.videoFrameRate).getVideoTracks()[0]),Object.assign(Qe.clone(),{enabled:!1})}e.getBlackMediaTrack=S;function ne(){if(pe()===`Edge`&&Number(me())<70)return!1;try{let e=window;return`mediaDevices`in e.navigator&&`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 navigator&&!0||!1}catch{return!1}}e.isBrowserSupported=ne;function re(){return!!navigator.mediaDevices.getDisplayMedia}e.isScreenCapturingSupported=re;function ie(){let e=F.browserName()===`Safari`&&F.browserVersion()===`15`&&F.browserSubVersion()===`1`,t=F.browserName()===`Opera`,n=F.browserName()===`Yandex`;return e||t||n}e.isBrokenH264Decoder=ie;function ae(){return F.browserName()===`Yandex`&&F.os()===`Windows`||w.simulcast}e.isBrokenVP9Encoder=ae;function oe(){let e=F.browserName()===`Safari`&&Number(F.browserVersion())===17&&[4,5,6].includes(Number(F.browserSubVersion())),t=F.os()===`Windows`&&F.osVersion()===10;return e||t}e.isBrokenVP9Decoder=oe;function se(){return F.browserName()===`Firefox`&&Number(F.browserVersion())<60}e.isOldDataChannelDescription=se;function ce(){return!(F.baseChromeVersion()&&F.isMobile())}e.canPreferH264=ce;function le(){return!(F.browserName()===`Firefox`||F.browserName()===`Safari`)}e.isSimulcastSupportedByBrowser=le;function ue(){return rt||(rt=(()=>{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(lt))return t;return`Unknown`})()),rt}e.os=ue;function de(){return it}e.osVersion=de;function fe(){return nt===null&&(nt=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(st)),nt}e.isMobile=fe;function pe(){return Ct()[0]}e.browserName=pe;function me(){return Ct()[1]}e.browserVersion=me;function he(){return Ct()[3]}e.baseChromeVersion=he;function C(){return ot||(ot=new(window.AudioContext||window.webkitAudioContext)),ot.resume().catch(()=>{R.warn(`Failed to resume AudioContext`)}),ot}e.getAudioContext=C;function ge(){return Ct()[4]}e.browserSubVersion=ge;function _e(){return F.baseChromeVersion()>=105&&!F.isMobile()}e.isAudioShareSupported=_e;function ve(e,t){ut[e]||(ut[e]=[]),ut[e].push(t)}e.addEventListener=ve;function ye(e,t){if(ut[e])if(!t)delete ut[e];else{let n=ut[e].indexOf(t);n>-1&&ut[e].splice(n,1)}}e.removeEventListener=ye})(F||(F={}));var I=F,wt=class e{static get startTime(){return e._list[0]?.t||0}static get endTime(){let t=e._list;return t[t.length-1]?.t||0}static startSession(){e._list=[]}static get conversationId(){return e._conversationId}static set conversationId(t){e._conversationId=t}static add(t){e._list.push(t)}static _createContextLogs(){let e=[[`Calls SDK ${w.sdkVersion}`,w.toJSON()],[`UserAgent:`,navigator.userAgent],[`Screen resolution:`,`${window.screen.width}x${window.screen.height}`],[`Permissions:`,`Camera: ${I.hasCameraPermission()}, Mic: ${I.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:`LOG`,d:e}))}static collectLogs(){let t=e._list;return t.length===0?[]:[...e._createContextLogs(),...t]}};g(wt,`_list`,[]),g(wt,`_conversationId`,null);var Tt=class{constructor(){g(this,`_items`,[])}get length(){return this._items.length}push(...e){this._items.push(...e)}merge(e){this._items.push(...e._items)}shift(){return this._items.shift()||null}bisect(){let e=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(e)}head(){return this._items[0]||null}tail(){let e=this._items.length;return e?this._items[e-1]:null}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(e,t)=>t instanceof Error?String(t):t):``}},Et=2*1024*1024,Dt=512*1024,Ot=100*1024,kt=5,At=`_okcls_logs_session_`,jt=3e4,Mt=class{constructor(){g(this,`_items`,[]),g(this,`_itemsSize`,0),g(this,`_storageSize`,Et);try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(At)!==0)continue;let n=e.getItem(t);if(!n){Ft(t);continue}let r=Pt(n);this.add(t,r)}}catch(e){console.error(`Storage is blocked`,e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(Ot)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=Math.min(e,this._storageSize,Et)}add(e,t){let n=parseInt(e.replace(At,``),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:n})}deleteOldestItem(){let e=this._items.shift();e&&(Ft(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>Et||this.length>kt-1||this.size+e>this.available);)this.deleteOldestItem()}};function Nt(){return`${At}${Date.now()}`}function Pt(e){return new Blob([e]).size}function Ft(e){try{window.localStorage.removeItem(e)}catch(e){console.error(`Failed to remove log from storage`,e)}}function It(){let e=Ht.toString();if(!L.available||!e)return;let t=Pt(e);if(t>Dt){Ht.bisect(),It();return}L.cleanup(Ot+t);try{window.localStorage.setItem(Ut,e)}catch(e){if(console.warn(`Failed to write log to storage`,e),L.storageSize=L.size+t,L.cleanup(Ot+t),L.available>=Ot+t){It();return}if(t>Ot){Ht.bisect(),It();return}L.storageSize=0;return}t>Dt&&(L.add(Ut,t),Ut=Nt(),Ht.clear(),L.cleanup(Ot))}function Lt(){!L.available||!Ht.length||It()}function Rt(e=!1){let t=[];try{let e=window.localStorage;for(let n of L.items){let r=e.getItem(n.key);t.push(r)}let n=Ht.toString();n&&t.push(n)}catch(e){console.error(`Storage is blocked`,e)}let n=`[${t.join(`,`)}]`;if(e)return n;let r=`logs_${Date.now()}.json`;return zt(n,r),r}function zt(e,t){let n=document.createElement(`a`),r=new Blob([e],{type:`text/json`});n.href=URL.createObjectURL(r),n.download=t,n.click()}function Bt(e,t){if(!L.available)return;let n=new Date,r={t:n.getTime(),l:e,d:t,h:n.toLocaleString(`ru-RU`,{dateStyle:`short`,timeStyle:`long`})};Ht.push(r),wt.add(r),Wt||(Wt=window.setTimeout(()=>{Wt=null,Lt()},jt))}function Vt(){L||(L=new Mt,Ht=new Tt,Ut=Nt(),window.addEventListener(`beforeunload`,Lt))}var L,Ht,Ut,Wt=null;window.__VKCallsSDKLogs__=(e=!1)=>(L||Vt(),Lt(),Rt(e));var Gt=function(e){return e.DEBUG=`DEBUG`,e.LOG=`LOG`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),Kt;(function(e){let t=`📞`,n=(e,...t)=>{P.onDebugMessage(e,...t)},r=!1,i=(e,t)=>(...n)=>{e(...n),Bt(t,n)},a=console.debug.bind(console,t),o=console.log.bind(console,t),s=console.warn.bind(console,t),c=console.error.bind(console,t),l=n.bind(null,`DEBUG`),u=n.bind(null,`LOG`),d=n.bind(null,`WARN`),f=n.bind(null,`ERROR`),p=l,m=u,h=d,ee=f;function te(...e){p(...e)}e.debug=te;function g(...e){m(...e)}e.log=g;function _(...e){h(...e)}e.warn=_;function v(...e){ee(...e)}e.error=v;function y(){return r}e.enabled=y;function b(e){r=e,w.debugLog&&Vt(),e?(p=w.debugLog?i(a,`DEBUG`):a,m=w.debugLog?i(o,`LOG`):o,h=w.debugLog?i(s,`WARN`):s,ee=w.debugLog?i(c,`ERROR`):c):(p=w.debugLog?i(l,`DEBUG`):l,m=w.debugLog?i(u,`LOG`):u,h=w.debugLog?i(d,`WARN`):d,ee=w.debugLog?i(f,`ERROR`):f)}e.toggle=b;function x(e,...t){switch(e){case`DEBUG`:te(...t);break;case`LOG`:g(...t);break;case`WARN`:_(...t);break;case`ERROR`:v(...t);break}}e.send=x;function S(e,...t){}e.test=S})(Kt||(Kt={}));var R=Kt,z=new class{constructor(){g(this,`_conversations`,new Map),g(this,`_activeId`,null),g(this,`_mutex`,!1)}add(e){if(this._conversations.has(e.id))throw Error(`CallRegistry: conversation ${e.id} already exists`);this._conversations.set(e.id,e)}remove(e){if(!this._mutex&&(e&&this._conversations.delete(e),this._activeId===e))if(this._conversations.size>0){let[e]=[...this._conversations][0];try{this.setActive(e)}catch{this._activeId=null}}else this._activeId=null}get(e){return this._conversations.get(e)}getActive(){return this._activeId?this._conversations.get(this._activeId)??null:null}getActiveId(){return this._activeId}has(e){return this._conversations.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();if(t)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,P.onCallActive(e));let n=this._conversations.get(e);if(n&&n?.isCallHeld)try{await n.hold(!1)}catch(e){throw R.error(`Can't hold next active, error: ${e}`),Error(`Cannot switch call: hold failed`)}}finally{this._mutex=!1}}}clear(){this._conversations.clear(),this._activeId=null}},qt=class extends _{constructor(...e){super(...e),g(this,`_abortSignal`,void 0)}setAbortSignal(e){this._abortSignal=e}get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setWebTransportEndpoint(e){}setConversationId(e){}readyToSend(e=!0){}cleanup(){}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 Jt(e){return e.stopStream}function Yt(e){return e.keyFrameRequested}function Xt(e){if(Jt(e))return`ss`;if(Yt(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}({}),Zt=`s`,Qt=`m`;function $t(e){return e.participantId+(e.mediaType?`:`+Zt+e.mediaType:``)+(e.streamName?`:`+Qt+e.streamName:``)}function en(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 Zt:r=tn(n.slice(1));break;case Qt: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:C.compose(n,a),mediaType:r,streamName:i}}function tn(e){for(let t of Object.keys(V))if(t===e)return V[t];return null}function nn(){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 an(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 on=0,sn=1,cn=2,ln=3,un=4,dn=5,fn=6,pn=7,mn=0,hn=1,gn=2,_n=0,vn=0,yn=0,bn=1,xn=class{constructor(){g(this,`participantIdRegistry`,null)}setParticipantIdRegistry(e){this.participantIdRegistry=e}serializeUpdateDisplayLayout(e,t){let n=nn();l.Int.enc(n,on),l.Int.enc(n,_n),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=nn();if(this.writeStreamDesc(t,i),Jt(r))l.Int.enc(i,hn);else if(Yt(r))l.Int.enc(i,gn);else if(l.Int.enc(i,mn),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,yn);break;case`cn`:l.Int.enc(i,bn);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=nn();return l.Int.enc(n,sn),l.Int.enc(n,_n),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=nn();return l.Int.enc(n,cn),l.Int.enc(n,_n),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=nn();return l.Int.enc(n,ln),l.Int.enc(n,_n),l.Int.enc(n,e),l.Bool.enc(n,t.request),n.ui8array().buffer}serializeNetworkStatReport(e,t){let n=nn();return l.Int.enc(n,un),l.Int.enc(n,_n),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=nn();return l.Int.enc(n,dn),l.Int.enc(n,_n),l.Int.enc(n,e),l.Bool.enc(n,t.enabled),n.ui8array().buffer}serializeEnableVideoSuspendSuggest(e,t){let n=nn();return l.Int.enc(n,fn),l.Int.enc(n,_n),l.Int.enc(n,e),l.Bool.enc(n,t.enabled),n.ui8array().buffer}serializeChangeSimulcast(e,t){let n=nn();l.Int.enc(n,pn),l.Int.enc(n,_n),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?an(`arrayBuffer`in Blob.prototype?await e.arrayBuffer():await de(e)):an(e);let n=l.Int.dec(t),r=l.Int.dec(t);if(r!==_n){R.warn(`Unsupported version for command type: `+n+`, version `+r);return}if(l.Int.dec(t)!==vn){R.warn(`Error code: `+n+`received for command type: `+n+`, version `+r);return}switch(n){case on:return this.deserializeUpdateDisplayLayoutResponse(t);case sn:return this.deserializeReportPerfStatResponse(t);default:R.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=an(e),n=l.Any.dec(t);if(typeof n==`string`)r[n]=l.Int.dec(t);else{let e=n,i=$t(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_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.CALL_START=`call_start`,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}(H||{}),Sn=1e3;function U(e,t,n=0){return t in e&&e[t]?e[t]:n}function Cn(...e){return t=>{for(let n of e)if(n(t))return!0;return!1}}function wn(e,t){return n=>n[e]===t}function Tn(e){return(t,n)=>n[e]-t[e]}function En(e,t){return t.reduce((t,n)=>(t[n[e]]=n,t),{})}function Dn(e){let t={},n=[];for(let r of e)t[r.id]||(t[r.id]=!0,n.push(r));return n}function On(e){return Object.keys(e).filter(t=>e[t]!==void 0).map(t=>[t,e[t]]).reduce((e,t)=>(e[t[0]]=C.isObject(t[1])?On(t[1]):t[1],e),{})}function kn(e){let t=[];for(let n of e)n.forEach(e=>t.push(e));return t}async function An(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(kn).then(Dn)}function jn(e){let t=e.filter(wn(`type`,`candidate-pair`)).sort(Tn(`priority`)).find(Cn(wn(`nominated`,!0),wn(`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(wn(`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(wn(`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}}),On(n)}function Mn(e,t,n=!1){let r=En(`id`,e),i=n?e.filter(Cn(wn(`type`,`remote-inbound-rtp`))):e.filter(Cn(wn(`type`,`inbound-rtp`),wn(`type`,`outbound-rtp`)));return I.browserName()===`Firefox`&&(i=Object.values(i.reduce((e,t)=>{if(!e[t.ssrc])e[t.ssrc]=t;else{let n=Object.assign({},e[t.ssrc],t),r=e[t.ssrc].isRemote?t:e[t.ssrc];n.id=r.id,n.type=r.type,delete n.isRemote,delete n.remoteId,e[n.ssrc]=n}return e},{}))),i.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 On(c)}).filter(e=>!!e)}function Nn(e,t,n=!1){if(!t||!t.rtps||!e.rtps)return e;let r,i;n&&(r=En(`ssrc`,e?.remoteRtps||[]),i=En(`ssrc`,t?.remoteRtps||[]));let a=En(`ssrc`,e.rtps),o=En(`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 Pn(e,t,n={},r=!1){let i=await An(e),a={timestamp:Date.now(),transport:jn(i),rtps:Mn(i,n)};return r&&(a.remoteRtps=Mn(i,n,!0)),t?Nn(a,t,r):(await C.delay(Sn),Pn(e,a,n,r))}function Fn(e){performance.clearMarks(e),performance.mark(e)}function In(e){performance.clearMarks(e)}function Ln(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 Rn(e){return`${H.SCREENSHARE_FIRST_FRAME}_${zn(e)}`}function zn(e){return typeof e==`string`?e:JSON.stringify(e)}var W={distinctById:Dn,rtcStatsToArray:kn,extractTransport:jn,extractRtps:Mn,delta:Nn,collectStats:Pn,setMark:Fn,clearMark:In,measureMark:Ln,getMarkNameScreenshareFirstFrame:Rn},Bn=class e{constructor(){g(this,`_eventualLogs`,new Set)}static create(){e._instance=new e}static logCallStat(t){if(e._instance?._eventualLogs.size){for(let n of e._instance._eventualLogs)Object.assign(n,{call_topology:t.call_topology,local_address:t.local_address,local_connection_type:t.local_connection_type,network_type:t.network_type,remote_address:t.remote_address,remote_connection_type:t.remote_connection_type,transport:t.transport}),O.logClientStats(n);e._instance._eventualLogs.clear()}O.logClientStats(t)}static logEventualStat(t){t.value===void 0&&(t.value=W.measureMark(t.name)),t.value!==null&&e._instance?._eventualLogs.add(t)}static destroy(){e._instance?._destroy(),e._instance=null}_destroy(){this._eventualLogs.clear()}};g(Bn,`_instance`,null);var Vn=function(e){return e.WEBSOCKET=`ws`,e.WEBTRANSPORT=`wt`,e}({}),Hn=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}({}),Un={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}},Wn=class{constructor(e){if(g(this,`q`,void 0),g(this,`inits`,[]),g(this,`n`,[1,2,3,4,5]),g(this,`np`,[1,1,1,1,1]),g(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]}},Gn=class{constructor(){g(this,`n`,0),g(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}},Kn=class{constructor(){g(this,`count`,0),g(this,`minVal`,1/0),g(this,`maxVal`,-1/0),g(this,`mean`,new Gn),g(this,`p50`,new Wn(.5)),g(this,`p95`,new Wn(.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}},qn=function(e){return e.NOTIFICATION=`NOTIFICATION`,e.FAILED=`FAILED`,e.RECONNECT=`RECONNECT`,e}(qn||{}),G=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.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}(G||{}),Jn=function(e){return e.producerNotification=`producerNotification`,e.producerCommand=`producerCommand`,e.consumerScreenShare=`consumerScreenShare`,e.producerScreenShare=`producerScreenShare`,e.asr=`asr`,e.animoji=`animoji`,e}(Jn||{}),{isObject:Yn,isObjectsEquals:Xn}=C;function Zn(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||Yn(e.bitrates)&&Yn(t.bitrates)&&!Xn(e.bitrates,t.bitrates,!0)?!1:e.bitrates===t.bitrates}var Qn=function(e){return e.L1T1=`L1T1`,e.L1T2=`L1T2`,e.L1T3=`L1T3`,e}({});function $n(e,t){return!(!Zn(e.camera,t.camera)||!Zn(e.screenSharing,t.screenSharing)||!Zn(e.fastScreenSharing,t.fastScreenSharing))}function er(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 tr(){return{camera:null,screenSharing:null,fastScreenSharing:null}}var nr=class e{constructor(){g(this,`_codecUsages`,new Map),g(this,`getCurrentTransportTopology`,()=>void 0)}static create(t){let n=new e;n.getCurrentTransportTopology=t,e._instance=n}static reportUsage(t){let n=e._instance,r=n?.getCurrentTransportTopology();if(!n||!r)return;let i=t.rtps.filter(e=>e.type===`outbound-rtp`&&!e.mid?.endsWith(`s`));w.simulcast&&(i=i.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},[])),i.forEach(e=>{let t=e.kind,i=e.mimeType;if((t===`audio`||t===`video`)&&i){let a=[i,`encoder`,e.encoderImplementation].filter(Boolean).join(`/`);n.saveUsage({kind:t,codecName:a,totalEncodeTime:(e.totalEncodeTime??0)*1e3,audioCodecParams:e.sdpFmtpLine,topology:r})}})}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:e.totalEncodeTime,call_topology:e.topology===J.DIRECT?`D`:`S`};e.audioCodecParams&&(t.string_value=e.audioCodecParams),O.logClientStats(t)}static destroy(){e._instance?._destroy(),e._instance=null}_destroy(){this._codecUsages.forEach(e=>{this.report(e)}),this._codecUsages.clear()}};g(nr,`_instance`,null);var rr=class extends _{constructor(e,t){super(),g(this,`_signaling`,void 0),g(this,`_mediaSource`,void 0),g(this,`_state`,q.IDLE),g(this,`_pc`,null),this._signaling=e,this._mediaSource=t}getState(){return this._state||q.IDLE}},ir=`videochat-epi`,ar=5e3,or=500,sr=class extends _{constructor(e,t,n=!1){super(),g(this,`_previousPerfStatReportTimestamp`,0),g(this,`_previousNetworkStatReportTimestamp`,Date.now()),g(this,`_previousCallStatReportTimestamp`,Date.now()),g(this,`_previousCallStatReport`,null),g(this,`_screenShareStats`,[]),g(this,`_signaling`,void 0),g(this,`_directTopology`,void 0),g(this,`_handleScreenSharingStat`,e=>{this._screenShareStats.push(e)}),g(this,`_handleTransportStateChanged`,e=>{(this._directTopology&&e===q.CONNECTED||!this._directTopology&&e===q.OPENED)&&(this._previousNetworkStatReportTimestamp=Date.now(),this._previousCallStatReportTimestamp=Date.now())}),this._signaling=t,this._directTopology=n,this.subscribe(e,K.REMOTE_DATA_STATS,this._handleStats.bind(this)),this.subscribe(e,K.SCREEN_SHARING_STAT,this._handleScreenSharingStat.bind(this)),this.subscribe(e,K.STATE_CHANGED,this._handleTransportStateChanged.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(ir)||``,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&&w.perfStatReportEnabled&&this._previousPerfStatReportTimestamp+ar<=t&&(await this.reportPerfStats(e),this._previousPerfStatReportTimestamp=t);let n=e.outbound.transport.local?.protocol===`tcp`;!this._directTopology&&n&&this._previousNetworkStatReportTimestamp+or<=t&&(await this.reportNetworkStats(e),this._previousNetworkStatReportTimestamp=t),w.callStatReportEnabled&&this._previousCallStatReportTimestamp+w.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(ir,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,packets_lost_video:0,packets_sent_video:0,packets_lost_audio:0,packets_sent_audio: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:lr(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:lr(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.packets_sent_video+=t.packetsSent):e.packets_sent_audio+=t.packetsSent,e),t),e.remoteInbound.rtps.reduce((e,t)=>(t.kind===`video`?e.packets_lost_video+=t.packetsLost:e.packets_lost_audio+=t.packetsLost,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(w.simulcast&&(i.is_simulcast=!0),navigator.hardwareConcurrency&&(i.cpu_hardware_concurrency=navigator.hardwareConcurrency),n&&!ur(t.jitter_video)&&(i.jitter_video=Math.round(t.jitter_video)),r&&!ur(t.jitter_audio)&&(i.jitter_audio=Math.round(t.jitter_audio)),n&&!ur(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&&!ur(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=dr(n/e*1e3),i.removed_audio_samples_for_acceleration=dr(r/e*1e3),i.concealed_audio_samples=dr(a/e*1e3),i.concealed_silent_audio_samples=dr(o/e*1e3),i.concealment_audio_avg_size=dr(a/s),i.total_audio_energy=t.total_audio_energy}cr(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),cr(t,`remote_address`,`remote_connection_type`)&&(i.remote_address=t.remote_address,i.remote_connection_type=t.remote_connection_type);let a=Math.max(0,t.packets_sent_video-this._previousCallStatReport.packets_sent_video),o=Math.max(0,t.packets_sent_audio-this._previousCallStatReport.packets_sent_audio);a>0&&(i.video_loss=dr(Math.max(0,t.packets_lost_video-this._previousCallStatReport.packets_lost_video)/a*100)),o>0&&(i.audio_loss=dr(Math.max(0,t.packets_lost_audio-this._previousCallStatReport.packets_lost_audio)/o*100)),Bn.logCallStat(i),w.enableLogPerfStatReport&&R.log(`Sent call stats`,i),this._previousCallStatReport=t}};function cr(e,...t){for(let n of t)if(!Object.hasOwn(e,n)||e[n]===void 0)return!1;return!0}function lr(e,t=!1){if(e?.address)return e.address+(t?`:${e.port}`:``)}function ur(e){return e===void 0}function dr(e){return Number.isNaN(e)?0:e}var fr=class{constructor(e,t=null){g(this,`weightUp`,void 0),g(this,`weightDown`,void 0),g(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}},pr=.25,mr=.35,hr=85,gr=.1,_r=1.5,vr=.1,yr=1,br=.6,xr=.3,Sr=class extends _{constructor(e){super(),g(this,`_signaling`,void 0),g(this,`_localNetworkStat`,void 0),g(this,`_remoteNetworkStat`,void 0),g(this,`_lastNetworkStat`,void 0),g(this,`_networkLimits`,{badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}}),g(this,`_lastStatSentTimestamp`,0),g(this,`_currentState`,`good`),this._signaling=e,this._localNetworkStat={rtt:new fr(pr,pr),loss:new fr(mr,mr),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)/hr);for(let e=0;e<r;e++)n*=1-gr;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)/_r);for(let e=0;e<r;e++)n*=1-vr;return n}_calcBitrateRating(e,t){if(!e||!t)return 1;let n=1-(1-Math.min(e,t)/Math.max(e,t))*yr;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>=br?`good`:e>=xr?`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>w.networkStatisticsInterval)&&(this._lastStatSentTimestamp=a,this._signaling.customData({sdk:Object.assign({type:`bad-net`},i)},null).catch(e=>{R.warn(`Unable to send [bad-net]`,e)})),this._currentState=c,this._triggerEvent(K.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}},Cr=30*1e3,wr=class e extends rr{constructor(e,t,n,r,i){super(n,r),g(this,`_participantId`,void 0),g(this,`_isMaster`,void 0),g(this,`_remoteSDP`,{}),g(this,`_remoteCandidates`,{}),g(this,`_lastRemoteSDP`,null),g(this,`_animojiDataChannel`,null),g(this,`_animojiReceiver`,null),g(this,`_animojiSender`,null),g(this,`_remoteAnimojiVersion`,1),g(this,`_isOpen`,!1),g(this,`_remotePeerId`,null),g(this,`_statInterval`,null),g(this,`_settingsInterval`,null),g(this,`_failedOnCreate`,null),g(this,`_remoteStream`,null),g(this,`_iceRestartTimeout`,null),g(this,`_reconnectionTimeout`,null),g(this,`_reconnectionPrevented`,!1),g(this,`_lastStat`,void 0),g(this,`_fingerprint`,null),g(this,`_neverConnected`,!0),g(this,`_serverSettings`,void 0),g(this,`_prevConsumerSettings`,{}),g(this,`_networkLimitsForVideo`,{bad:{loss:4,rtt:1e3},good:{loss:2,rtt:700}}),g(this,`_videoMaxDimensionsForNet`,{worst:320,bad:640,good:1280}),g(this,`_lastVideoMaxDimension`,this._videoMaxDimensionsForNet.good),g(this,`_lastBadConnection`,0),g(this,`_perfStatReporter`,void 0),g(this,`_directStatReporter`,void 0),this._participantId=e,this._isMaster=t,this._serverSettings=i,this._perfStatReporter=new sr(this,n,!0),this._directStatReporter=new Sr(n),this.subscribe(this._signaling,qn.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Oe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Oe.SOURCE_CHANGED,this._applySettings.bind(this)),this.subscribe(this._directStatReporter,K.NETWORK_STATUS,this._onNetworkStatus.bind(this));try{this._pc=new RTCPeerConnection({iceServers:w.iceServers,iceTransportPolicy:w.forceRelayPolicy?`relay`:`all`})}catch(e){R.error(`Failed to create RTCPeerConnection:`,e),this.close(e);return}if(this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},w.vmoji&&this._createDataChannel(this._pc,Jn.animoji,e=>{this._animojiDataChannel=e,this._animojiDataChannel.binaryType=`arraybuffer`,this._animojiReceiver?.setDataChannel(this._animojiDataChannel),this._animojiSender?.setDataChannel(this._animojiDataChannel)}),this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(e){O.log(b.ERROR,`addTrack-direct`),R.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[q.IDLE,q.CLOSED,q.FAILED].includes(this.getState())}async open(e=null){if(this._isOpen){R.warn(`DirectTransport: Already opened`,{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(R.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){O.log(b.ERROR,`addTrack-direct`),R.error(`DirectTransport: Unable to add media source tracks`,e,{participantId:this._participantId}),this.close(e);return}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){$n(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}setAnimojiTransport(e,t){if(w.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._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(e=>{e.stop(),this._triggerEvent(K.REMOTE_TRACK_REMOVED,this._remoteStream,e)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._animojiDataChannel&&(this._animojiDataChannel.onopen=null,this._animojiDataChannel.onmessage=null,this._animojiDataChannel.onerror=null,this._animojiDataChannel.close()),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),this._onNetworkStatus(1),this.unsubscribe(),e?(R.error(`DirectTransport: Closed`,e,{participantId:this._participantId}),this._setState(q.FAILED)):(R.debug(`DirectTransport: Closed`,{participantId:this._participantId}),this._setState(q.CLOSED)),this._triggerEvent(K.PEER_CONNECTION_CLOSED))}_setState(e){this._state!==e&&(R.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(K.STATE_CHANGED,e))}_onSignalingNotification(e){switch(e.notification){case G.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case G.SETTINGS_UPDATE:this._directStatReporter.updateSettings(e.settings);break;case G.CUSTOM_DATA:Object.hasOwn(e.data,`sdk`)&&this._directStatReporter.reportRemote(e.data?.sdk);break}}_handleTransmittedData(e){let t=e.data,n=C.getPeerIdString(e.peerId);C.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){R.debug(`Add remote ice candidate`,{participantId:this._participantId,candidate:t});try{await this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(e){throw O.log(b.ERROR,`addIceCandidate-direct`),R.error(`Unable to add remote ice candidate`,e,{participantId:this._participantId,candidate:t}),e}}else R.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]){R.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),R.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 O.log(b.ERROR,`setRemoteDescription-direct`),R.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,w.vmojiOptions?.protocolVersion||1);this._animojiSender?.setProtocolVersion(t)}_onAddTrack(e){R.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(K.REMOTE_TRACK_REMOVED,this._remoteStream,e.track)}),this._triggerEvent(K.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}async _handleIceCandidate(e){e.candidate&&this._signaling.ready&&(R.debug(`Local ice candidate`,{participantId:this._participantId,candidate:e.candidate}),await this._signaling.sendCandidate(this._participantId,e.candidate))}_onSignalingStateChange(){R.debug(`DirectTransport: Signaling state changed to ${this._pc?.signalingState}`,{participantId:this._participantId});let e={animojiVersion:w.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(R.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`:I.browserName()===`Safari`&&this._pc?.connectionState!==`connected`&&this._markConnected();break}}_markConnected(){this._neverConnected=!1,this._setState(q.CONNECTED),this._stopReconnection(),this._pc&&C.getPeerConnectionHostInfo(this._pc).then(e=>{e?.local&&(O.log(b.ICE_CONNECTION_TYPE,e.local.type),R.debug(`Selected ICE candidates`,e))}),this._startStatInterval()}_onConnectionStateChange(){switch(R.debug(`DirectTransport: Connection state changed to ${this._pc?.connectionState}`,{participantId:this._participantId}),O.log(b.ICE_CONNECTION_STATE,this._pc?.connectionState),this._pc?.connectionState){case`connected`:this._markConnected();break;case`failed`:case`disconnected`:this._reconnectionPrevented?this.close(Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(q.RECONNECTING),this._startReconnection());break;case`closed`:this.close(Error(`Ice connection closed`));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(R.log(`Waiting for reconnection...`,{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},w.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(R.log(`Switch topology DIRECT to SERVER`,{participantId:this._participantId}),this._signaling.switchTopology(J.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(O.log(b.ICE_RESTART),R.log(`Ice restart`,{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):R.debug(`Waiting for ice restart...`,{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,R.error(`Ice restart failed`,{participantId:this._participantId}),O.log(b.ERROR,`iceRestart-direct`),this._requestTopologySwitch()},w.iceRestartWaitTime)}async _createOffer(t){let n={iceRestart:t,offerToReceiveAudio:!0,offerToReceiveVideo:!0};R.debug(`Create offer`,{participantId:this._participantId,options:n});let r;try{r=await this._pc?.createOffer(n),R.debug(`Created offer`,{participantId:this._participantId,offer:r}),r=e._patchLocalDescription(r)}catch(e){throw R.error(`Unable to create offer`,e,{participantId:this._participantId}),O.log(b.ERROR,`createOffer-direct`),e}try{return R.debug(`Set local description`,{participantId:this._participantId,offer:r}),this._calcFingerprint(r.sdp),await this._pc?.setLocalDescription(r),r}catch(e){throw R.error(`Unable to set local description`,e,{participantId:this._participantId}),O.log(b.ERROR,`setLocalDescription-direct`),e}}async _createAnswer(){R.debug(`Create answer`,{participantId:this._participantId});let t;try{t=await this._pc?.createAnswer(),R.debug(`Created answer`,{participantId:this._participantId,answer:t}),t=e._patchLocalDescription(t)}catch(e){throw R.error(`Unable to create answer`,e,{participantId:this._participantId}),O.log(b.ERROR,`createAnswer-direct`),e}try{return R.debug(`Set local description`,{participantId:this._participantId,answer:t}),this._calcFingerprint(t.sdp),await this._pc?.setLocalDescription(t),t}catch(e){throw R.error(`Unable to set local description`,e,{participantId:this._participantId}),O.log(b.ERROR,`setLocalDescription-direct`),e}}static _patchLocalDescription(e){let t=!!I.baseChromeVersion();return e.sdp=C.patchLocalSDP(e.sdp,w.preferH264&&I.canPreferH264(),I.isBrokenH264Decoder(),w.preferVP9,t&&w.audioNack),e}static _patchRemoteDescription(e){return e.sdp=C.patchRemoteSDP(e.sdp,!1,!1,!1,w.preferVP9,I.isBrokenVP9Encoder(),I.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=>{R.error(`DirectTransport: Unable to replace track`,e,{participantId:this._participantId}),O.log(b.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,nr.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(K.REMOTE_DATA_STATS,n),this._statInterval=window.setTimeout(e,w.statisticsInterval)})};this._statInterval=window.setTimeout(e,w.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:I.browserName()===`Firefox`?`transmission`:`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 R.warn(`Failed to get encodingInfo`,a,e),!1}}async _checkPPTNetwork(e){if(!w.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=Qn.L1T1;if(r?(this._lastBadConnection=Date.now(),i?(a=this._videoMaxDimensionsForNet.bad,o=Qn.L1T2):(a=this._videoMaxDimensionsForNet.worst,o=Qn.L1T3)):n&&(a=this._videoMaxDimensionsForNet.good,o=Qn.L1T1),!(a<this._lastVideoMaxDimension||Date.now()-this._lastBadConnection>Cr)||this._lastVideoMaxDimension===a)return;let s=this._serverSettings.camera;if(!s||!await this._isSVCSupported(e,o))return;R.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(K.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=C.sdpFingerprint(e);if(t===null){R.warn(`Fingerprint calculation is unsupported`);return}this._fingerprint===null?this._fingerprint=t:(P.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=C.applySettings(this._pc,e,this._prevConsumerSettings))}_createDataChannel(e,t,n){R.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{negotiated:!0,id:1});r.onopen=()=>{let e=r.readyState;e===`open`?(R.debug(`[${t}] data channel opened`),r.onerror=e=>{R.error(`[${t}] data channel error`,e)},n(r)):R.error(`[${t}] data channel open failed, state [${e}]`)}}},Tr=function(e){return e.AUDIO_MIX=`audio-mix`,e.PARTICIPANT_AGNOSTIC_TRACK_PREFIX=`pat`,e.TRANSPARENT_AUDIO_TRACK_PREFIX=`ta`,e}({}),Er;(function(e){function t(){return{estimatedPerformanceIndex:sr.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:8,producerCommandDataChannelVersion:3,consumerScreenDataChannelVersion:1,producerScreenDataChannelVersion:1,asrDataChannelVersion:+!!w.asrDataChannel,animojiDataChannelVersion:w.vmoji?w.vmojiOptions.protocolVersion:1,animojiBackendRender:!w.vmojiOptions.renderingOptions.useFullClientRendering,onDemandTracks:!0,unifiedPlan:!0,singleSession:!0,videoTracksCount:w.videoTracksCount,red:!0,audioShare:w.audioShare,fastScreenShare:w.fastScreenShare,videoSuspend:w.videoSuspend,simulcast:w.simulcast,consumerFastScreenShare:w.consumerFastScreenShare,consumerFastScreenShareQualityOnDemand:w.consumerFastScreenShareQualityOnDemand,transparentAudio:w.transparentAudio}}e.get=t})(Er||(Er={}));var Dr=Er,Or=16,kr=class e{constructor(e,t,n){g(this,`_datachannel`,void 0),g(this,`_participantIdRegistry`,void 0),g(this,`_asrCallback`,void 0),g(this,`_textDecoder`,void 0),R.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(Or)}}_onDataChannelMessage(t){let n=e.parse(t),r=this._participantIdRegistry?.getStreamDescription(n.ssrc)?.participantId;if(!r){R.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}},Ar,jr=class{constructor(){g(this,`_value`,1)}get value(){return this._value}set value(e){this._value=e}};Ar=jr,g(jr,`_instance`,null),g(jr,`getInstance`,()=>(Ar._instance||(Ar._instance=new Ar),Ar._instance));var Mr=class{constructor(){g(this,`streamDescriptionByCompactId`,new Map),g(this,`compactIdByStreamDescription`,new Map)}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=en(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:G.AUDIO_ACTIVITY,activeParticipants:i}:{type:`notification`,notification:G.STALLED_ACTIVITY,stalledParticipants:i};case 3:let a=(0,l.decode)(r);return{type:`notification`,notification:G.SPEAKER_CHANGED,speaker:this.getStreamDescription(a)?.participantId};case 5:let o=(0,l.decode)(r);return{type:`notification`,notification:G.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:G.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:G.MOVIE_UPDATE_NOTIFICATION,data:e}}case 9:let u=(0,l.decode)(r);return{type:`notification`,notification:G.VIDEO_SUSPEND_SUGGEST,bandwidth:u};default:return R.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){R.error(`could not uncompress participant ID ${t}`);continue}}else c=null;if(a===null){R.error(`unexpected null sequenceNumber`,e,r);continue}let l=Tr.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:G.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:n}}},Nr=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}({}),Pr=class{constructor(){g(this,`_worker`,null)}async _createWorker(e,t,n=[],r={},i=[]){return new Promise((a,o)=>{let s=n.join(`,`),c=new Blob([e,`exports.default(${s});`],{type:`application/javascript; charset=utf-8`}),l=window.URL.createObjectURL(c);this._worker=new Worker(l),this._worker.onmessage=e=>{switch(e.data.type){case Nr.READY:a();break;case Nr.ERROR:o(e.data.error);break;case Nr.FRAME:t(e.data);break;case Nr.DEBUG:R.debug(e.data.message);break;case Nr.LOG_ERROR:O.log(b.ERROR,e.data.message);break}},this._sendToWorker(Nr.INIT,r,i)})}_removeWorker(){this._worker?.terminate(),this._worker=null}_sendToWorker(e,t={},n=[]){this._worker?.postMessage(Object.assign({type:e},t),n)}static isBrowserSupported(){throw Error(`Not implemented`)}},Fr=class extends Pr{async init(e,t,n){R.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?(R.warn(`LibVPxDecoder`,r.error),t(r.error)):r.requestKeyFrame?(R.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(Nr.FRAME,{timestamp:e,data:t.buffer,isVP9:n,keyFrame:r,debug:R.enabled()},[t.buffer])}destroy(){this._removeWorker(),R.debug(`LibVPxDecoder destroyed`)}static isBrowserSupported(){return`WebAssembly`in window&&`Worker`in window}},Ir=class extends Pr{async init(e,t,n){R.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(){self.postMessage({type:t.READY})}function d(e,n,r,i=!1){c={timestamp:e,data:n,isVP9:r,keyFrame:i};let a=p(r);if(o&&!i){self.postMessage({type:t.FRAME,error:`WebCodecsDecoder waiting for keyframe`}),f();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});try{a.decode(l)}catch(e){m(`because failed call decode: ${e.message}`);return}h(i)}self.onmessage=e=>{switch(e.data.type){case t.INIT:u();break;case t.FRAME:d(e.data.timestamp,e.data.data,e.data.isVP9,e.data.keyFrame);break}};function f(){s||(self.postMessage({type:t.FRAME,requestKeyFrame:!0}),s=!0)}function p(e){return a!==e&&(a=e,m(`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=>{g();let r=n?[e]:[];self.postMessage({type:t.FRAME,data:e},r),e.close()},error:e=>{g(),m(`because error during decoding: ${e.message}`),i===`prefer-software`?self.postMessage({type:t.FRAME,error:`WebCodecsDecoder failed, reinitialize: `+String(e)}):(i=`prefer-software`,c&&c.keyFrame&&d(c.timestamp,c.data,c.isVP9,c.keyFrame),self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec switch to prefer-software because decoding issue: ${e.message}`}))}}),r.configure(_(a,i))),r}function m(e){if(r){try{r&&r.state!==`closed`&&r.close()}catch{}r=null,self.postMessage({type:t.FRAME,error:`WebCodecsDecoder reset ${e}`})}}function h(e=!1){l=setTimeout(()=>{m(`because of decode timeout`)},3e3)}function g(){l&&clearTimeout(l),l=null}function _(t,n){return{codec:t?e.VP9:e.VP8,hardwareAcceleration:n}}}})(),exports={default:workerExports};",r=>{r.error?(R.warn(`WebCodecsDecoder`,r.error),t(r.error)):r.requestKeyFrame?(R.debug(`WebCodecsDecoder requests key frame`),n()):(e(r.data),r.data.close())},[I.baseChromeVersion()>=92||I.browserName()===`Safari`])}decodeFrame(e,t,n,r=!1){this._sendToWorker(Nr.FRAME,{timestamp:e,data:t.buffer,isVP9:n,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),R.debug(`WebCodecsDecoder destroyed`)}static isBrowserSupported(){return`VideoDecoder`in window&&`Worker`in window&&`VideoFrame`in window&&!I.isBrokenVP9Decoder()&&I.browserName()!==`Firefox`}},Lr=class{constructor(e=null,t=0){g(this,`_counter`,0),g(this,`_interval`,0),g(this,`_lastCalculationTime`,Date.now()),g(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}},Rr=class{constructor(e){g(this,`_participantId`,void 0),g(this,`_firstFrameReceived`,!1),this._participantId=e}measure(e,t){if(this._firstFrameReceived)return;this._firstFrameReceived=!0;let n=W.getMarkNameScreenshareFirstFrame(this._participantId),r=W.measureMark(n);r!==null&&Bn.logEventualStat({name:H.SCREENSHARE_FIRST_FRAME,value:r,width:e,height:t})}},zr=65536,Br=`MARK_SCREENSHARE_FREEZE_DURATION`,Vr=class e{constructor(e,t,n,r){g(this,`_participantId`,void 0),g(this,`_onStream`,void 0),g(this,`_onStat`,void 0),g(this,`_onKeyFrameRequested`,void 0),g(this,`_statScreenShareFirstFrame`,void 0),g(this,`_chunks`,[]),this._participantId=e,this._onStream=t,this._onStat=n,this._onKeyFrameRequested=r,this._statScreenShareFirstFrame=new Rr(e)}appendChunk(t){let n=this._chunks.length;if(t.start)this._measureFreezeDuration(!1),this._measureFreezeDuration(!0),n&&(R.warn(`[FrameBuilder] Cleanup buffer`,Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!n||(this._chunks[n-1].sequence+1)%zr!==t.sequence){R.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(Br),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(Br);return}let t=W.measureMark(Br);t!==null&&t>1e3&&this._onStat({freeze_duration:t})}},Hr=class{constructor(e){g(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")}},Ur=class extends Hr{constructor(e){super(e),g(this,`_useImageBitmap`,void 0),g(this,`_canvas`,null),g(this,`_canvasContext`,null),g(this,`_stream`,null),g(this,`_track`,null),R.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){R.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){R.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(),R.debug(`CanvasRenderer destroyed`)}static isBrowserSupported(){return(`CanvasCaptureMediaStream`in window||`CanvasCaptureMediaStreamTrack`in window)&&!(I.browserName()===`Safari`&&Number(I.browserVersion())===15)&&!(I.browserName()===`Firefox`&&Number(I.browserVersion())<60)}},Wr=class extends Hr{constructor(e){super(e),g(this,`_generator`,void 0),g(this,`_writer`,void 0),g(this,`_stream`,void 0),R.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()),R.debug(`TrackGeneratorRenderer destroyed`)}static isBrowserSupported(){return`VideoFrame`in window&&`MediaStreamTrackGenerator`in window&&Ir.isBrowserSupported()}},Gr=class extends Vr{constructor(e,t,n,r){super(e,t,n,r),g(this,`_renderer`,void 0),g(this,`_decoder`,void 0),g(this,`_decoderReady`,!1),g(this,`_decoderBusy`,!1),g(this,`_decoderQueue`,[]),g(this,`_fpsMeter`,void 0),R.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 Lr(e=>R.log(`[StreamBuilder][${this._participantId}] fps: ${e}`),2e4)}_initRenderer(e=!1){e||!Wr.isBrowserSupported()?this._renderer=new Ur(this._onStream):this._renderer=new Wr(this._onStream)}_initDecoder(e=!1){e||!Ir.isBrowserSupported()?this._decoder=new Fr:this._decoder=new Ir,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=>{this._decoderBusy=!1,this._decodeQueue(),this._decoder instanceof Ir&&typeof e==`string`&&e.includes(`EncodingError`)&&this._switchToLibVPXDecoder()},this._onKeyFrameRequested).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_switchToLibVPXDecoder(){R.warn(`StreamBuilder switch to LibVPX decoder`),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)}_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(),R.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return Ur.isBrowserSupported()||Wr.isBrowserSupported()}},Kr=1,qr=1,Jr=2,Yr=0,Xr=1,Zr=2,Qr=4,$r=8;function ei(e,t,n,r,i,a,o){let s=0;t&&(s|=Xr),n&&(s|=Zr),r&&(s|=Qr),o||(s|=$r);let c=new ArrayBuffer(11),l=new DataView(c);if(l.setUint8(0,Kr),l.setUint16(1,i),l.setUint32(3,e),l.setUint8(7,+!!a),l.setUint16(8,Yr),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&Xr),l=!!(s&Zr),u=!!(s&Qr),d=!!(s&$r);if(n!==Kr)throw Error(`Unexpected protocol version. Got ${n}, expected ${Kr}`);return{timestamp:i,start:c,end:l,keyframe:u,sequence:r,isVP9:a,ssrc:o,eos:d,data:e.slice(11)}}function ni(e){if(!e||!e.byteLength||e.byteLength!==4)return!1;let t=new DataView(e);return!(t.getUint8(0)!==Kr||t.getUint8(1)!==qr||t.getUint16(2)!==Yr)}function ri(e){if(!e||!e.byteLength||e.byteLength!==10)return null;let t=new DataView(e);return t.getUint8(0)!==Kr||t.getUint8(1)!==Jr||t.getUint16(2)!==Yr?null:{seq:t.getUint16(4),ts2:t.getUint32(6)}}function ii(e){let t=new ArrayBuffer(4),n=new DataView(t);return n.setUint8(0,Kr),n.setUint8(1,qr),n.setUint16(2,e),t}var ai=2**15-1,oi=1,si=5,ci=5,li=class e{constructor(e){g(this,`_mediaSource`,void 0),g(this,`_codec`,void 0),g(this,`_sourceBuffer`,null),g(this,`_queue`,[]),g(this,`_clearBufferTill`,0),this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener(`sourceopen`,t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener(`sourceopen`,t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let e=this._sourceBuffer.buffered.start(0);e<this._clearBufferTill&&(this._sourceBuffer.remove(e,this._clearBufferTill),R.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)-si);r-n>ci&&(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}},ui=class e extends Vr{constructor(e,t,n){super(e,t,n),g(this,`_mediaBuffer`,null),g(this,`_video`,null),g(this,`_stream`,null),g(this,`_earliestTimestamp`,0),g(this,`_clusterStartTime`,0),g(this,`_lastFrameTimestamp`,0),R.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 li(e),this._video=document.createElement(`video`),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents=`none`,this._video.style.visibility=`hidden`,this._video.style.position=`absolute`,this._video.style.width=`160px`,this._video.style.height=`90px`,this._video.style.bottom=`0`,this._video.style.right=`0`,this._video.style.zIndex=`5000`,this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video?.src){R.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=()=>R.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,R.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(),R.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>ai&&(this._clusterStartTime=r,i=0),i===0){R.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),R.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"`)}},di=class{constructor(e,t,n,r,i){g(this,`_datachannel`,void 0),g(this,`_participantIdRegistry`,null),g(this,`_streamBuilders`,{}),g(this,`_onStream`,()=>{}),g(this,`_onEos`,()=>{}),g(this,`_onStat`,void 0),R.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){R.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=w.screenShareWebmBuilder&&ui.isBrowserSupported()?new ui(n,e,this._onStat):new Gr(n,e,this._onStat,()=>{this._requestKeyFrame(t.ssrc)}),this._streamBuilders[n]=r}r.appendChunk(t)}_requestKeyFrame(e){if(!(!this._datachannel||this._datachannel.readyState!==`open`))try{let t=ii(e);this._datachannel.send(t),R.debug(`ScreenCaptureReceiver request for keyframe for ssrc ${e}`)}catch(e){R.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,R.debug(`ScreenCaptureReceiver destroyed`)}},fi=class{constructor(e,t,n){g(this,`_prev`,void 0),g(this,`_next`,void 0),g(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}},pi=class{constructor(){g(this,`_head`,null),g(this,`_tail`,null),g(this,`_length`,0)}get length(){return this._length}push(...e){for(let t of e)this._tail=new fi(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):``}},mi=1e3,hi=class extends Pr{constructor(e,t,n,r){super(),g(this,`_sourceTrack`,void 0),g(this,`_onFrame`,void 0),g(this,`_useCongestionControl`,void 0),g(this,`_maxBitrate`,void 0),g(this,`_useImageCapture`,void 0),g(this,`_video`,null),g(this,`_imageCapture`,null),g(this,`_canvas`,null),g(this,`_canvasCtx`,null),g(this,`_frameReadTimeout`,0),g(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;R.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(Nr.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)},mi),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(Nr.SET_BITRATE,{bitrate:e,useCbr:t})}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),R.debug(`LibVPxEncoder destroyed`)}},gi=class extends Pr{constructor(e,t,n,r,i,a){super(),g(this,`_sourceTrack`,void 0),g(this,`_trackProcessor`,void 0),g(this,`_onFrame`,void 0),g(this,`_useCongestionControl`,void 0),g(this,`_maxBitrate`,void 0),g(this,`_useCbr`,void 0),g(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;R.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;function g(e){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),y(),self.postMessage({type:t.READY})}function _(e){e&&!h&&(h=!0),self.clearTimeout(l),l=self.setTimeout(()=>{c&&v(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(!x){r.releaseLock(),n.cancel();return}c=t,v(t,h)}}))}function v(e,t){(e.codedWidth!==i||e.codedHeight!==a)&&(i=e.codedWidth,a=e.codedHeight,y(),h=!0),x.encode(e,{keyFrame:t}),t&&(h=!1)}function y(){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),x.configure(t)}function b(e,t,n){d=e,m=t,s=n,y()}let x=new VideoEncoder({output:e=>{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])},error:e=>{self.postMessage({type:t.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case t.INIT:g(e.data);break;case t.FRAME:_(e.data.keyFrame);break;case t.SET_BITRATE:b(e.data.bitrate,e.data.useCbr,e.data.fps);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})},[],{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(Nr.FRAME,{keyFrame:e})}setBitrate(e,t,n){this._sendToWorker(Nr.SET_BITRATE,{bitrate:e,useCbr:t,fps:n})}isVP9(){return!0}destroy(){this._removeWorker(),R.debug(`WebCodecsEncoder destroyed`)}static isBrowserSupported(){return`VideoEncoder`in window&&`Worker`in window&&`EncodedVideoChunk`in window&&`MediaStreamTrackProcessor`in window}},_i=2100,vi=600,yi=1.2,bi=.8,xi=2e3,Si=8e3,Ci=8e3,wi=16e3,Ti=4,Ei=2e3,Di=function(e){return e[e.NONE=0]=`NONE`,e[e.UP=1]=`UP`,e[e.DOWN=2]=`DOWN`,e}(Di||{}),Oi=class{constructor(e,t,n,r,i,a,o){g(this,`_onCongestion`,void 0),g(this,`_ccEnabled`,void 0),g(this,`_fastSharing`,void 0),g(this,`_trendDelayThreshold`,void 0),g(this,`_highDelayThreshold`,void 0),g(this,`_targetFps`,void 0),g(this,`_minBitrate`,void 0),g(this,`_maxBitrate`,void 0),g(this,`_targetBitrate`,void 0),g(this,`_lastDown`,void 0),g(this,`_lastUp`,void 0),g(this,`_lastProbing`,void 0),g(this,`_lastCheckDelay`,void 0),g(this,`_upPenalty`,0),g(this,`_probing`,void 0),g(this,`_delayAvgShort`,-1),g(this,`_delayAvgLong`,-1),g(this,`_minDelay`,Number.MAX_VALUE),g(this,`_maxDelay`,0),g(this,`_largeDelayDuration`,0),g(this,`_lastFpsCalcMs`,void 0),g(this,`_frames`,0),g(this,`_fps`,0),this._onCongestion=e,this._ccEnabled=r,this._minBitrate=t,this._maxBitrate=n,this._fastSharing=i,this._targetFps=o,a>0?this._highDelayThreshold=a:this._highDelayThreshold=_i,i&&(this._highDelayThreshold=vi),this._trendDelayThreshold=Math.round(this._highDelayThreshold/3),this._targetBitrate=this._maxBitrate,this._probing=!1;let s=Date.now();this._lastDown=0,this._lastUp=s,this._lastProbing=s,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&&R.debug(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Di[i]} tr=${l} br=${n}`);let d=r-this._lastDown;if(i===2&&d>xi){this._probing&&(this._upPenalty=Math.min(++this._upPenalty,Ti),this._probing=!1);let n=bi*u*1e3;if(n>=this._targetBitrate&&(n=this._targetBitrate*bi),n=Math.max(n,this._minBitrate),n<this._targetBitrate){let r=Math.round(n/1e3),s=Math.round(this._upPenalty*Ci/1e3);R.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Di[i]}`),R.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=Si+this._upPenalty*Ci;if(i===1&&f>p&&d>p){let n=Math.min(this._targetBitrate*yi,this._maxBitrate);if(n>this._targetBitrate){let s=Math.round(n/1e3),c=Math.round(this._targetBitrate/1e3),l=Math.round(this._upPenalty*Ci/1e3);R.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${a} percent=${o} -> ${Di[i]}`),R.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>wi&&(this._probing=!1);let h=r-this._lastDown;this._upPenalty>0&&h>3*p&&(R.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>Ei){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&&R.log(`cc: fps=${this._fps}`)}}},ki=class{constructor(e){g(this,`_maxSize`,void 0),g(this,`_size`,0),g(this,`_buffer`,void 0),g(this,`_head`,0),g(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}},Ai=65536,ji=50,Mi=400,Ni=1e6,Pi=3e5,Fi=3e4,Ii=2e3,Li=5,Ri=0,zi=class{constructor(e,t,n,r){g(this,`_encoder`,void 0),g(this,`_datachannel`,void 0),g(this,`_signaling`,void 0),g(this,`_fastSharing`,void 0),g(this,`_destroyed`,!1),g(this,`_needKeyframe`,!0),g(this,`DATA_SIZE`,void 0),g(this,`_congestionControl`,void 0),g(this,`_frameNum`,0),g(this,`_width`,void 0),g(this,`_height`,void 0),g(this,`_feedback`,new ki(1024)),g(this,`_lastSentFrameSeq`,0),g(this,`_lastDeliveredFrameSeq`,0),g(this,`_lastFrameDelay`,0),g(this,`_lastFramerateReduced`,Date.now()),g(this,`_lastSharingStat`,Date.now()),g(this,`_congestionControlEnabled`,void 0),g(this,`_queue`,new pi),g(this,`_fpsMeter`,void 0),g(this,`_maxFrameDelay`,void 0),R.debug(`ScreenCaptureSender started`),this.DATA_SIZE=w.consumerScreenDataChannelPacketSize-11,this._datachannel=t,this._signaling=n,this._fastSharing=r,this._congestionControlEnabled=w.screenShareCongestionControl||this._fastSharing,this._width=e.getSettings().width,this._height=e.getSettings().height,this._maxFrameDelay=this._fastSharing?w.screenShareCongestionControlThreshold:w.screenShareCongestionControlThreshold*2;let i=w.getScreenFrameRate(this._fastSharing),{minBitrate:a,maxBitrate:o}=this._calcMinMaxBitrate(this._width,this._height),s=this._onCongestionCallback.bind(this);R.log(`ScreenCaptureSender: CongestionControl: enabled=${this._congestionControlEnabled} minBitrate=${Math.round(a/1e3)}k maxBitrate=${Math.round(o/1e3)}k delayThreshold=${w.screenShareCongestionControlThreshold}`),this._congestionControl=new Oi(s,a,o,this._congestionControlEnabled,this._fastSharing,w.screenShareCongestionControlThreshold,i);let c=(e,t)=>{if(this._destroyed)return;if(!e){R.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(gi.isBrowserSupported()){let t=this._fastSharing;this._encoder=new gi(e,c,this._congestionControlEnabled,o,t,i)}else this._encoder=new hi(e,c,this._congestionControlEnabled,o);this._datachannel.onmessage=e=>{ni(e.data)&&(R.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0);let t=ri(e.data);t!==null&&this._checkCcFeedback(t)},this._encoder.init().then(()=>this._handleQueue()).catch(e=>R.warn(`ScreenCaptureSender init failed`,e)),this._fpsMeter=new Lr(e=>R.log(`[ScreenCaptureSender] fps: ${e}`),5e3)}_handleQueue(){if(this._destroyed)return;let e=this._queue.shift();if(!e){if((this._lastSentFrameSeq-this._lastDeliveredFrameSeq+Ai)%Ai>Li&&this._lastFrameDelay>this._maxFrameDelay){let e=Date.now();e-this._lastFramerateReduced>Ii&&(this._lastFramerateReduced=e,R.debug(`[ScreenCaptureSender] reduce framerate: delay=${this._lastFrameDelay} maxDelay=${this._maxFrameDelay}`))}else this._requestFrame();return}if(!this._sendFrameChunk(e)){this._needKeyframe=this._needKeyframe||!this._cleanupQueue(),C.setImmediate(()=>this._handleQueue());return}if(e.isLast){this._frameNum++,this._fpsMeter.increment(),e.isKey&&R.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 C.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 pi;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=ei(e,t,n,r,Ri,this._encoder.isVP9(),i),o={sequence:Ri,data:a};return Ri=(Ri+1)%Ai,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 R.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(),R.debug(`ScreenCaptureSender destroyed`)}static isBrowserSupported(){return gi.isBrowserSupported()||hi.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);R.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(Pi,Math.min(Ni,Math.round(n*ji))),maxBitrate:Math.round(n*Mi)}}_checkCcFeedback(e){let t=this._feedback.update(e.seq,e.ts2);if(t===null)R.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>Fi){let t=this._congestionControl.getStat();t!==null&&(R.debug(`cc: send stats: ${JSON.stringify(t)}`),this._signaling.reportSharingStat(t)),this._lastSharingStat=e}}},Bi=90,Vi=4294967295,Hi=class e extends rr{constructor(e,t,n){super(e,t),g(this,`_producerNotification`,null),g(this,`_producerCommand`,null),g(this,`_producerScreen`,null),g(this,`_consumerScreen`,null),g(this,`_asr`,null),g(this,`_animojiDataChannel`,null),g(this,`_animojiReceiver`,null),g(this,`_animojiSender`,null),g(this,`_isOpen`,!1),g(this,`_observer`,!1),g(this,`_reconnectionPrevented`,!1),g(this,`_statInterval`,null),g(this,`_settingsInterval`,null),g(this,`_monitorRtpShareInterval`,null),g(this,`_statBytes`,{}),g(this,`_ssrcMap`,{}),g(this,`_ssrcMapUpdated`,!1),g(this,`_perfStatReporter`,void 0),g(this,`_producerOfferIsProcessing`,!1),g(this,`_producerNextOffer`,null),g(this,`_producerNextSessionId`,null),g(this,`_lastStat`,null),g(this,`_serverSettings`,void 0),g(this,`_prevConsumerSettings`,{}),g(this,`_prevConsumerFastSharingSettings`,{}),g(this,`_asrTrack`,null),g(this,`_captureSender`,null),g(this,`_captureReceiver`,null),g(this,`_participantIdRegistry`,null),g(this,`_disabledSenders`,new Set),g(this,`_rtpReceiversByStreamId`,{}),g(this,`_producerSessionId`,``),g(this,`_newAudioShareTrack`,null),g(this,`_simulcastInfo`,null),this.subscribe(this._signaling,qn.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Oe.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Oe.SOURCE_CHANGED,this._onSourcesChanged.bind(this)),this.subscribe(this._mediaSource,Oe.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._createPerfStatsReporter(),this._serverSettings=n,R.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){R.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?(R.error(`ServerTransport: Closed`,e),this._setState(q.FAILED)):(R.debug(`ServerTransport: Closed`),this._setState(q.CLOSED)))}removeParticipant(e){this._captureReceiver?.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){$n(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}setAnimojiTransport(e,t){if(w.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(){w.simulcast&&await this._changeSimulcastInfo(!0,!1)}_createPerfStatsReporter(){this._perfStatReporter?.destroy(),this._perfStatReporter=new sr(this,this._signaling)}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._stopMonitorRtpShareInterval(),this._removeAsrTrack(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._simulcastInfo=null,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(K.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,n){R.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let e=r.readyState;e===`open`?(R.debug(`[${t}] data channel opened`),n(r)):R.error(`[${t}] data channel open failed, state [${e}]`)},r.onerror=e=>{let n=e.error;R.error(`[${t}] data channel error`,n?.errorDetail,n?.message)}}_openConnection(t=!1){R.debug(`ServerTransport: Open single connection`);try{this._pc=new RTCPeerConnection}catch(e){R.error(`Failed to create RTCPeerConnection:`,e),this.close(e);return}this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=C.debounce(e=>{this._pc&&this._onConnectionStateChange(this._pc,e)},500),this._pc.onsignalingstatechange=e._onSignalingStateChange.bind(this,this._pc),this._participantIdRegistry=new Mr,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._createDataChannel(this._pc,Jn.producerNotification,e=>{this._producerNotification=e,this._producerNotification.binaryType=`arraybuffer`,this._signaling.setProducerNotificationDataChannel(e)}),this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,Jn.producerCommand,e=>{this._producerCommand=e,this._signaling.setProducerCommandDataChannel(e)}),this._createDataChannel(this._pc,Jn.producerScreenShare,e=>{this._producerScreen=e,this._producerScreen.binaryType=`arraybuffer`,this._createCaptureReceiver()}),w.asrDataChannel&&this._createDataChannel(this._pc,Jn.asr,e=>{this._asr=e,this._asr.binaryType=`arraybuffer`,this._removeAsrTrack(),this._asrTrack=new kr(e,this._participantIdRegistry,e=>{this._onAsrTranscription(e)})}),w.vmoji&&this._createDataChannel(this._pc,Jn.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(w.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){R.error(`ServerTransport: Unable to add media source tracks`,e),O.log(b.ERROR,`addTrack-single`),this.close(e);return}this._createDataChannel(this._pc,Jn.consumerScreenShare,e=>{this._consumerScreen=e,this._consumerScreen.binaryType=`arraybuffer`;let t=this._mediaSource.getScreenTrack();t&&(!w.consumerFastScreenShare||!this._mediaSource.mediaSettings.isFastScreenSharingEnabled)&&this._createCaptureSender(t)}),t||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(K.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(K.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(K.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(K.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
15
15
  `).forEach(e=>{let t=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Tr.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+)|(?:${Tr.TRANSPARENT_AUDIO_TRACK_PREFIX}-[0-9]+))`,n=new RegExp(t).exec(e);n&&(this._ssrcMap[n[1]]=n[3],this._ssrcMapUpdated=!0)})}_createCaptureSender(e){let t=this._mediaSource.mediaSettings;!e||!this._consumerScreen||!t.isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new zi(e,this._consumerScreen,this._signaling,t.isFastScreenSharingEnabled))}_removeCaptureSender(){this._captureSender?.destroy(),this._captureSender=null}_createCaptureReceiver(){this._producerScreen&&(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new di(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(K.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(K.REMOTE_STREAM_SECOND,e,null)},e=>{this._triggerEvent(K.SCREEN_SHARING_STAT,e)}))}_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){R.log(`Disabling video upload`),this._disabledSenders.add(n),n.replaceTrack(I.getBlackMediaTrack()).catch(e=>{R.error(`Could not disable video upload`,e)});return}let a=this._mediaSource.getSendVideoTrack();if(!r&&i&&a){R.log(`Enabling video upload`),this._disabledSenders.delete(n);let e=n.track;e.enabled=a.enabled,n.replaceTrack(a).then(()=>e.stop()).catch(e=>{R.error(`Could not enable video upload`,e)})}C.applyVideoTrackSettings(e,n,a??n.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}if(this._mediaSource.mediaSettings.isFastScreenSharingEnabled&&w.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`||C.applyVideoTrackSettings(e,n,n.track,this._prevConsumerFastSharingSettings,t)}),this._prevConsumerFastSharingSettings=t}}}_onScreenSharingStatus(e){e.track?(!w.consumerFastScreenShare||!this._mediaSource.mediaSettings.isFastScreenSharingEnabled)&&this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(K.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),nr.reportUsage(e)}).catch(()=>{}),this._statInterval=window.setTimeout(e,w.statisticsInterval)};this._statInterval=window.setTimeout(e,w.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(K.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=Tr.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(K.AUDIO_MIX_STALL,i)}this._statBytes[n]={bytesReceived:t.bytesReceived,stalled:i}}_allocateConsumer(){if(!this._signaling.ready)return;let e=Dr.get();!w.videoTracksCount&&!this._observer&&R.warn(`Setting videoTracksCount to 0 is deprecated`),this._signaling.allocateConsumer(null,e)}async _processOffer(e,t){if(!this._pc)throw Error(`Interrupt allocation`);let n=w.simulcast;try{await this._pc.setRemoteDescription(e)}catch(e){throw R.error(`[single] unable to set remote offer`,e),O.log(b.ERROR,`setRemoteDescription-single`),e}let r=this._findFirstSimTransceiver();if(w.simulcast)if(r){R.log(`_processOffer: caps.simulcast=${w.simulcast} mid=${r.mid} dir=${r.direction}`);let e=this._mediaSource.getStream(),t=await this._setupSimulcastTransceiver(e,r);R.log(`_processOffer: simulcastInfo`,t),t||(R.log(`_processOffer: simulcast transceiver not found in server offer mid=${r.mid}, disable simulcast`),n=!1)}else R.log(`_processOffer: simulcast transceiver not found in server offer, disable simulcast`),n=!1;let i;try{if(await this._handleTracks(),R.debug(`[single] create local answer`),!this._pc)throw Error(`Interrupt allocation`);i=await this._pc.createAnswer()}catch(e){throw R.error(`[single] unable to create answer`,e),O.log(b.ERROR,`createAnswer-single`),e}try{if(!this._pc)throw Error(`Interrupt allocation`);i.sdp=C.patchLocalSDP(i.sdp,!1,I.isBrokenH264Decoder(),!1),R.debug(`[single] set local answer`,{answer:i}),await this._pc.setLocalDescription(i)}catch(e){throw R.error(`[single] unable to set local answer`,e),O.log(b.ERROR,`setLocalDescription-single`),e}if(n&&r){i.sdp=C.patchSimulcastAnswerSdp(i.sdp,r,ne.WIDTH,ne.HEIGHT);for(let e of this._pc.getTransceivers())e.mid===null&&e.stop()}try{R.debug(`[single] transmit local answer`,{answer:i}),this._updateSSRCMap(e),await this._signaling.acceptProducer(i,Object.keys(this._ssrcMap),t),R.debug(`[single] remote offer has been processed`)}catch(e){R.warn(`[single] unable to send local answer`,e),O.log(b.ERROR,`acceptProducer`)}n&&await this._changeSimulcastInfo(!0,!0)}_findFirstSimTransceiver(){if(!this._pc)return null;for(let e of this._pc.getTransceivers()){let t=e.sender?.track?e.sender.track?.kind:e.receiver?.track?.kind;if(!e.sender||t!==k.video)continue;let n=e.sender.getParameters();if(!(!n.encodings||n.encodings.length<=1))return e}return null}async _setupSimulcastTransceiver(e,t){if(!t?.sender||!e)return null;t.direction=`sendonly`;let n=e.getVideoTracks()[0];await t.sender.replaceTrack(n),t.sender.setStreams(e);let r=t.sender.getParameters();if(!r.encodings||r.encodings.length<=1)return R.log(`_setup:sim: mid=${t.mid} dir=${t.direction}: wrong encodings:${JSON.stringify(r.encodings)}`),null;let i=ce(ne.WIDTH,ne.HEIGHT,this._serverSettings.camera?.bitrates?.generic),a=0,o=1;for(let e of r.encodings)e.scalabilityMode=re,e.active=!0,a>=i.streams.length?e.maxBitrate=0:e.maxBitrate=i.streams[a].bitrate,e.scaleResolutionDownBy=o,o*=2,a++;await t.sender.setParameters(r);let s=n.getSettings();return R.log(`_setup:sim: mid=${t.mid} dir=${t.direction} track=${s.width}x${s.height} encodings=${JSON.stringify(r.encodings)}`),!0}async _acceptProducer(e,t){if(this._producerOfferIsProcessing){this._producerNextOffer=e,this._producerNextSessionId=t,R.debug(`[single] wait until other remote offer is processed`);return}this._producerOfferIsProcessing=!0;let n={type:`offer`,sdp:C.patchRemoteSDP(e,I.isOldDataChannelDescription(),!1,!1,!1,I.isBrokenVP9Encoder(),I.isBrokenVP9Decoder())};if(R.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){R.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){R.warn(`Cannot find screenshare transceiver`);return}try{e.direction=`sendonly`,await e.sender.replaceTrack(this._mediaSource.getScreenShareTrack())}catch(e){R.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){R.warn(`Cannot find audioshare transceiver`);return}e.sender.track!==null&&R.warn(`Unexpected track assigned to audioshare`);try{e.direction=`sendonly`,await e.sender.replaceTrack(this._newAudioShareTrack),this._newAudioShareTrack=null}catch(e){R.error(`ServerTransport: Unable to replace track`,e),O.log(b.ERROR,`replaceTrack-single`)}}async _handleScreenShareTrack(){this._mediaSource.getScreenShareTrack()&&await this._replaceScreenShareTrack()}async _onSignalingNotification(e){if(this._isOpen)switch(e.notification){case G.PRODUCER_UPDATED:await this._onProducerUpdated(e);break;case G.REALLOC_CON:this._reconnect();break;case G.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case G.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case G.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case G.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}}_onAsrTranscription(e){this._triggerEvent(K.ASR_TRANSCRIPTION,e)}async _onProducerUpdated(e){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),w.breakVideoPayloadTypes&&(R.log(`test mode enabled, video switched off`),this._signaling.requestTestMode(`breakVideoPayloadTypes`,null)),this._producerSessionId=e.sessionId,await this._acceptProducer(e.description,e.sessionId)}_onAddTrack(e,t){R.debug(`[single] remote track (added)`,{track:t.track});let n=t.streams[0];n?(n.onremovetrack||(n.onremovetrack=e=>{this._triggerEvent(K.REMOTE_TRACK_REMOVED,n.id,n,e.track)}),n.getTracks().find(e=>e.id===t.track.id)||n.addTrack(t.track),this._rtpReceiversByStreamId[n.id]=t.receiver,this._triggerEvent(K.REMOTE_TRACK_ADDED,n.id,n,t.track)):R.error(`[single] unable to get media stream from track event`)}static _onSignalingStateChange(e,t){R.debug(`[single] signaling state changed`,{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(R.debug(`[single] connection state changed`,{state:e.connectionState},t),O.log(b.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),C.getPeerConnectionHostInfo(e).then(e=>{e?.local&&(O.log(b.ICE_CONNECTION_TYPE,e.local.type),R.debug(`Selected ICE candidates`,e))});break}}_onReplacedTrack(e,t){if(this._pc){R.debug(`_onReplacedTrack: newTrack=${e}, sendTrack=${t}`),t&&(e=t);let n=(e,t)=>{e.replaceTrack(t).catch(e=>{R.error(`ServerTransport: Unable to replace track`,e),O.log(b.ERROR,`replaceTrack-single`)})};if(R.log(`_onReplacedTrack: newTrack=${e.getSettings().width}x${e.getSettings().height}`),w.simulcast&&e.kind===k.video){let t=this._pc?.getTransceivers().find(t=>t.direction===`sendonly`&&t.sender?.track?.kind===k.video&&t.sender.track.contentHint===e.contentHint)?.sender;t?.track?(n(t,e),e.getSettings().width&&e.getSettings().height&&this._changeSimulcastInfo(!1,!1)):R.warn(`_onReplacedTrack: simulcast video transceiver not found`)}else{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&&w.consumerFastScreenShare&&this._mediaSource.mediaSettings.isFastScreenSharingEnabled&&await this._replaceScreenShareTrack(),this._applyConsumerSettings()}getStreamWaitingTimeMs(e,t){if(!this._pc)return O.log(b.PAT_WAITING_TIME_ERROR,`noConnection`),R.error(`Cannot get stream waiting time, peer connection is not initialized`),0;if(!RTCRtpReceiver.prototype.getSynchronizationSources)return O.log(b.PAT_WAITING_TIME_ERROR,`oldBrowser`),R.error(`Cannot get stream waiting time, RTCRtpReceiver.getSynchronizationSources is not supported`),0;let n=this._rtpReceiversByStreamId[e];if(!n)return O.log(b.PAT_WAITING_TIME_ERROR,`noReceiver`),R.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=n.getSynchronizationSources();if(!r||!r.length)return R.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let i=r[0].rtpTimestamp;if(!Number.isInteger(i))return O.log(b.PAT_WAITING_TIME_ERROR,`timestampNotInteger`),R.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${i}`),0;let a=t-i&Vi,o=Math.ceil(a/Bi);return Math.min(100,Math.max(0,o))}async _changeSimulcastInfo(e,t){let n=this._mediaSource.mediaSettings.isVideoEnabled,r=this._findFirstSimTransceiver();if(!w.simulcast||!n||!r||!r.sender)return;let i=this._mediaSource.getStream();if(!i)return;let a=i.getVideoTracks()[0],o=a.getSettings().width,s=a.getSettings().height,c=ce(o,s,this._serverSettings.camera?.bitrates?.generic),l=t||!oe(this._simulcastInfo,c);if(!c.streams.length||!l)return;let u=r.sender.getParameters();if(u.encodings||(u.encodings=[{}]),!(u.encodings.length<=1)){if(R.log(`_changeSimulcastInfo: ${o}x${s} command: ${JSON.stringify(c)} `),e){let e=0;for(let t of u.encodings)t.scaleResolutionDownBy=le(t.rid),t.scalabilityMode=re,e>=c.streams.length?(t.maxBitrate=0,t.active=!1):(t.active=!0,t.maxBitrate=c.streams[e].bitrate),e++;await r.sender.setParameters?.(u).catch(e=>{R.error(`Failed to set sender parameters`,u,e)}),R.log(`_changeSimulcastInfo: actual encodings: ${JSON.stringify(u.encodings)} `)}if(this._simulcastInfo=c,c.streams){let e={mediaSource:ke.CAMERA,simulcastInfo:c};await this._signaling.changeSimulcast(e)}}}async _monitorRtpShare(){let e=jr.getInstance().value;if(!this._mediaSource.mediaSettings.isFastScreenSharingEnabled||!w.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),R.log(`
16
16
  degradationPreference updated for fast share RTP Sender
17
17
  Actual senderStats: ${JSON.stringify(e)}