@vkontakte/calls-sdk 2.5.3-beta.2 → 2.5.3-beta.3

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.5.3-beta.2
3
- * Fri, 13 May 2022 17:30:09 GMT
2
+ * @vkontakte/calls-sdk v2.5.3-beta.3
3
+ * Mon, 16 May 2022 13:01:38 GMT
4
4
  * https://st.mycdn.me/static/callssdk/2-5-3/doc/
5
5
  */
6
6
 
@@ -8,5 +8,5 @@ var fa=Object.create;var _t=Object.defineProperty;var Sa=Object.getOwnPropertyDe
8
8
  `;if(!I&&!y&&!V&&!D)return A?X(u.split(T)).join(q):u;function X(ne){let v=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],R="a=rtcp-fb:111",F=ne.findIndex(J=>J.startsWith(R));return~F&&(ne[F]=ne[F]+q+v.join(q)),ne}function O(ne,v,R){let F=ne.split(" "),J=F.slice(0,3),ie;for(ie=3;ie<F.length;ie++)R.includes(F[ie])&&J.push(F[ie]);for(ie=3;ie<F.length;ie++)!R.includes(F[ie])&&!v.includes(F[ie])&&J.push(F[ie]);return J.join(" ")}function te(ne,v){let R=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),F,J=[];for(F=0;F<ne.length;++F){let ie=ne[F].match(R);ie&&ie.length===3&&ie[2]===v&&J.push(ie[1])}return J}function Oe(ne,v,R,F){let J,ie="m="+v;for(J=0;J<ne.length;++J)if(ne[J].startsWith(ie)){ne[J]=O(ne[J],R,F);break}}let be=[],re=u.split(T);(y||I)&&(be=te(re,"H264"));let ke=[];V&&(ke=te(re,"VP9"));let At=[];if(D&&(At=te(re,"red")),y){let ne=be.slice(0),v=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),R;for(R=0;R<re.length;++R){let J=re[R].match(v);J&&J.length===3&&ne.includes(J[2])&&ne.push(J[1])}let F=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(R=re.length;R--;){let J=re[R].match(F);J&&J.length===3&&ne.includes(J[2])&&re.splice(R,1)}Oe(re,"video",ne,[])}else I&&Oe(re,"video",[],be);return V&&Oe(re,"video",[],ke),D&&At.length>0&&Oe(re,"audio",[],At),A&&X(re),re.join(q)}ei.patchSDP=a;function e(u){return u?`${u.type||"WEB_SOCKET"}_${u.id}`:"_"}ei.getPeerIdString=e;function t(u,I){return u&&u.id===I.id&&(u.type||"WEB_SOCKET")===(I.type||"WEB_SOCKET")}ei.comparePeerId=t;function i(u){return c(this,null,function*(){return!u||!u.getStats?Promise.resolve(null):u.getStats(null).then(I=>{let y=null,V=null;if(I.forEach(A=>{A.type==="transport"&&A.selectedCandidatePairId?V=I.get(A.selectedCandidatePairId):A.type==="candidate-pair"&&A.state==="succeeded"&&!V&&(!A.hasOwnProperty("selected")||A.selected)&&(V=A)}),V&&V.localCandidateId){let A=I.get(V.localCandidateId);A&&(y={type:A.candidateType,ip:A.ip||A.ipAddress,port:A.port||A.portNumber})}return y}).catch(()=>null)})}ei.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function s(u,I){let y=String(u);return n.test(y)?(o.warn(`Already composite id [${u}] type supplied [${I}]`),y):I===Q.GROUP?"g"+y:I===Q.USER?"u"+y:(o.warn(`Unknown type [${I}] for id [${u}]`),y.match(r)?"u"+y:y)}ei.composeUserId=s;function l(u,I,y){let V=s(u,I);return p(V,y)}ei.composeParticipantId=l;function p(u,I){return I?u+ot+xt+I:u}ei.compose=p;function h(u){return l(u.id,u.idType||Q.USER,u.deviceIdx||0)}ei.composeId=h;function b(u){return u.participant?h(u.participant):l(u.participantId,u.participantType||Q.USER,u.deviceIdx||0)}ei.composeMessageId=b;function P(u){let I=String(u),y=I.match(n);return y?{id:Number(y[2]),type:y[1]==="g"?Q.GROUP:Q.USER}:(o.warn(`Unsupported compositeId [${u}]`),{id:Number(I),type:Q.USER})}ei.decomposeId=P;function $(u){let I=u.split(ot+xt);return{compositeUserId:I[0],deviceIdx:I.length>1?parseInt(I[1],10):0}}ei.decomposeParticipantId=$;function W(){var T,q;let u=(q=(T=window.crypto)==null?void 0:T.randomUUID)==null?void 0:q.call(T);if(u)return u;let I="0123456789abcdefghijklmnopqrstuvwxyz".split(""),y=new Array(36),V=0,A,D;for(D=0;D<36;D++)D===8||D===13||D===18||D===23?y[D]="-":D===14?y[D]="4":(V<=2&&(V=33554432+Math.random()*16777216|0),A=V&15,V=V>>4,y[D]=I[D===19?A&3|8:A]);return y.join("")}ei.uuid=W;function L(u,I){let y;function V(){let A=this,D=arguments;y&&window.clearTimeout(y),y=window.setTimeout(()=>{u.apply(A,D)},I)}return V}ei.throttle=L;function me(u){let I="",y=u.split(`
9
9
  `);for(let T of y)if(T.startsWith("a=fingerprint")){let q=T.split(" ");if(q.length===2){I=q[1];break}}if(!I)return st.default.minusOne;let V=I.split(":"),A=st.default.zero;for(let T=Math.min(7,V.length-1);T>=0;T--){let q=(0,st.default)(V[T],16);A=A.shiftLeft(8).or(q)}return((T,q)=>{let X=q.value;if(typeof X=="bigint")return(0,st.default)(BigInt.asIntN(T,X));let O=st.default.one.shiftLeft(T),te=q.and(O.subtract(1));return te.greaterOrEquals(O.subtract(te))?te.subtract(O):te})(64,A)}ei.sdpFingerprint=me;function Ae(u){return c(this,null,function*(){return new Promise(I=>window.setTimeout(I,u))})}ei.delay=Ae;function le(u,I,y){let V=[];return u.getSenders().forEach(A=>Ge(I,A,A.track,y,V)),V}ei.applySettings=le;function Ge(u,I,y,V,A){if(u&&y&&y.kind===de.video){let D=y.getSettings();if(D){let T=u.maxBitrateK?u.maxBitrateK*1024:null,q=D.width,X=D.height,O=q&&X&&u.maxDimension?Math.max(1,Math.max(q,X)/u.maxDimension):null,te=u.maxFramerate?u.maxFramerate:null,Oe=u.degradationPreference?u.degradationPreference:"balanced",be=V[y.id];if(be&&be.bitrate===T&&be.scaleResolutionDownBy===O&&be.maxFramerate===te&&be.degradationPreference===Oe){A[y.id]=be;return}A[y.id]={bitrate:T,scaleResolutionDownBy:O,maxFramerate:te,degradationPreference:Oe};let re=I.getParameters();re.encodings||(re.encodings=[{}]),re.encodings.forEach(ke=>{T?ke.maxBitrate=T:delete ke.maxBitrate,O?ke.scaleResolutionDownBy=O:delete ke.scaleResolutionDownBy,te?ke.maxFramerate=te:delete ke.maxFramerate}),re.degradationPreference=Oe,I.setParameters(re)}}}ei.applyVideoTrackSettings=Ge;function ce(u,I){Array.isArray(I)||(I=[I]);for(let y of I)if(u.includes(y))return!0;return!1}ei.includesOneOf=ce;function Re(u){var I;return Object.entries(((I=u.participantState)==null?void 0:I.state)||{}).reduce((y,[V,A])=>(u.participantState&&(y[V]={ts:u.participantState.stateUpdateTs[V],state:A}),y),{})}ei.mapParticipantState=Re;function j(u){return Object.entries(u).reduce((I,[y,{state:V}])=>(I[y]=V,I),{})}ei.mapLegacyParticipantState=j;function ht(u){let I=u.map(y=>{let V={uid:y.externalId,mediaSettings:y.mediaSettings,status:y.status,muteStates:y.muteStates,unmuteOptions:y.unmuteOptions};return d.participantStateMapped&&(V.participantState=y.participantState),V});return d.filterObservers?I.filter(y=>!y.uid.observer):I}ei.mapSharedParticipants=ht;function Vi(u,I){let y=Object.keys(u),V=Object.keys(I);if(y.length!==V.length)return!1;for(let A of y)if(!V.hasOwnProperty(A)||u[A].state!==I[A].state||u[A].ts!==I[A].ts)return!1;return!0}ei.isEqualParticipantState=Vi;function Fi(u,I){let y=Object.keys(u),V=Object.keys(I);if(y.length!==V.length)return!1;for(let A of y)if(!I.hasOwnProperty(A)||u[A]!==I[A])return!1;return!0}ei.isObjectsEquals=Fi;function Hi(u,I){if(u.length!==I.length)return!1;for(let y of u)if(I.indexOf(y)<0)return!1;return!0}ei.isArraysEquals=Hi;function Gi(u){return!Object.keys(u).length}ei.isEmptyObject=Gi})(mi||(mi={}));var S=mi;var qe=null,hi=null,Nt=[],Lt=[],_i=[],St=null,vt=null,gi=null,fi=!1,Si=!1,Ut,ct,Bt,Mr=!1,Dr=!1,vi=null,Ei="",Vt=[],Ti=null,Ar=navigator.appVersion,wa=navigator.appName,Ee=navigator.userAgent,Ii=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(Ii||{}),Et=class{constructor(e,t=!1,i=d.videoMaxWidth,r=d.videoMaxHeight){let n=!1;if(e){n={noiseSuppression:d.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let l;vt&&(l=vt.deviceId),typeof e=="string"&&(l=e),l&&(n.deviceId={ideal:l})}let s=!1;if(t){s={width:{min:d.videoMinWidth,max:i,ideal:i},height:{min:d.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:d.videoAspectRatio},frameRate:{ideal:d.videoFrameRate}};let l;St&&(l=St.deviceId),typeof t=="string"&&(l=t),l&&(s.deviceId={ideal:l}),d.videoFacingMode&&(s.facingMode={ideal:d.videoFacingMode})}this.audio=n,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},Or=class extends Et{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=d.screenFrameRate}};function xa(){return c(this,null,function*(){qe=null,yield Ft()})}function Na(){qe=null,Ft().then(()=>E.onDeviceChange())}function Ft(){return c(this,null,function*(){return qe||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!hi&&navigator.mediaDevices.addEventListener&&(hi=S.throttle(Na,1e3),navigator.mediaDevices.addEventListener("devicechange",hi)),qe=navigator.mediaDevices.enumerateDevices().then(a=>{Nt=a.filter(r=>r.kind==="videoinput"?(r.label&&(fi=!0),!0):!1),Lt=a.filter(r=>r.kind==="audioinput"?(r.label?Si=!0:Je.isMobile()&&Je.browserName()==="Firefox"&&(Si=fi),!0):!1),_i=a.filter(r=>r.kind==="audiooutput");let e=Ve.get("videoinput"),t=Ve.get("audioinput"),i=Ve.get("audiooutput");return St=Nt.find(r=>r.deviceId===e)||null,vt=Lt.find(r=>r.deviceId===t)||null,gi=_i.find(r=>r.deviceId===i)||null,qe=Promise.resolve(a),a}).catch(()=>(qe=null,[]))))})}function La(){return c(this,null,function*(){return Je.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(Mr=!0),/^a=mid:0$/m.test(t.sdp)&&(Dr=!0),a()}).catch(a)}):Promise.resolve()})}function Ht(a,e){return c(this,null,function*(){o.debug("Try to get media",a.getNative());let t=Je.hasPermissions(a.isVideo());!t&&!e&&E.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield xa()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?ee.CAMERA_PERMISSION:ee.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?ee.CAMERA_ACCESS:ee.MIC_ACCESS;break}if(a.canSimplify())return Ht(a.simplify(),e);let r=e||ee.UNKNOWN;throw E.onPermissionsError(r),r}})}function Ua(a){return c(this,null,function*(){o.debug("Try to get screen",a.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(a.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(o.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw ee.SCREEN_PERMISSION;default:throw ee.SCREEN_ACCESS}}})}function Gt(){return Vt.length||(Vt=(()=>{let a,e=!1,t=0,i="0",r=Ee.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return a=/\brv[ :]+(\d+)/g.exec(Ee),["IE",a&&a[1]||"Unknown",e,t,i];if(r[1]==="Safari"){if(a=Ee.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(a=Ee.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,Number(a[1]),i];if(a=Ee.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t,i];if(a=Ee.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t,i];if(a=Ee.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t,i]}if(r[1]==="Chrome"){if(e=!0,t=Number(r[2]),a=Ee.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t,i];if(a=Ee.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t,i];if(a=Ee.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t,i];if(a=Ee.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t,i];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t,i]}return a=Ee.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),a&&a[2]!==void 0&&(i=a[2]),[r[2]?r[1]:wa,a&&a[1]||r[2]||Ar,e,t,i]})()),Vt}var Je;(A=>{function a(){return c(this,null,function*(){return yield La(),Ft()})}A.init=a;function e(){return Nt}A.getCameras=e;function t(){return Lt}A.getMicrophones=t;function i(){return _i}A.getOutput=i;function r(){return Nt.length>0}A.hasCamera=r;function n(){return Lt.length>0}A.hasMicrophone=n;function s(){return St}A.getSavedCamera=s;function l(){return vt}A.getSavedMicrophone=l;function p(){return gi}A.getSavedOutput=p;function h(){return fi}A.hasCameraPermission=h;function b(){return Si}A.hasMicrophonePermission=b;function P(D=!1){return b()?r()&&D?h():!0:!1}A.hasPermissions=P;function $(D=!1,T=!0,q=!0){return c(this,null,function*(){let X=n()&&T,O=r()&&D,te;if(!X&&!O)te=new MediaStream;else try{te=yield Ht(new Et(X,O))}catch(Oe){te=new MediaStream}return!te.getVideoTracks().length&&q&&te.addTrack(Ge()),!te.getAudioTracks().length&&q&&te.addTrack(le()),te})}A.getUserMedia=$;function W(){return c(this,null,function*(){return Ua(new Or(window.screen.width,window.screen.height))})}A.getScreenMedia=W;function L(D,T=!1){return c(this,null,function*(){let q=T?d.videoEffectMaxWidth:d.videoMaxWidth,X=T?d.videoEffectMaxHeight:d.videoMaxHeight;return Ht(new Et(!1,D||!0,q,X))})}A.getUserVideo=L;function me(D){return c(this,null,function*(){return Ht(new Et(D||!0,!1))})}A.getUserAudio=me;function Ae(D,T){return c(this,null,function*(){let X=(yield Ft()).find(O=>O.kind===D&&O.deviceId===T);return X?(D==="videoinput"?St=X:D==="audioinput"?vt=X:D==="audiooutput"&&(gi=X),Ve.set(D,T),X):null})}A.saveDeviceId=Ae;function le(){if(!Bt||Bt.readyState==="ended"){let D=y(),T=D.createMediaStreamDestination(),q=D.createGain();q.gain.value=1e-5,q.connect(T),q.connect(D.destination);let X=D.createOscillator();X.type="sine",X.frequency.value=0,X.connect(q),X.start(),Bt=T.stream.getAudioTracks()[0]}return Object.assign(Bt.clone(),{enabled:!1})}A.getSilentMediaTrack=le;function Ge(D=d.videoMinWidth,T=d.videoMinHeight){return ct||(ct=document.createElement("canvas"),ct.getContext("2d")),ct.width=D,ct.height=T,(!Ut||Ut.readyState==="ended")&&(Ut=ct.captureStream(d.videoFrameRate).getVideoTracks()[0]),Object.assign(Ut.clone(),{enabled:!1})}A.getBlackMediaTrack=Ge;function ce(){if(ei()==="Edge"&&Number(u())<70)return!1;try{let D=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&D.RTCPeerConnection&&D.RTCIceCandidate&&D.RTCSessionDescription&&D.HTMLCanvasElement&&D.HTMLCanvasElement.prototype.captureStream&&D.RTCRtpSender&&D.RTCRtpSender.prototype.replaceTrack&&D.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(D){return!1}}A.isBrowserSupported=ce;function Re(){return!!navigator.mediaDevices.getDisplayMedia}A.isScreenCapturingSupported=Re;function j(){return Mr}A.canVP8=j;function ht(){return Dr}A.isUnifiedPlan=ht;function Vi(){let D=A.browserName()==="Safari"&&A.browserVersion()==="15"&&A.browserSubVersion()==="1",T=A.browserName()==="Opera"&&A.os()==="Windows";return D||T}A.isBrokenH264=Vi;function Fi(){return!(A.baseChromeVersion()&&A.isMobile())}A.canPreferH264=Fi;function Hi(){return Ei||(Ei=(()=>{let D={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 D)if(D.hasOwnProperty(T)&&D[T].test(Ee))return T;return"Unknown"})()),Ei}A.os=Hi;function Gi(){return vi===null&&(vi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Ar)),vi}A.isMobile=Gi;function ei(){return Gt()[0]}A.browserName=ei;function u(){return Gt()[1]}A.browserVersion=u;function I(){return Gt()[3]}A.baseChromeVersion=I;function y(){return Ti||(Ti=new(window.AudioContext||window.webkitAudioContext)),Ti}A.getAudioContext=y;function V(){return Gt()[4]}A.browserSubVersion=V})(Je||(Je={}));var C=Je;var kr=We(require("bit-buffer"));var Ba=65536,Ye=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(o.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%Ba!==e.sequence){o.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:n}=Ye.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:n})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((n,s)=>n+s.data.byteLength,0),i=new Uint8Array(t),r=0;for(let n of e)i.set(new Uint8Array(n.data),r),r+=n.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new kr.BitStream(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),s=i.readBits(1)<<1|r;return s===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,s>=2&&i.index++,i.readBits(3)!==7?(i.index++,(s===1||s===3)&&(i.index+=3)):(s===1||s===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Tt=class extends Ye{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;o.debug(`StreamBuilder started for participant [${e}]`),this._useImageBitmap="ImageBitmap"in window,$e.isBrowserSupported()?this._decoder=new $e:this._decoder=new at,this._decoder.init(i=>this._drawImage(i)).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}_drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._removeStream(),o.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(C.browserName()==="Safari"&&Number(C.browserVersion())>=15)}};var Wt=1,Va=1,wr=0,xr=11,Nr=1,Lr=2,Ur=4,Br=8;function Vr(a,e,t,i,r,n,s){let l=0;e&&(l|=Nr),t&&(l|=Lr),i&&(l|=Ur),s||(l|=Br);let p=new ArrayBuffer(xr),h=new DataView(p);if(h.setUint8(0,Wt),h.setUint16(1,r),h.setUint32(3,a),h.setUint8(7,n?1:0),h.setUint16(8,wr),h.setUint8(10,l),!s)return p;let b=new Uint8Array(p.byteLength+s.byteLength);return b.set(new Uint8Array(p),0),b.set(new Uint8Array(s),p.byteLength),b.buffer}function Fr(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,s=e.getUint16(8),l=e.getUint8(10),p=!!(l&Nr),h=!!(l&Lr),b=!!(l&Ur),P=!!(l&Br);if(t!==Wt)throw new Error(`Unexpected protocol version. Got ${t}, expected ${Wt}`);return{timestamp:r,start:p,end:h,keyframe:b,sequence:i,isVP9:n,ssrc:s,eos:P,data:a.slice(xr)}}function Hr(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==Wt||e.getUint8(1)!==Va||e.getUint16(2)!==wr)}var f=We(require("simple-ebml-builder"));var Fa=Ki(2,15)-1,Ci=1,Ha=5,Ga=5;var jt=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),o.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=jt._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return f.build(e[0])}else return new Uint8Array;let t=e.reduce((n,s)=>n+s.countSize(),0),i=new Uint8Array(t),r=0;for(let n of e){let s=f.build(n);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var n,s,l;((n=this._mediaSource)==null?void 0:n.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let e=(l=this._sourceBuffer)==null?void 0:l.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-Ha);r-i>Ga&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},Me=class extends Ye{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;o.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return 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,i){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"))]),n=[f.element(f.ID.PixelWidth,f.number(e)),f.element(f.ID.PixelHeight,f.number(t))],s=f.element(f.ID.Tracks,f.element(f.ID.TrackEntry,[f.element(f.ID.TrackNumber,f.number(Ci)),f.element(f.ID.TrackUID,f.number(Ci)),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_${i.toUpperCase()}`)),f.element(f.ID.Video,n)]));return f.unknownSizeElement(f.ID.Segment,[r,s])}static _genClusterHeader(e){return f.unknownSizeElement(f.ID.Cluster,[f.element(f.ID.Timecode,f.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new jt(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){o.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>o.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,o.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),o.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=Me._genWebmHeader();this._mediaBuffer.append(s);let l=Me._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(l)}let r=Math.round(i-this._clusterStartTime);if(r>Fa&&(this._clusterStartTime=i,r=0),r===0){o.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=Me._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let n=f.element(f.ID.SimpleBlock,[f.vintEncodedNumber(Ci),f.bytes(Me._intToU16BE(r)),f.number((e.keyframe?1:0)<<7),f.bytes(e.frameData)]);this._mediaBuffer.append(n,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),o.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var dt=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};o.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=n=>this._onDataChannelMessage(n.data)}_onDataChannelMessage(e){var n,s;let t=Fr(e),i=(s=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){o.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];if(!r){let l=p=>this._onStream(i,p);d.screenShareWebmBuilder&&Me.isBrowserSupported()?r=new Me(i,l):r=new Tt(i,l),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,o.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return($e.isBrowserSupported()||at.isBrowserSupported())&&(Tt.isBrowserSupported()||Me.isBrowserSupported())}};var yi=We(require("@vkontakte/libvpx"));var Wa=1e3,It=class extends Ne{constructor(e,t){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return c(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=l=>t(),r.onerror=()=>i(new Error("Video element error"));let n=r.play(),s=()=>i(new Error("Autoplay is disabled"));n?n.catch(s):s()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return c(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return c(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;o.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var u=Object.defineProperty;var b=o=>u(o,"__esModule",{value:!0});var g=(o,n)=>{b(o);for(var t in n)u(o,t,{get:n[t],enumerable:!0})};var y={};g(y,{default:()=>R});var e=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(e||{});var R=(o,n)=>{let t;function m(a,r){return o({locateFile:n}).then(s=>{if(t=new s.VpxEncoder,t.debug(r),!t.init(a?s.VpxType.VP9:s.VpxType.VP8))throw self.postMessage({type:e.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");t.setMaxQuantizer(10),t.setTargetBitrate(1024)})}function E(a,r,s,i){let c=t.allocateImage(a,r);if(!c){self.postMessage({type:e.FRAME,error:"No buffer data"});return}c.set(new Uint8Array(s));let f=Math.round(performance.now()),l=150;if(!t.encode(f,l,i)){self.postMessage({type:e.FRAME,error:"Encode failed"});return}let p=t.readFrame();if(!p){self.postMessage({type:e.FRAME,error:"No encoded data"});return}t.readFrame()&&(self.postMessage({type:e.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:e.LOG_ERROR,message:"LibVPxEncoder-drop"}));let d=new Uint8Array(p.byteLength);d.set(p),self.postMessage({type:e.FRAME,frameType:i?"key":"delta",timestamp:f,duration:l,data:d.buffer},[d.buffer])}self.onmessage=a=>{switch(a.data.type){case e.INIT:m(a.data.isVP9,a.data.debug).then(()=>self.postMessage({type:e.READY})).catch(r=>self.postMessage({type:e.ERROR,error:String(r)}));break;case e.FRAME:E(a.data.width,a.data.height,a.data.imageData,a.data.keyFrame);break}}};return y;})();
10
10
  `,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength})},[yi.default,yi.default.getUrl],{isVP9:this.isVP9(),debug:o.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(_e.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},Wa),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),o.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var lt=class extends Ne{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return c(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;o.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var b=Object.defineProperty;var g=i=>b(i,"__esModule",{value:!0});var F=(i,n)=>{g(i);for(var r in n)b(i,r,{get:n[r],enumerable:!0})};var A={};F(A,{default:()=>h});var l=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(l||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,n,r,c,s,f,t,a=null,p=0,u=!1;function V(e){n=e.readable,r=n.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&E(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),n.cancel();return}a=R,E(R,e)}}))}function E(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
11
- `,r=>{var n;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(n=r.data)==null?void 0:n.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:d.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(_e.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),o.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var ja=16*1024,Ka=11,Gr=ja-Ka,$a=65536,Ri=0,pt=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;o.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,n)=>{if(!this._destroyed){if(!r){o.warn("requestFrame failed, keyFrame: "+this._needKeyframe,n),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{o.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};lt.isBrowserSupported()?this._encoder=new lt(e,i):this._encoder=new It(e,i),this._datachannel.onmessage=r=>{Hr(r.data)&&(o.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>o.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,n){let s=Vr(e,t,i,r,Ri,this._encoder.isVP9(),n);return Ri=(Ri+1)%$a,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return c(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let n=e.data.slice(t,t+Gr),s=e.data.byteLength<=t+n.byteLength,l=this._wrapHeader(e.timestamp,!t,s,e.type==="key",n);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(l)}catch(p){o.warn("Error send data to DataChannel",p),r();return}s||window.setTimeout(()=>this._sendChunk(e,t+Gr,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),o.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return lt.isBrowserSupported()||It.isBrowserSupported()}};var Z=class{static get sessionKey(){return Z._sessionKey}static set sessionKey(e){Z._sessionKey=e}static get sessionSecretKey(){return Z._sessionSecretKey}static set sessionSecretKey(e){Z._sessionSecretKey=e}static get accessToken(){return Z._accessToken}static set accessToken(e){Z._accessToken=e}static isEmpty(){return!Z._sessionKey||!Z._sessionSecretKey}};var g=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(g._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(g._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(g._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(Z.accessToken=e.apiAuth.accessToken,Z.sessionKey=e.apiAuth.sessionKey,Z.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(g._params,e)}static get(e){return g._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.5.3-beta.2"}static get debug(){return undefined}static get protocolVersion(){return g._params.joinFromMultipleDevices?6:5}static get platform(){return g._params.platform}static set platform(e){g._params.platform=e}static get clientType(){return g._params.clientType}static set clientType(e){g._params.clientType=e}static get device(){return g._params.device}static get apiKey(){return g._params.apiKey}static get apiEnv(){return g._params.apiEnv}static get apiEndpoint(){switch(g.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return g._params.apiEnv}}static get authToken(){return g._params.authToken}static set authToken(e){g._params.authToken=e}static get anonymToken(){return g._params.anonymToken}static set anonymToken(e){g._params.anonymToken=e}static get domain(){return g._params.domain}static get iceServers(){return g._params.iceServers}static set iceServers(e){g._params.iceServers=e}static get wssBase(){return g._params.wssBase}static set wssBase(e){g._params.wssBase=e}static get wssToken(){return g._params.wssToken}static set wssToken(e){g._params.wssToken=e}static get signalingReconnectDelay(){return g._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return g._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return g._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return g._params.waitConnectionDelay}static get waitResponseDelay(){return g._params.waitResponseDelay}static get waitMessageDelay(){return g._params.waitMessageDelay}static get waitAnotherTabDelay(){return g._params.waitAnotherTabDelay}static get debugLog(){return g._params.debugLog}static get forceRelayPolicy(){return g._params.forceRelayPolicy}static set forceRelayPolicy(e){g._params.forceRelayPolicy=e}static get videoMinWidth(){return g._params.videoMinWidth}static get videoMaxWidth(){return g._params.videoMaxWidth}static set videoMaxWidth(e){g._params.videoMaxWidth=e}static get videoMinHeight(){return g._params.videoMinHeight}static get videoMaxHeight(){return g._params.videoMaxHeight}static set videoMaxHeight(e){g._params.videoMaxHeight=e}static get videoAspectRatio(){return g._params.videoAspectRatio}static get videoFrameRate(){return g._params.videoFrameRate}static get videoFacingMode(){return g._params.videoFacingMode}static get screenFrameRate(){return g._params.screenFrameRate}static get videoEffects(){return g._params.videoEffects}static set videoEffects(e){g._params.videoEffects=e}static get videoEffectMaxWidth(){return g._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){g._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return g._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){g._params.videoEffectMaxHeight=e}static get voiceParams(){return g._params.voiceParams}static get specListenerParams(){return g._params.specListenerParams}static get iceRestartWaitTime(){return g._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return g._params.transportConnectionWaitTime}static get statisticsInterval(){return g._params.statisticsInterval}static set statisticsInterval(e){g._params.statisticsInterval=e}static get networkStatisticsInterval(){return g._params.networkStatisticsInterval}static get perfStatReportEnabled(){return g._params.perfStatReportEnabled}static get callStatReportEnabled(){return g._params.callStatReportEnabled}static get producerNotificationDataChannel(){return g._params.producerNotificationDataChannel&&dt.isBrowserSupported()}static get producerCommandDataChannel(){return g._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return g._params.consumerScreenDataChannel&&pt.isBrowserSupported()}static get producerScreenDataChannel(){return g._params.producerScreenDataChannel&&g.producerNotificationDataChannel}static get screenShareWebmBuilder(){return g._params.screenShareWebmBuilder}static get noiseSuppression(){return g._params.noiseSuppression}static set noiseSuppression(e){g._params.noiseSuppression=e}static get preferH264(){return g._params.preferH264}static get preferVP9(){return g._params.preferVP9}static get audioNack(){return g._params.audioNack}static get consumerScreenTrack(){return g._params.consumerScreenTrack&&g.consumerScreenDataChannel}static get producerScreenTrack(){return g._params.producerScreenTrack&&g.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=g._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return g._params.movieShare&&g.videoTracksCount>0}static get videoTracksCount(){return g.producerNotificationDataChannel?g._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return g._params.breakVideoPayloadTypes}static get filteredMessages(){return g._params.filteredMessages}static get serverAudioRed(){return g._params.serverAudioRed}static get p2pAudioRed(){return g._params.p2pAudioRed}static get batchParticipantsOnStart(){return g._params.batchParticipantsOnStart}static get participantStateMapped(){return g._params.participantStateMapped}static get filterObservers(){return g._params.filterObservers}static get muteMode(){return g._params.muteMode}},d=g;d._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,serverAudioRed:!1,p2pAudioRed:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,participantStateMapped:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1};var Y=(p=>(p.WAITING_HALL="WAITING_HALL",p.WAITING="WAITING",p.CONNECTING="CONNECTING",p.CONNECTED="CONNECTED",p.RECONNECT="RECONNECT",p.ERROR="ERROR",p.HANGUP="HANGUP",p.PERMISSIONS="PERMISSIONS",p))(Y||{});function K(a,...e){let t=d.get(a);t&&setTimeout(t,0,...e)}function Ie(a,e,...t){if(d.filterObservers){if(Array.isArray(e)){if(e=e.filter(i=>!i.observer),!e.length)return}else if(e.observer)return}K(a,e,...t)}function Le(a){return Object.assign({},a)}function ut(a){return a.slice()}var bi;(ne=>{function a(v,R){K("onLocalStream",v,Le(R))}ne.onLocalStream=a;function e(v,R){K("onScreenStream",v,Le(R))}ne.onScreenStream=e;function t(v,R){K("onLocalStreamUpdate",Le(v),R)}ne.onLocalStreamUpdate=t;function i(v){K("onLocalStatus",v)}ne.onLocalStatus=i;function r(v,R){Ie("onRemoteStream",v,R)}ne.onRemoteStream=r;function n(v,R,F){Ie("onRemoteLive",v,R,F)}ne.onRemoteLive=n;function s(v,R){Ie("onRemoteScreenStream",v,R)}ne.onRemoteScreenStream=s;function l(v,R,F,J){Ie("onConversation",v,Le(R),Le(F),J)}ne.onConversation=l;function p(v,R){Ie("onRemoteMediaSettings",v,Le(R))}ne.onRemoteMediaSettings=p;function h(v,R){Ie("onRemoteParticipantState",v,Le(R))}ne.onRemoteParticipantState=h;function b(v,R,F=null){Ie("onRemoteStatus",v,R,F)}ne.onRemoteStatus=b;function P(v,R,F=null){Ie("onParticipantStatus",v,R,F)}ne.onParticipantStatus=P;function $(){K("onPermissionsRequested")}ne.onPermissionsRequested=$;function W(v){K("onPermissionsError",v)}ne.onPermissionsError=W;function L(v){Ie("onRemoteRemoved",v)}ne.onRemoteRemoved=L;function me(v,R,F){K("onCallState",v,R,Le(F))}ne.onCallState=me;function Ae(v,R){K("onDeviceSwitched",v,R)}ne.onDeviceSwitched=Ae;function le(v,R,F,J=!1,ie=!1,ti=null,ga=null){K("onMuteStates",Le(v),ut(R),ut(F),J,ie,ti,ga)}ne.onMuteStates=le;function Ge(v,R){Ie("onRolesChanged",v,ut(R))}ne.onRolesChanged=Ge;function ce(v){K("onLocalRolesChanged",ut(v))}ne.onLocalRolesChanged=ce;function Re(v,R){Ie("onPinnedParticipant",v,R)}ne.onPinnedParticipant=Re;function j(v){K("onLocalPin",v)}ne.onLocalPin=j;function ht(v){K("onOptionsChanged",ut(v))}ne.onOptionsChanged=ht;function Vi(){K("onCallAccepted")}ne.onCallAccepted=Vi;function Fi(){K("onRateNeeded")}ne.onRateNeeded=Fi;function Hi(v){Ie("onSpeakerChanged",v)}ne.onSpeakerChanged=Hi;function Gi(v){K("onVolumesDetected",ut(v))}ne.onVolumesDetected=Gi;function ei(v,R){K("onLocalVolume",v,R)}ne.onLocalVolume=ei;function u(v,R){K("onJoinStatus",v,R)}ne.onJoinStatus=u;function I(v,R){K("onHangup",v,R)}ne.onHangup=I;function y(v){K("onMultipartyChatCreated",Le(v))}ne.onMultipartyChatCreated=y;function V(){K("onDeviceChange")}ne.onDeviceChange=V;function A(v){K("onFingerprintChange",v)}ne.onFingerprintChange=A;function D(){K("onTokenExpired")}ne.onTokenExpired=D;function T(v,R,F=!1){K("onChatMessage",v,R,F)}ne.onChatMessage=T;function q(v,R,F=!1){K("onCustomData",v,R,F)}ne.onCustomData=q;function X(v,R,F,J,ie,ti){K("onRecordStarted",v,R,F,J,ie,ti)}ne.onRecordStarted=X;function O(){K("onRecordStopped")}ne.onRecordStopped=O;function te(v){K("onLocalNetworkStatusChanged",v)}ne.onLocalNetworkStatusChanged=te;function Oe(v){K("onNetworkStatusChanged",v)}ne.onNetworkStatusChanged=Oe;function be(v,...R){K("onDebugMessage",v,...R)}ne.onDebugMessage=be;function re(v,R){let F=Object.assign({},v,{memory:R});K("onStatistics",F)}ne.onStatistics=re;function ke(){K("onAutoplayError")}ne.onAutoplayError=ke;function At(v,R,F){K("onChatRoomUpdated",v,R,F)}ne.onChatRoomUpdated=At})(bi||(bi={}));var E=bi;var Pi=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(Pi||{}),Mi;(ce=>{let a="📞",e=(Re,...j)=>{E.onDebugMessage(Re,...j)},t=!1,i=(Re,j)=>(...ht)=>{Re(...ht),Cr(j,ht)},r=console.debug.bind(console,a),n=console.log.bind(console,a),s=console.warn.bind(console,a),l=console.error.bind(console,a),p=e.bind(null,"DEBUG"),h=e.bind(null,"LOG"),b=e.bind(null,"WARN"),P=e.bind(null,"ERROR");ce.debug=p,ce.log=h,ce.warn=b,ce.error=P;function Ae(){return t}ce.enabled=Ae;function le(Re){t=Re,d.debugLog&&si(),Re?(ce.debug=d.debugLog?i(r,"DEBUG"):r,ce.log=d.debugLog?i(n,"LOG"):n,ce.warn=d.debugLog?i(s,"WARN"):s,ce.error=d.debugLog?i(l,"ERROR"):l):(ce.debug=d.debugLog?i(p,"DEBUG"):p,ce.log=d.debugLog?i(h,"LOG"):h,ce.warn=d.debugLog?i(b,"WARN"):b,ce.error=d.debugLog?i(P,"ERROR"):P)}ce.toggle=le;function Ge(Re,...j){switch(Re){case"DEBUG":ce.debug(...j);break;case"LOG":ce.log(...j);break;case"WARN":ce.warn(...j);break;case"ERROR":ce.error(...j);break}}ce.send=Ge})(Mi||(Mi={}));var o=Mi;var ze=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(ze||{}),pe;(l=>{function a(p){return p.length?typeof p[0]=="object"?p:p.map(h=>e(h)):[]}l.fromIds=a;function e(p,h="USER"){return{id:p,type:h}}l.fromId=e;function t(p){return{id:p.id,type:p.type==="ANONYM"?"ANONYM":"USER"}}l.fromSignaling=t;function i(p){return`{"id":"${p.id}","type":"${p.type}"}`}l.toString=i;function r(p,h="USER"){return i(e(p,h))}l.fromIdToString=r;function n(p){try{return JSON.parse(p)}catch(h){throw new Error(`Failed to parse ExternalId from string '${p}'`)}}l.fromString=n;function s(p,h){return p.id===h.id&&p.type===h.type}l.compare=s})(pe||(pe={}));var ue;(r=>{function a(n,s="USER",l=0){return{id:n,type:s,deviceIdx:l}}r.fromId=a;function e(n){return`{"id":"${n.id}","type":"${n.type}","deviceIdx":"${n.deviceIdx}"}`}r.toString=e;function t(n,s){return Object.assign({deviceIdx:s},pe.fromSignaling(n))}r.fromSignaling=t;function i(n){return n&&typeof n=="object"?n.deviceIdx:0}r.getDeviceIdx=i})(ue||(ue={}));var Se=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(Se||{}),Wr="s",jr="m";function Fe(a){return a.participantId+(a.mediaType?ot+Wr+a.mediaType:"")+(a.streamName?ot+jr+a.streamName:"")}function Ct(a){let e=a.split(ot),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i=null,r,n=0;for(let l of e)switch(l.charAt(0)){case Wr:i=qa(l.slice(1));break;case jr:r=l.slice(1);break;case xt:n=Number.parseInt(l.slice(1),10);break;default:throw new Error("Unexpected parameter type "+l.charAt(0)+" in stream description "+a)}return{participantId:S.compose(t,n),mediaType:i,streamName:r}}function qa(a){for(let e of Object.keys(Se))if(e===a)return Se[e];return null}function Di(a,e){return a===null||e===null?a===null&&e===null:!(a.maxDimension!==e.maxDimension||a.maxBitrateK!==e.maxBitrateK||a.maxFramerate!==e.maxFramerate||a.degradationPreference!==e.degradationPreference)}function Kt(a,e){return!(!Di(a.camera,e.camera)||!Di(a.screenSharing,e.screenSharing))}function Ai(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function Kr(a){try{return btoa(JSON.stringify(a))}catch(e){o.warn("WaitingParticipant: failed convert to string",a,e)}return null}function $r(a){try{return JSON.parse(atob(a))}catch(e){o.warn("WaitingParticipant: failed convert from string",a,e)}return null}var yt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,m.log(_.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,m.log(_.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(o.log("Failed to fix RV"),m.log(_.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),m.log(_.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,o.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===de.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var $t=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(d.muteMode||!((s=this._output)==null?void 0:s.audioTrack))return;let e=C.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{o.warn("Error on play audio"),E.onAutoplayError()},r=l=>{t.srcObject=new MediaStream([l]),t.load();let p=t.play();p?p.catch(i):i()},n=()=>{var p;o.debug("Recover audio playback");let l=(p=this._output)==null?void 0:p.audioTrack;l?r(l):o.warn("Broken audio track")};t.onpause=n,t.onstalled=n,t.onerror=n,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return c(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=C.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw m.log(_.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var Ja=90,Ya=3,qt=class extends z{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),E.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>Ja?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Ya)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var za=44100,Rt=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=C.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=za/this._fftBins.length,t=Math.ceil(d.voiceParams.minFreq/e),i=Math.floor(d.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((n,s)=>n+s,0)/e.length/255,r=this._lastSmoothedLevel*d.voiceParams.smoothing+i*(1-d.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var Jt=class extends z{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&E.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,d.voiceParams.interval)};this._interval=window.setTimeout(t,d.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,ve.SOURCE_CHANGED,r=>{r.kind===de.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new Rt("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var qr="videochat-epi",Qa=5e3,Xa=3e4,Qe=class extends z{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,N.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(qr)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return c(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&d.perfStatReportEnabled&&this._previousTimestamp+Qa<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),d.callStatReportEnabled&&this._previousCallStatReportTimestamp+Xa<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return c(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(qr,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,n)=>(n.kind==="video"?(n.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+n.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+n.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=n.framesDropped,r.nack_sent+=n.nackCount,r.pli_sent+=n.pliCount,r.fir_sent+=n.firCount):(n.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+n.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+n.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=n.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=n.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=n.removedSamplesForAcceleration,r.concealed_audio_samples+=n.concealedSamples,r.silent_concealed_audio_samples+=n.silentConcealedSamples,r.audio_concealment_events+=n.concealmentEvents),r),t),e.outbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.nack_received+=n.nackCount,r.pli_received+=n.pliCount,r.fir_received+=n.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,n=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,l=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,p=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,h=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=n/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=l/r*1e3,i.concealed_silent_audio_samples=p/r*1e3,i.concealment_audio_avg_size=l/h,i.total_audio_energy=t.total_audio_energy}m.logCustom("callStat",i),o.log("Sent call stats",i),this._previousCallStatReport=t}};var Za=1e3;function oe(a,e,t=0){return e in a&&a[e]?a[e]:t}function Jr(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function He(a,e){return t=>t[a]===e}function en(a){return(e,t)=>e[a]-t[a]}function Yt(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function tn(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function rn(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Oi(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=rn(t[1])?Oi(t[1]):t[1],e),{})}function an(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function nn(a){return c(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...a.getReceivers().map(t=>t.getStats())),e.push(...a.getSenders().map(t=>t.getStats()))):e.push(a.getStats()),Promise.all(e).then(an).then(tn)})}function sn(a){let e=a.filter(He("type","candidate-pair")).sort(en("priority")).find(Jr(He("nominated",!0),He("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=a.find(He("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=a.find(He("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),Oi(t)}function on(a,e){let t=Yt("id",a),i=a.filter(Jr(He("type","inbound-rtp"),He("type","outbound-rtp")));C.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,s)=>{if(!n[s.ssrc])n[s.ssrc]=s;else{let l=Object.assign({},n[s.ssrc],s),p=n[s.ssrc].isRemote?s:n[s.ssrc];l.id=p.id,l.type=p.type,delete l.isRemote,delete l.remoteId,n[l.ssrc]=l}return n},{})));let r={};if(C.browserName()==="Safari"){let n=a.filter(He("type","track"));r=Yt("trackIdentifier",n)}return i.map(n=>{let s=Number(n.ssrc),l=n.mediaType||n.kind,p=n.trackId,h=n.type,b=n.codecId;if(C.browserName()==="Safari"){let $=/^.+_([\d]+)$/.exec(n.id);if($&&(s=parseInt($[1],10)),l=n.id.indexOf("Audio")>0?"audio":"video",e[s]){let W=l+"-"+e[s];r[W]&&(p=r[W].id)}}if(!h||!s||!l)return null;let P={ssrc:s,type:h,kind:l,bytesReceived:oe(n,"bytesReceived"),bytesSent:oe(n,"bytesSent"),jitter:oe(n,"jitter"),packetsLost:oe(n,"packetsLost"),packetsReceived:oe(n,"packetsReceived"),packetsSent:oe(n,"packetsSent"),fractionLost:oe(n,"fractionLost"),pliCount:oe(n,"pliCount"),firCount:oe(n,"firCount"),nackCount:oe(n,"nackCount"),userId:e[s]};if(l==="video"){let $=oe(n,"framesDecoded"),W=oe(n,"totalInterFrameDelay"),L=oe(n,"totalSquaredInterFrameDelay");P.interframeDelayVariance=(L-W*W/$)/$}if(l==="audio"&&(P.totalSamplesReceived=oe(n,"totalSamplesReceived"),P.concealedSamples=oe(n,"concealedSamples"),P.insertedSamplesForDeceleration=oe(n,"insertedSamplesForDeceleration"),P.removedSamplesForAcceleration=oe(n,"removedSamplesForAcceleration"),P.silentConcealedSamples=oe(n,"silentConcealedSamples"),P.concealmentEvents=oe(n,"concealmentEvents"),P.totalAudioEnergy=oe(n,"totalAudioEnergy")),b&&t[b]){let $=t[b];P.clockRate=$.clockRate,P.mimeType=$.mimeType}if(p&&t[p]){let $=t[p];P.frameHeight=$.frameHeight,P.frameWidth=$.frameWidth,P.framesDecoded=$.framesDecoded,P.framesReceived=$.framesReceived,P.framesDropped=$.framesDropped}return Oi(P)}).filter(n=>!!n)}function cn(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=Yt("ssrc",a.rtps),i=Yt("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let s=t[n],l=i[n];if(!(!s||!l)){if(s.bytesReceived&&s.bytesReceived>l.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-l.bytesReceived)/r)),s.bytesSent&&s.bytesSent>l.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-l.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>l.packetsReceived||s.packetsLost>l.packetsLost){let p=s.packetsLost-l.packetsLost,h=s.packetsReceived-l.packetsReceived;s.packetLoss=parseFloat((100*p/(p+h)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&l.framesDropped&&s.framesDropped>l.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-l.framesDropped)/r).toFixed(0)))}}),a}function bt(i,r){return c(this,arguments,function*(a,e,t={}){let n=yield nn(a),s={timestamp:Date.now(),transport:sn(n),rtps:on(n,t)};return e?cn(s,e):(yield S.delay(Za),bt(a,s,t))})}var zt=.8,Xe=class extends z{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=U.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=n,this._perfStatReporter=new Qe(this,i,!0),this.subscribe(this._signaling,he.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ve.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ve.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:d.iceServers,iceTransportPolicy:d.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(s){m.log(_.ERROR,"addTrack-direct"),o.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===U.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==U.IDLE&&e!==U.CLOSED&&e!==U.FAILED&&this._startStatInterval()}open(e=null){return c(this,null,function*(){if(this._isOpen){o.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(o.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(i){m.log(_.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(U.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(N.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Kt(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(o.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(U.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(U.CLOSED)),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case k.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case k.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case k.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((n=e.data.sdk)==null?void 0:n.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=S.getPeerIdString(e.peerId);S.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){o.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw m.log(_.ERROR,"addIceCandidate-direct"),o.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else o.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return c(this,null,function*(){if(!this._remoteCandidates[e]){o.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){o.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw m.log(_.ERROR,"setRemoteDescription-direct"),o.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){o.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(N.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return c(this,null,function*(){e.candidate&&this._signaling.ready&&(o.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(o.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>c(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(o.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===U.IDLE||e===U.OPENED?this._setState(U.CONNECTING):this._setState(U.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),m.log(_.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(U.CONNECTED),this._stopReconnection(),S.getPeerConnectionHostInfo(this._pc).then(e=>{e&&m.log(_.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(U.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(o.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},d.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(o.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(Te.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(m.log(_.ICE_RESTART),o.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):o.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,o.error("Ice restart failed",{participantId:this._participantId}),m.log(_.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return c(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return o.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw o.error("Unable to create offer",i,{participantId:this._participantId}),m.log(_.ERROR,"createOffer-direct"),i}).then(i=>c(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=Xe._patchDescription(i),o.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw o.error("Unable to set local description",i,{participantId:this._participantId}),m.log(_.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return c(this,null,function*(){return o.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw o.error("Unable to create answer",e,{participantId:this._participantId}),m.log(_.ERROR,"createAnswer-direct"),e}).then(e=>c(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=Xe._patchDescription(e),o.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw o.error("Unable to set local description",e,{participantId:this._participantId}),m.log(_.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!C.baseChromeVersion();return e.sdp=S.patchSDP(e.sdp,d.preferH264&&C.canPreferH264(),C.isBrokenH264(),d.preferVP9,t&&d.audioNack,d.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{o.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),m.log(_.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}bt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:Te.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:Te.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(N.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,d.statisticsInterval)})};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=le=>le.rtt<=this._networkLimits.goodNet.rtt&&le.loss<=this._networkLimits.goodNet.loss,i=le=>le.rtt>=this._networkLimits.badNet.rtt||le.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((le,Ge)=>Math.max(le,Ge.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-zt)+r*zt,loss:this._lastNetworkStat.loss*(1-zt)+n*zt},l=i(s),p=t(s),h=i(this._remoteNetworkStat),b=t(this._remoteNetworkStat),P=i(this._lastNetworkStat),$=t(this._lastNetworkStat),me=l||h?.2:p&&b?1:0,Ae=Date.now();if((P!==l||$!==p||Ae-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(le=>{o.warn("Unable to send [bad-net]",le)})),me){let le={};le[this._participantId]=le[""]=me,this._triggerEvent(N.NETWORK_STATUS,le)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=S.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(E.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=S.applySettings(this._pc,e,this._prevConsumerSettings))}};var Yr=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Yr||{}),Pt=Yr;var Ze=We(require("messagepack"));var ki=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var n,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let l=(0,Ze.decode)(r);return Object.entries(l).forEach(([L,me])=>{let Ae=Ct(L);this.streamDescriptionByCompactId.set(me,Ae)}),null;case 2:case 4:let p=(0,Ze.decode)(r),h=[];for(let L of p){let me=this.getStreamDescription(L);me&&h.push(me.participantId)}return i===2?{type:"notification",notification:k.AUDIO_ACTIVITY,activeParticipants:h}:{type:"notification",notification:k.STALLED_ACTIVITY,stalledParticipants:h};case 3:let b=(0,Ze.decode)(r);return{type:"notification",notification:k.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(b))==null?void 0:n.participantId};case 5:let P=(0,Ze.decode)(r);return{type:"notification",notification:k.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:P[0],maxDimension:P[1]}};case 6:let $=(0,Ze.decode)(r),W={};for(let[L,me]of Object.entries($)){let Ae=(s=this.getStreamDescription(Number(L)))==null?void 0:s.participantId;Ae&&(W[Ae]=me/100)}return{type:"notification",notification:k.NETWORK_STATUS,statuses:W};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return o.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,Ze.decode)(e),i=[];for(let[r,n]of Object.entries(t)){let s=n[0],l=n[1],p=n[2],h;if(s!==null){if(h=this.getStreamDescription(s),!h){o.error(`could not uncompress participant ID ${s}`);continue}}else h=null;if(p===null){o.error("unexpected null sequenceNumber",r,n);continue}let b=Pe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,P=l?l>>>0:null;i.push({participantStreamDescription:h,streamId:b,rtpTimestamp:P,sequenceNumber:p})}return{type:"notification",notification:k.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var dn=90,ln=4294967295,Ce=class extends z{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=U.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,he.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ve.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ve.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,ve.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Qe(this,e),this._serverSettings=i,o.debug("ServerTransport: Created")}getState(){return this._state||U.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==U.IDLE&&e!==U.CLOSED&&e!==U.FAILED&&this._startStatInterval()}open(e=!1){if(this._isOpen){o.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(o.error("ServerTransport: Closed",e),this._setState(U.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(U.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Kt(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,Ce._closeDataChannel(this._producerNotification),Ce._closeDataChannel(this._producerCommand),Ce._closeDataChannel(this._producerScreen),Ce._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){o.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let n=r.readyState;n==="open"?(o.debug(`[${t}] data channel opened`),r.onerror=s=>{o.error(`[${t}] data channel error`,s)},i(r)):o.error(`[${t}] data channel open failed, state [${n}]`)}}_openConnection(e=!1){o.debug("ServerTransport: Open single connection");let t={};C.baseChromeVersion()&&(t.sdpSemantics=Ce._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=S.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Ce._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,Pt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new ki,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,Pt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,Pt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){o.error("ServerTransport: Unable to add media source tracks",i),m.log(_.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,Pt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(U.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==U.OPENED&&(this._setState(U.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(N.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(N.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(N.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(N.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
- `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Pe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!d.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new pt(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!d.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new dt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!d.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==de.video)return;let r=!this._disabledSenders.has(i),n=e.maxDimension!==0;if(r&&!n){o.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(C.getBlackMediaTrack()).catch(l=>{o.error("Could not disable video upload",l)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&n&&s){o.log("Enabling video upload"),this._disabledSenders.delete(i);let l=i.track;l.enabled=s.enabled,i.replaceTrack(s).then(()=>l.stop()).catch(p=>{o.error("Could not enable video upload",p)})}S.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,d.statisticsInterval)};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return c(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield bt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(N.REMOTE_DATA_STATS,{inbound:{topology:Te.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:Te.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=Pe.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(N.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Qe.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:d.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:d.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:d.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:d.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:Ce._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount,red:d.serverAudioRed};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return c(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,o.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(o.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw o.error("[single] unable to set remote offer",i),m.log(_.ERROR,"setRemoteDescription-single"),i}).then(()=>c(this,null,function*(){if(o.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw o.error("[single] unable to create answer",i),m.log(_.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=S.patchSDP(i.sdp,!1,C.isBrokenH264(),!1),i)).then(i=>c(this,null,function*(){if(o.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw o.error("[single] unable to set local answer",i),m.log(_.ERROR,"setLocalDescription-single"),i}).then(i=>c(this,null,function*(){o.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),o.debug("[single] remote offer has been processed")})).catch(i=>{o.warn("[single] unable to send local answer",i),m.log(_.ERROR,"acceptProducer")}).then(()=>c(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){o.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return c(this,null,function*(){if(!!this._isOpen)switch(e.notification){case k.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case k.REALLOC_CON:this._reconnect();break;case k.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case k.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case k.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case k.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return c(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),d.breakVideoPayloadTypes&&(o.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){o.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,i.id,i,n.track)}),i.getTracks().find(n=>n.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(N.REMOTE_TRACK_ADDED,i.id,i,t.track)):o.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){o.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(o.debug("[single] connection state changed",{state:e.connectionState},t),m.log(_.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===U.IDLE||i===U.OPENED?this._setState(U.CONNECTING):e.iceConnectionState==="checking"&&this._setState(U.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(U.RECONNECTING);break;case"connected":this._setState(U.CONNECTED),S.getPeerConnectionHostInfo(e).then(r=>{r&&m.log(_.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(d.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{o.error("ServerTransport: Unable to replace track",r),m.log(_.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=C.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(C.browserName(),Number(C.browserVersion()))}getStreamWaitingTimeMs(e,t){if(!this._pc)return m.log(_.PAT_WAITING_TIME_ERROR,"noConnection"),o.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return m.log(_.PAT_WAITING_TIME_ERROR,"noReceiver"),o.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return o.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return m.log(_.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),o.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let l=t-s&ln,p=Math.ceil(l/dn);return Math.min(100,Math.max(0,p))}};var N=(L=>(L.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",L.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",L.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",L.REMOTE_ALL_STALL="REMOTE_ALL_STALL",L.REMOTE_DATA_STATS="REMOTE_DATA_STATS",L.STATE_CHANGED="STATE_CHANGED",L.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",L.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",L.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",L.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",L.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",L.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",L.NETWORK_STATUS="NETWORK_STATUS",L.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",L))(N||{}),U=(l=>(l.IDLE="IDLE",l.OPENED="OPENED",l.CONNECTING="CONNECTING",l.RECONNECTING="RECONNECTING",l.CONNECTED="CONNECTED",l.CLOSED="CLOSED",l.FAILED="FAILED",l))(U||{}),Te=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(Te||{}),wi=class extends z{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,he.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){o.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,i=!1){let r=!1;for(let n of e){if(this._opened.indexOf(n)!==-1){o.warn(`The participant [${n}] has already had opened transport`);continue}if(this._allocated.indexOf(n)===-1){o.warn(`The participant [${n}] has no allocated transport`);continue}this._opened.push(n),r=!0}!r||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),o.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&o.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===k.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===k.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(o.log(`Topology changed ${this._topology} -> ${e.topology}`),m.log(_.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],n=e.offerToDeviceIdxs||[],s=i.length&&r.length?S.composeParticipantId(i[0],r[0],n[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){o.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&o.warn("Topology changed to DIRECT, but the allocated participants count more then one");let l=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let p=s===l;this._directTransport=this._createDirectTransport(l,p)}this._opened.indexOf(l)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new Xe(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._dtListeners&&this._dtListeners.length>0&&o.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new Ce(this._signaling,this._mediaSource,this._serverSettings);return this._stListeners&&this._stListeners.length>0&&o.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("ACTIVE_PARTICIPANTS_NO_SIGNAL",this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;d.noiseSuppression!==e&&(d.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent("ACTIVE_PARTICIPANTS_NO_SIGNAL")}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(m.log(_.PAT_WAITING_TIME_ERROR,"wrongTopology"),o.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(m.log(_.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var et=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(et||{}),xi=class extends z{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===de.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Rt(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,d.voiceParams.interval)};this._interval=window.setTimeout(n,d.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===de.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===Pe.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var Ni=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(Ni||{}),Li=class extends z{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,et.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,N.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>d.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*d.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent("SPEAKER_CHANGED",e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var Qt=class extends z{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,et.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===U.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),d.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),d.specListenerParams.volumeTimeout))),t===U.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==U.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var pn=1e3,un=1e4;var mn=15,B=class extends z{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=G.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;m.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),m.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new $t,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),pn))}static current(){return B._current}static hangupAfterInit(){B._activationMutex&&!B._current&&(B._delayedHangup=!0)}static id(){var e,t;return((t=(e=B._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,s=!1){return c(this,null,function*(){if(B._activationMutex)throw m.log(_.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new w(M.FAILED);B._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let l=this._mediaSource.getMediaSettings();t===we.CHAT||e.length>1?this._logWithMediaSettings(_.OUTGOING_MULTIPARTY_CALL,l):this._logWithMediaSettings(_.OUTGOING_CALL,l);let p=yield this._startConversation(e,t,Ue.OUTGOING,i,r,n,s);if(!this._conversation)throw new w(M.UNKNOWN_ERROR);if(this._participantState=G.ACCEPTED,this._signaling.changeMediaSettings(l),yield this._registerParticipants(p.conversation.participants),this._processConnectionData(p),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new w(M.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let h=Object.values(this._participants),b;return d.batchParticipantsOnStart&&(b=S.mapSharedParticipants(h)),E.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,b),E.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),B._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(h,Y.WAITING),this._conversation}catch(l){throw this._close(l,"Unable to start conversation"),l}finally{B._activationMutex=!1}})}onJoin(e){return c(this,null,function*(){var t;if(B._activationMutex)throw m.log(_.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new w(M.FAILED);B._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.JOIN_CONVERSATION,r);let n=yield this._joinConversation(e);if(!this._conversation)throw new w(M.UNKNOWN_ERROR);return this._conversation.observer=i,E.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(o.log("In waiting hall"),B._current=this,B._activationMutex=!1,this._signaling.readyToSend(),E.onLocalStatus(Y.WAITING_HALL),this._conversation):this._onJoinPart2(n)}catch(i){throw B._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return c(this,null,function*(){o.debug("Join conversation part 2"),B._activationMutex=!0;try{if(this._participantState=G.ACCEPTED,!this._conversation||!this._mediaSource)throw new w(M.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new w(M.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=S.mapSharedParticipants(t)),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),E.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),B._current=this,d.batchParticipantsOnStart||this._setParticipantsStatus(t,Y.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{B._activationMutex=!1}})}onPush(r){return c(this,arguments,function*(e,t=Q.USER,i){if(B._activationMutex)throw o.warn("Conversation: there is already running activation"),new w(M.REJECTED);B._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new w(M.UNKNOWN_ERROR);if(!n.conversation.participants.find(l=>{var p;return l.state===G.CALLED&&l.id===((p=this._conversation)==null?void 0:p.userId)}))throw o.log("Push rejected (there is an active call)"),m.log(_.PUSH,"rejected"),new w(M.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),m.log(_.PUSH,"accepted"),B._current=this,B._delayedHangup)throw new w(M.CANCELED);B._activationMutex=!1}catch(n){throw B._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(kt.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>S.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return c(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new w(M.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),E.onCallAccepted(),this._state="ACTIVE",this._participantState=G.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return c(this,null,function*(){if(this._state!=="IDLE")throw m.log(_.ERROR,"acceptIncoming"),o.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new w(M.UNKNOWN_ERROR);this._state="PROCESSING",o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=G.ACCEPTED;let i=Object.values(this._participants),r;d.batchParticipantsOnStart&&(r=S.mapSharedParticipants(i)),E.onCallAccepted(),E.onLocalStream(this._mediaSource.getStream(),t),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),E.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(Be.MUTE)||n.includes(Be.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),d.batchParticipantsOnStart||this._setParticipantsStatus(i,Y.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return c(this,null,function*(){var e;if(this._state!=="IDLE")throw m.log(_.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",o.debug("Decline incoming call"),this._logWithMediaSettings(_.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=G.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(M.REJECTED)),this._close(new w(M.REJECTED))})}hangup(){return c(this,null,function*(){o.debug("Hangup");let e=this._state==="ACTIVE"?M.HUNGUP:M.CANCELED;m.log(_.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new w(e))):E.onHangup(new w(M.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return c(this,null,function*(){if(!this._signaling.ready){this._close(new w(M.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=M.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(S.composeId(n),n,r)})}removeParticipant(e,t=!1){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let n of e)(n.state===G.CALLED||n.state===G.ACCEPTED)&&(this._transport.isAllocated(n.id)||this._transport.allocate(n.id,t)),n.state===G.ACCEPTED&&i.push(n.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&o.error(t,e),o.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(M.FAILED):m.log(_.ERROR,e.hangup),B._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([M.CANCELED,M.NOT_FRIENDS,M.CALLEE_IS_OFFLINE,M.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===M.REJECTED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===M.HUNGUP&&(!e.remote||this._participantState===G.CALLED)){E.onHangup(e,i),this.destroy();return}if(e.hangup===M.MISSED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===M.SOCKET_CLOSED&&B._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===M.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=G.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),m.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,E.onHangup(e||new w(M.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;o.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),m.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return c(this,null,function*(){let t=yield this._api.getConversationParams(e);o.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let s=r.urls.filter((l,p,h)=>h.indexOf(l)===p);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return d.iceServers=i,d.wssBase=t.endpoint,d.wssToken=t.token,t.client_type&&(d.clientType=t.client_type),t})}_startConversation(e,t,i,r,n="",s=!1,l=!1){return c(this,null,function*(){let p=S.uuid();o.debug("Conversation: start",{conversationId:p,opponentIds:e,opponentType:t,direction:i});let h=r.includes(se.VIDEO),b=yield this._api.startConversation(p,e,t,h,n,s,l);o.debug("Api.startConversation",b),yield this._getConversationParams(b.id);let P=yield this._connectSignaling(xe.START,b);return yield this._setConversation(b,P,i),P})}_joinConversation(e){return c(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n,observedIds:s}=e;o.debug("Conversation: join",{conversationId:t,joinLink:n,observedIds:s});let l=i.includes(se.VIDEO),p;if(t)p=yield this._api.joinConversation(t,l,r);else if(n)p=yield this._api.joinConversationByLink(n,l,s);else throw new w(M.UNKNOWN_ERROR);o.debug("Api.joinConversation",p),yield this._getConversationParams(p.id);let h=yield this._connectSignaling(xe.JOIN,p);return yield this._setConversation(p,h,Ue.JOINING),h})}_prepareConversation(r){return c(this,arguments,function*(e,t=Q.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let n=this._api.getUserId();if(!n)throw new w(M.UNKNOWN_ERROR);let l=(yield this._getConversationParams(e)).device_idx||0,p={id:e,peerId:i,endpoint:`${d.wssBase}?userId=${n}&entityType=${t}&deviceIdx=${l}&conversationId=${e}&token=${d.wssToken}`,is_concurrent:!1,p2p_forbidden:!1,device_idx:l},h=yield this._connectSignaling(xe.ACCEPT,p);return B._current&&(B._current._participantState===G.ACCEPTED||B._current._participantState===G.CALLED)?(o.log("Push rejected (busy)"),m.log(_.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(M.BUSY),Promise.reject({hangup:M.BUSY})):(B._current&&(B._current.destroy(),B._current=null),yield this._setConversation(p,h,Ue.INCOMING,t),h)})}_createParticipant(e){return c(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:ge(),participantState:{},state:G.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[]},e);if(e.externalId){let r=S.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(r,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return((i=t.observedIds)==null?void 0:i.length)&&(t.externalId.observer=!0),t})}_getParticipantId(e){return c(this,null,function*(){try{let t=S.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new w(M.NETWORK_ERROR),t),t}})}_setConversation(n,s,l){return c(this,arguments,function*(e,t,i,r=Q.USER){let p=t.conversation.participants.map(W=>W.id);yield this._api.prepareUserIds(p);let h=this._api.getUserId(),b=e.device_idx||0;if(!h){let W=(t.conversation.participants||[]).find(L=>S.comparePeerId(L.peerId,t.peerId));if(!W)throw new w(M.UNKNOWN_ERROR);h=Number(W.id),W.idType&&(r=W.idType),W.deviceIdx&&(b=W.deviceIdx),this._api.setUserId(h)}let P=S.composeParticipantId(h,r,b),$=yield this._getParticipantId(P);this._conversation={userId:h,compositeUserId:P,externalId:$,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||Te.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),m.log(_.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new w(M.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||Te.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new ui;return this.subscribe(e,ve.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,ve.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new yt(e),e}_connectSignaling(e,t){return c(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,he.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,he.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,he.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return c(this,null,function*(){if(!!this._conversation)for(let t of e){let i=S.composeId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),E.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===G.HUNGUP||t.state===G.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],M.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&ue.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:ge(t.mediaSettings),participantState:S.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?Y.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),E.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){S.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Ot.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new wi(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new qt,this.subscribe(this._transport,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,N.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,N.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,N.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,N.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,N.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,N.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,N.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,N.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Ue.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===G.ACCEPTED||t.state===G.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new xi(this._transport),this.subscribe(this._volumesDetector,et.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Li(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,Ni.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Jt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Qt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=C.getCameras().length,t=C.getMicrophones().length;o.debug("Cameras: "+e+(C.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(C.hasMicrophonePermission()?"✔":"✖")),m.log(_.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){m.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===G.CALLED||e.state===G.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===M.HUNGUP?this._setParticipantsStatus([e],Y.HANGUP):this._setParticipantsStatus([e],Y.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Se.CAMERA,stopStream:!0}]),delete this._participants[e.id],E.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){o.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return c(this,null,function*(){o.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===G.ACCEPTED||r.state===G.CALLED)){o.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&ue.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:ge(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}),r=this._participants[e]),this._setParticipantsStatus([r],Y.WAITING),i?(r.state=G.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=G.CALLED,this._transport.allocate(r.id,!0),m.log(_.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){o.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=mn;i++){let r=S.compose(e,i),n=this._participants[r];n&&t.push(n)}if(!t.length){o.warn(`Participant [${e}] isn't in conversation`);return}if(this._transport)for(let i of t)this._transport.close(i.id);m.log(_.REMOVE_PARTICIPANT)}changeDevice(e){return c(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new yt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ee.UNKNOWN)})}toggleScreenCapturing(e){return c(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ee.UNKNOWN)})}setVideoStream(e,t=!1){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return c(this,null,function*(){if(this._mediaSource)return m.log(_.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return c(this,null,function*(){if(this._mediaSource)return m.log(_.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return c(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let n=typeof r.uid=="object"?r.uid:ue.fromId(r.uid),s=ue.toString(n);i[s]=r.priority}for(let r of Object.values(this._participants)){let n=ue.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return c(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return c(this,null,function*(){let t={};return t[Fe(e)]="kf",this._signaling.updateDisplayLayout(t)})}updateDisplayLayout(e){return c(this,null,function*(){if(e.length<1||!this._signaling.ready)return;o.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:ue.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(n);if(!s){let b=ue.toString(n);o.log(`Unknown participant external ID ${b}`);continue}let l=S.compose(s,n.deviceIdx),p=Fe({participantId:l,mediaType:r.mediaType,streamName:r.streamName}),h=this._participants[l];h&&(h.lastRequestedLayouts[p]=r),B._isStopStreaming(r)?this._streamIdByStreamDescription.has(p)&&!this._cooldownTimestampByStreamDescription.has(p)&&this._cooldownTimestampByStreamDescription.set(p,Date.now()):(this._cooldownTimestampByStreamDescription.delete(p),!this._streamIdByStreamDescription.has(p)&&d.videoTracksCount>0&&this._streamIdByStreamDescription.set(p,null),t[p]=B._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>d.videoTracksCount;){let r=i.next();if(r.done){o.error("Cannot accommodate all streaming requests: tracks available "+d.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]=B._layoutToString({stopStream:!0})}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(o.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Ct(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Se.STREAM||i.mediaType===Se.SCREEN)?E.onRemoteLive(r.externalId,i.streamName,null):E.onRemoteStream(r.externalId,null),m.log(_.PAT_DEALLOCATED)):o.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return c(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,n]of Object.entries(t.errorCodeByParticipantId||{})){let s=Ct(r),l=this._participants[s.participantId];if(l){let p;typeof n!="number"?(o.warn(`Unexpected error code ${n} received for participant ${s.participantId}`),p=hr.UNKNOWN_ERROR):p=_r(n),i.push({externalId:l.externalId,errorReason:p})}}if(i&&i.length)throw new Xt("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+un>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=B._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(B._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),t}_onParticipantSourcesUpdate(e){if(this._conversation){o.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return c(this,null,function*(){o.log("Promoted in waiting hall",!e.demote),e.demote?(o.log("Kicked from waiting hall"),this._close(new w(M.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return c(this,arguments,function*(e,t=0,i=[]){o.log(`Chat room updated: ${e}`);let n=[],s=[];i.length&&(i.forEach(l=>{if(l.externalId){let p=pe.fromSignaling(l.externalId);n.push(p),this._api.cacheExternalId(l.id.id,p)}else s.push(S.decomposeId(l.id.id).id)}),s.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(s))),E.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var l,p;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===Se.SCREEN)return;let i=Fe(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){o.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),m.log(_.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let h=t.participantId,b=this._participants[h];if(!b){m.log(_.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${h}`);return}let P=this._streamByStreamId.get(n);if(!P){m.log(_.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}m.log(_.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let $=(l=e.participantStreamDescription)==null?void 0:l.mediaType;if($===Se.STREAM||$===Se.MOVIE)((p=e.participantStreamDescription)==null?void 0:p.streamName)&&E.onRemoteLive(b.externalId,e.participantStreamDescription.streamName,P);else{let W=(d.producerScreenTrack?null:b.secondStream)||P;E.onRemoteStream(b.externalId,W)}}else{o.debug(`Waiting for ${s} until stream ${n} for ${i} is switched`);let h=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,h)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Fe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Fe(i)))return i}else{let i={participantId:t,mediaType:Se.CAMERA};if(this._streamIdByStreamDescription.has(Fe(i)))return i;let r={participantId:t,mediaType:Se.SCREEN};if(this._streamIdByStreamDescription.has(Fe(r)))return r}return o.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?S.includesOneOf(this._conversation.roles,[je.ADMIN,je.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!S.includesOneOf(this._conversation.roles,[je.ADMIN,je.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return c(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return c(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return c(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=ir(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return c(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=$r(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let s=n.participants||[],l=[],p=[],h=null;return s.length&&(s.forEach(b=>{if(b.externalId){let P=pe.fromSignaling(b.externalId);l.push(P),this._api.cacheExternalId(b.id.id,P)}else p.push(S.decomposeId(b.id.id).id)}),p.length&&!l.length&&(l=yield this._api.getExternalIdsByOkIds(p)),n.hasMore&&(h=Kr(s[s.length-1].id))),{participants:l,pageMarker:h,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return c(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return c(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return c(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return c(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return c(this,null,function*(){var l;let n={movieId:e,participantId:(l=this._conversation)==null?void 0:l.compositeUserId};(t||t===0)&&(n.gain=t),i&&(n.offset=i),typeof r!==void 0&&(n.pause=r);let s=yield this._signaling.updateMovie(n);if(s.error)throw new Error(s.error)})}removeMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",n=null){return c(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},l=yield this._signaling.startStream(s);return l.error?Promise.reject(l.message):l})}stopStream(){return c(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return c(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return c(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return c(this,null,function*(){var r;if(e<d.videoMinWidth||t<d.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<d.videoMinWidth||i.effect.height<d.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");d.videoEffectMaxHeight=i.effect.height,d.videoEffectMaxWidth=i.effect.width}return d.videoMaxWidth=e,d.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return c(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return c(this,null,function*(){var t,i;!this._conversation||(o.debug("Local media stream changed",e.mediaSettings),E.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return c(this,null,function*(){var t,i;if(o.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;E.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){o.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&E.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){o.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&(d.participantStateMapped?E.onRemoteParticipantState(i.externalId,i.participantState):E.onRemoteParticipantState(i.externalId,S.mapLegacyParticipantState(i.participantState))))}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(o.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),E.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case k.ACCEPTED_CALL:return this._onAcceptedCall(e);case k.HUNGUP:return this._onHungup(e);case k.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case k.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case k.CLOSED_CONVERSATION:return this._onClosedConversation(e);case k.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case k.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case k.RATE_CALL_DATA:return this._onNeedRate();case k.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case k.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case k.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case k.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case k.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case k.REGISTERED_PEER:return this._onPeerRegistered(e);case k.SWITCH_MICRO:return this._onMicSwitched(e);case k.CHAT_MESSAGE:return this._onChatMessage(e);case k.CUSTOM_DATA:return this._onCustomData(e);case k.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case k.RECORD_STOPPED:return this._onRecordInfo(null);case k.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case k.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case k.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case k.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case k.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case k.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case k.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return c(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let s=S.composeId(n),l=n.roles||[];if(s===this._conversation.compositeUserId){t=ge(n.mediaSettings),gt(this._conversation.roles,l)||this._onRolesChanged(s,l);continue}r.push(s);let p=this._participants[s];if(!p)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let h=ge(n.mediaSettings);yr(h,p.mediaSettings)||this._changeRemoteMediaSettings(s,h);let b=S.mapParticipantState(n),P=p.participantState;S.isEqualParticipantState(b,P)||this._changeRemoteParticipantState(s,b),gt(l,p.roles)||this._onRolesChanged(p.id,l)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],M.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){o.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return c(this,null,function*(){let t=S.composeMessageId(e),i=S.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new w(M.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:ge(e.mediaSettings)}),r=this._participants[t]),r.state=G.ACCEPTED,r.mediaSettings=ge(e.mediaSettings),this._logWithMediaSettings(_.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Ue.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){o.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=S.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new w(e.reason,{remote:!0}));return}let i=this._participants[t];if(!i){o.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===M.REJECTED?G.REJECTED:G.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,M.HUNGUP)}_onAddedParticipant(e){return c(this,null,function*(){var r,n;o.debug(`Participant added [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state!==G.HUNGUP&&i.state!==G.REJECTED){o.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&ue.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}),i=this._participants[t]),i.state=G.CALLED,i.mediaSettings=ge((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=S.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],Y.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return c(this,null,function*(){var r,n;o.debug(`Participant joined [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state===G.ACCEPTED){o.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&ue.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Ue.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=G.ACCEPTED,i.mediaSettings=ge(e.mediaSettings),i.participantState=S.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],Y.CONNECTED):this._setParticipantsStatus([i],Y.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((n=this._conversation)==null?void 0:n.observer))),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new w(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=S.composeMessageId(e);this._changeRemoteMediaSettings(t,ge(e.mediaSettings))}_onParticipantStateChanged(e){let t=S.composeMessageId(e);this._changeRemoteParticipantState(t,S.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),E.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return c(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ge(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),d.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Ai(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=Ai(this._serverSettings,r),o.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=S.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return c(this,null,function*(){E.onDeviceSwitched(se.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return c(this,null,function*(){let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),E.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return c(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),E.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return c(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getParticipantId(e.initiator);E.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else E.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!gt(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,E.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!gt(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,E.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return c(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){o.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let l=this._participants[e.participantId];l&&(o.debug(`Mute states for participant [${e.participantId}] changed`,i),E.onMuteStates(i,r,n,e.muteAll,e.unmute,l.externalId,s==null?void 0:s.externalId));return}S.isObjectsEquals(this._conversation.muteStates,i)&&S.isArraysEquals(this._conversation.unmuteOptions,r)&&!n.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(n,e.muteAll,e.unmute,t,s)))})}_processMuteState(){return c(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==G.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),l=this._conversation.unmuteOptions,p=this._mediaSource.getMediaSettings(),h=Object.entries(s);for(let[b,P]of h)if(!(P!==Be.MUTE&&P!==Be.MUTE_PERMANENT)&&(this._isCallAdmin()&&P===Be.MUTE_PERMANENT&&(s[b]=Be.MUTE),!(!e.includes(b)||i)))switch(b){case se.VIDEO:p.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(E.onDeviceSwitched(se.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case se.AUDIO:p.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(E.onDeviceSwitched(se.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case se.SCREEN_SHARING:p.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(E.onDeviceSwitched(se.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}E.onMuteStates(s,l,e,t,i,null,n==null?void 0:n.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?E.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&E.onLocalPin(!0)),this._participants[e]?E.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&E.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!tr(this._conversation.options,e)&&(this._conversation.options=e,E.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let n;if(i===this._conversation.compositeUserId||i==="")n=this._conversation.networkRating;else if(this._participants[i])n=this._participants[i].networkRating;else continue;if(n!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,E.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;o.log("Received network status update: ",e),E.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){E.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,d.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){o.error("Received remote stream notification for a participant that has no track associated with it",r);return}let n=this._streamIdByStreamDescription.get(r);if(!n||this._streamWaitTimerByStreamDescription.has(r)){o.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(n);if(!s){m.log(_.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}E.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&E.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===Te.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Zi.ADD_PARTICIPANT);E.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&E.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}E.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return c(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===U.CONNECTED?i=Y.CONNECTED:t===U.CONNECTING||t===U.OPENED?i=Y.CONNECTING:t===U.RECONNECTING&&(i=Y.RECONNECT),!i)return;let r=e.reduce((n,s)=>{if(s in this._participants){let l=this._participants[s];n.push(l),t===U.CONNECTED&&(l.remoteStream||(l.mediaSettings&&this._changeRemoteMediaSettings(s,l.mediaSettings),this._changeRemoteParticipantState(s,l.participantState)),this._updateDisplayLayoutFromCache(s))}else o.warn(`Participant [${s}] isn't in conversation`);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return c(this,null,function*(){o.debug(`Local transport state has changed: ${e}`),e===U.CONNECTED&&E.onLocalStatus(Y.CONNECTED),e===U.CONNECTING&&E.onLocalStatus(Y.CONNECTING),e===U.RECONNECTING&&E.onLocalStatus(Y.RECONNECT),e===U.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(M.FAILED)),this._close(new w(M.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return c(this,null,function*(){if(e.endsWith(Pe.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(Pe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))o.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{o.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(o.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],Y.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===de.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;E.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),d.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(o.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case de.audio:this._removeAudioTrack(e,t,i);break;case de.video:case de.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Pe.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onRemoteActivityNoSignal(){this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)}_onTopologyChanged(e){this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let n=this._participants[r];e||this._lastStalled[r]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,Y.RECONNECT),i.length&&this._setParticipantsStatus(i,Y.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let s=this._participants[n];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let s=this._participants[n];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,Y.RECONNECT),r.length&&this._setParticipantsStatus(r,Y.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!C.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),E.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return c(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==Te.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,s)=>(s.status!==t&&(s.status=t,d.batchParticipantsOnStart?n.push(s.externalId):E.onParticipantStatus(s.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&E.onRemoteStatus(r,t,i)}},x=B;x._delayedHangup=!1;var Xt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Xt.prototype),this.participantErrors=t}};var Zt;function hn(){return c(this,null,function*(){var a;if(d.apiEnv!=="AUTO")return d.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(a=i==null?void 0:i.Answer[0])==null?void 0:a.data;if(!r)throw new Error("Wrong DNS response");return o.debug("Resolved API endpoint",r),r}catch(e){return o.warn("Failed to resolve API endpoint using DNS, default is used",e),d.apiEndpoint}})}function zr(){if(!d.apiKey)throw new w(ee.API,{message:"Required argument apiAppKey not passed"})}function Ui(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Xr(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${Zt}/fb.do`,r)}function Qr(i){return c(this,arguments,function*(a,e={},t=!1){Zt||(Zt=yield hn());let r=Xr(a,e,t);return _n(r)})}function _n(a){return c(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${Zt}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(n){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(a)})})}function Xr(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=d.apiKey),t||(Z.sessionKey?e.session_key=Z.sessionKey:Z.accessToken&&(e.access_token=Z.accessToken));for(let[r,n]of Object.entries(e))typeof n=="object"&&(e[r]=JSON.stringify(n));let i="";for(let[r,n]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(n)}`;return i}var fn=10,Sn=700,vn=3e3,Mt=class extends tt{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return c(this,arguments,function*(e,t={},i=!1){let n=s=>c(this,null,function*(){try{return yield Qr(e,t,i)}catch(l){if(!l.hasOwnProperty("error_msg")&&(s++,o.debug(`${e} network error, attempt ${s}...`),s<fn))return yield S.delay(Math.min(s*Sn,vn)),n(s);throw o.warn(e,"error",l),l}});return n(0)})}_call(r){return c(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){o.warn("Api call error",n);let s=ee.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=M.SERVICE_DISABLED;break;case 1102:s=M.CALLEE_IS_OFFLINE;break;case 1103:s=M.NOT_FRIENDS;break;case 1104:case 1106:s=M.EXTERNAL_API_ERROR;break}throw new w(s,{message:n.error_msg,code:n.error_code})}})}userId(e){return c(this,null,function*(){let t=S.decomposeId(e).id;return Z.isEmpty()?pe.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),pe.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return c(this,null,function*(){Z.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return c(this,null,function*(){if(!this._uuid){let t=Ve.get("uuid");t||(t=S.uuid(),Ve.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:d.appVersion,client_type:"SDK_JS"}};return d.authToken&&(e.session_data.auth_token=d.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),Z.sessionKey=t.session_key,Z.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&E.onTokenExpired(),new w(ee.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${d.appName}:${d.sdkVersion}`,platform:d.platform,items:e})};Ui("log.externalLog",t)}init(){zr()}joinConversation(e,t=!1,i){return c(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:d.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return c(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1};return t&&(r.payload=t),d.domain&&(r.domainId=d.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,n="",s=!1,l=!1){return c(this,null,function*(){let p={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case we.USER:p.uids=t.join(",");break;case we.GROUP:p.gid=t[0];break;case we.CHAT:p.chatId=t[0];break}return s&&(p.createJoinLink=!0),n&&(p.payload=n),d.domain&&(p.domainId=d.domain),l&&(p.requireAuthToJoin=!0),this._startConversation(p)})}_startConversation(e){return c(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return c(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return c(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return c(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i){return c(this,null,function*(){let r={joinLink:e,isVideo:t,protocolVersion:d.protocolVersion};return(i==null?void 0:i.length)&&(r.observedIds=i.join(",")),d.anonymToken&&(r.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",r)})}getOkIdsByExternalIds(e){return c(this,null,function*(){let t=pe.fromIds(e),i=[],r={methods:[]},n=[],s=Object.keys(this._externalUidsCache),l=Object.values(this._externalUidsCache);for(let h of t){let b=pe.toString(h),P=l.indexOf(b);P>-1?i.push(Number(s[P])):(n.push(b),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:h.id,anonym:h.type===ze.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((h,b)=>{if(h.ok){let P=Number(h.ok.ok_id);this._externalUidsCache[P]=n[b],i.push(P)}}),i})}getExternalIdsByOkIds(e){return c(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(pe.fromString(this._externalUidsCache[n])):i.push(n);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let n of i)r.hasOwnProperty(n)&&t.push(pe.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=pe.toString(e),n=i.indexOf(r);return n>-1?S.composeUserId(t[n],Q.USER):null}cacheExternalId(e,t){let i=S.decomposeId(e).id;this._externalUidsCache[i]=pe.toString(t)}getConversationParams(e){return c(this,null,function*(){let t={};return d.anonymToken&&(t.anonymToken=d.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:M.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),Ui("vchat.hangupConversation",t)}removeHistoryRecords(e){return c(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return c(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,n]of Object.entries(i.external_ids))t[r]=pe.fromIdToString(n,ze.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=pe.fromIdToString(n,ze.ANONYM);return t}catch(i){return t}})}};var Zr=(T=>(T.RECOVER="recover",T.ACCEPT_CALL="accept-call",T.ADD_PARTICIPANT="add-participant",T.REMOVE_PARTICIPANT="remove-participant",T.HANGUP="hangup",T.TRANSMIT_DATA="transmit-data",T.ACCEPT_PRODUCER="accept-producer",T.ALLOCATE_CONSUMER="allocate-consumer",T.CHANGE_MEDIA_SETTINGS="change-media-settings",T.CHANGE_PARTICIPANT_STATE="change-participant-state",T.CHANGE_STREAM_PRIORITIES="change-streams-priorities",T.UPDATE_DISPLAY_LAYOUT="update-display-layout",T.REPORT_PERF_STAT="report-perf-stat",T.RECORD_START="record-start",T.RECORD_STOP="record-stop",T.RECORD_SET_ROLE="record-set-role",T.RECORD_GET_STATUS="record-get-status",T.SWITCH_MICRO="switch-micro",T.SWITCH_TOPOLOGY="switch-topology",T.REQUEST_REALLOC="request-realloc",T.CHAT_MESSAGE="chat-message",T.CHAT_HISTORY="chat-history",T.CUSTOM_DATA="custom-data",T.GRANT_ROLES="grant-roles",T.MUTE_PARTICIPANT="mute-participant",T.PIN_PARTICIPANT="pin-participant",T.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",T.CHANGE_OPTIONS="change-options",T.GET_WAITING_HALL="get-waiting-hall",T.PROMOTE_PARTICIPANT="promote-participant",T.REQUEST_TEST_MODE="request-test-mode",T.ADD_MOVIE="add-movie",T.UPDATE_MOVIE="update-movie",T.REMOVE_MOVIE="remove-movie",T))(Zr||{}),H=Zr;var ea="open",ta=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0,()=>d.movieShare],En=10,ye=class extends rt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+d.platform+"&appVersion="+d.appVersion+"&version="+d.protocolVersion+"&device="+d.device+"&capabilities="+ye._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null}static _getCapabilityFlags(){let e=0;for(let t=0;t<ta.length;t++)ta[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return c(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){m.log(_.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return c(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=S.decomposeParticipantId(t.participantId),s=S.decomposeId(n.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),n.deviceIdx&&(t.deviceIdx=n.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return c(this,arguments,function*(e,t={},i=0){let n=s=>{var p;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((p=this.producerCommandDataChannel)==null?void 0:p.readyState)===ea&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){m.log(_.SOCKET_ACTION,"not_opened"),o.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(m.log(_.SOCKET_ACTION,"invalid_state"),o.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,l)=>{let p=(b,P=!1)=>{!i||P?l(b):(o.debug("Resending a signaling message",e,h.sequence),i--,n(h))},h={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:p};n(h)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return c(this,null,function*(){return this._send(H.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return c(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return c(this,null,function*(){return this._send(H.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return c(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return c(this,null,function*(){return this._send(H.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return c(this,null,function*(){return this._send(H.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},En)})}changeParticipantState(e){return c(this,null,function*(){return this._send(H.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return c(this,null,function*(){return this._send(H.ADD_PARTICIPANT,qi({participantId:e},t))})}removeParticipant(e,t=!1){return c(this,null,function*(){return this._send(H.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return c(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(H.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return c(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(H.ACCEPT_PRODUCER,i)})}changePriorities(e){return c(this,null,function*(){return this._send(H.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return c(this,null,function*(){return this._send(H.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return c(this,null,function*(){return this._send(H.ADD_MOVIE,e)})}updateMovie(e){return c(this,null,function*(){return this._send(H.UPDATE_MOVIE,e)})}removeMovie(e){return c(this,null,function*(){return this._send(H.REMOVE_MOVIE,e)})}startStream(e){return c(this,null,function*(){return this._send(H.RECORD_START,e)})}stopStream(){return c(this,null,function*(){return this._send(H.RECORD_STOP)})}recordSetRole(e,t){return c(this,null,function*(){return this._send(H.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return c(this,null,function*(){return this._send(H.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return c(this,null,function*(){return this._send(H.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return c(this,null,function*(){return this._send(H.REQUEST_REALLOC)})}reportPerfStat(e){return c(this,null,function*(){return this._send(H.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return c(this,null,function*(){return this._send(H.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return c(this,null,function*(){return this._send(H.CHAT_HISTORY,{count:e})})}customData(e,t){return c(this,null,function*(){return this._send(H.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return c(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(H.GRANT_ROLES,r)})}muteParticipant(e,t,i){return c(this,null,function*(){return this._sendRaw(H.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return c(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(H.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return c(this,null,function*(){return this._send(H.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return c(this,null,function*(){return this._send(H.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return c(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(H.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return c(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(H.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===xe.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),o.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){o.debug("Socket opened"),m.log(_.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){m.log(_.SOCKET_ACTION,"parse_error"),o.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(o.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(he.RECONNECT,e),e.conversation.topology&&this._triggerEvent(he.NOTIFICATION,{type:"notification",notification:k.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(he.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(m.log(_.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(m.log(_.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new w(M.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(he.NOTIFICATION,{notification:k.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new w(ee.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(m.log(_.SOCKET_ACTION,"unknown_message"),o.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(he.FAILED,e)}_onError(e){m.log(_.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){m.log(_.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<ye.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(ye.RECONNECT_MAX_DELAY,ye.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),m.log(_.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,xe.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],m.log(_.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),ye.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),n=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==ea){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}ye._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),ye.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(n))}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),ye.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(n))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new w(ee.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},ye.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{o.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(xe.RETRY)},ye.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},De=ye;De.RECONNECT_DELAY=d.signalingReconnectDelay,De.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,De.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,De.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,De.WAIT_RESPONSE_DELAY=d.waitResponseDelay,De.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var ia=(t=>(t.KING="KING",t.PAWN="PAWN",t))(ia||{}),ra=ia;var mt,ae,Dt=null,Tn={getCameras:C.getCameras,getMicrophones:C.getMicrophones,getOutput:C.getOutput,hasCamera:C.hasCamera,hasMicrophone:C.hasMicrophone,getSavedCamera:C.getSavedCamera,getSavedMicrophone:C.getSavedMicrophone,getSavedOutput:C.getSavedOutput,hasCameraPermission:C.hasCameraPermission,hasMicrophonePermission:C.hasMicrophonePermission,hasPermissions:C.hasPermissions,getUserMedia:C.getUserMedia,getUserVideo:C.getUserVideo,getUserAudio:C.getUserAudio,saveDeviceId:C.saveDeviceId,isBrowserSupported:C.isBrowserSupported,isScreenCapturingSupported:C.isScreenCapturingSupported,os:C.os,isMobile:C.isMobile,browserName:C.browserName,browserVersion:C.browserVersion,baseChromeVersion:C.baseChromeVersion,getAudioContext:C.getAudioContext};function aa(a){ae=a}function na(a){mt=a}function In(a){Dt=a}function Cn(a){d.videoEffects=a}function yn(a){return c(this,null,function*(){if(d.set(a),C.browserName()==="Sferum"&&(d.platform=`SFERUM:${C.browserVersion()}`),ae||aa(new Mt),mt||na(()=>new De),d.debug&&(Bi.default.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${d.sdkVersion}`,a),yield C.init(),!C.isBrowserSupported())throw new w(ee.UNSUPPORTED);ae.init()})}function Rn(n){return c(this,arguments,function*(a,e=[se.AUDIO],t="",i=!1,r=!1){let s=[],l=[];if(Array.isArray(a)?s=a.length?a:[]:a&&(s=[a]),s.length&&(l=yield ae.getOkIdsByExternalIds(s),!l.length))throw new w(M.CALLEE_IS_OFFLINE);return sa(l,we.USER,e,t,i,r)})}function sa(s){return c(this,arguments,function*(a,e=we.USER,t,i="",r=!1,n=!1){if(x.current())throw o.error("There is already active call"),new w(M.FAILED);return new x(ae,mt(),Dt).onStart(a,e,t,i,r,n)})}function bn(a){return c(this,null,function*(){return oa(a)})}function oa(i){return c(this,arguments,function*(a,e=Q.USER,t){if(a===x.id())throw new Error("Push has already been processed");return new x(ae,mt(),Dt).onPush(a,e,t)})}function Pn(a){return c(this,null,function*(){return a&&(d.authToken=a),ae.authorize()})}function Mn(){return c(this,arguments,function*(a=[se.AUDIO]){let e=x.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function Dn(){return c(this,null,function*(){let a=x.current();if(a)return a.decline()})}function An(t){return c(this,arguments,function*(a,e=[se.AUDIO]){return ca(a,e)})}function ca(a,e,t){return c(this,null,function*(){if(x.current())throw o.error("There is already active call"),new w(M.FAILED);return new x(ae,mt(),Dt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function On(r){return c(this,arguments,function*(a,e=[se.AUDIO],t,i){if(x.current())throw o.error("There is already active call"),new w(M.FAILED);return t&&(d.anonymToken=t),new x(ae,mt(),Dt).onJoin({joinLink:a,mediaOptions:e,observedIds:i})})}function kn(){return c(this,null,function*(){let a=x.current();if(a)return a.hangup();x.hangupAfterInit()})}function wn(a,e){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return da(t[0],e)})}function da(a,e){return c(this,null,function*(){let t=x.current();t&&(yield t.addParticipant(S.composeUserId(a,Q.USER),e))})}function xn(a,e=!1){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);return la(t[0],e)})}function la(a,e=!1){return c(this,null,function*(){let t=x.current();t&&(yield t.removeParticipant(S.composeUserId(a,Q.USER),e))})}function Nn(a,e){return c(this,null,function*(){let t=yield C.saveDeviceId(a,e),i=x.current();return t&&i?i.changeDevice(a):Promise.reject()})}function Ln(a){return c(this,null,function*(){let e=x.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function Un(a,e=!1){return c(this,null,function*(){let t=x.current();t&&(yield t.setVideoStream(a,e))})}function Bn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalVideo(a))})}function Vn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalAudio(a))})}function Fn(a,e,t){return c(this,null,function*(){let i=x.current();if(i)return i.setLocalResolution(a,e,t)})}function Hn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.changePriorities(a))})}function Gn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.changeParticipantState(a))})}function Wn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.updateDisplayLayout(a))})}function jn(a,e,t=!1){return c(this,null,function*(){let i=yield ae.getOkIdsByExternalIds([a]);return pa(i[0],e,t)})}function pa(a,e,t=!1){return c(this,null,function*(){let i=x.current();i&&(yield i.grantRoles(S.composeUserId(a,Q.USER),e,t))})}function Kn(){return c(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield ae.getOkIdsByExternalIds([a]))[0]),ua(i,e,t,ue.getDeviceIdx(a))})}function ua(){return c(this,arguments,function*(a=null,e,t=[],i=0){let r=x.current();if(r){let n=a?S.composeParticipantId(a,Q.USER,i):null;yield r.muteParticipant(n,e,t)}})}function $n(a,e=!1){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);return ma(t[0],e,ue.getDeviceIdx(a))})}function ma(a,e=!1,t=0){return c(this,null,function*(){let i=x.current();i&&(yield i.pinParticipant(S.composeParticipantId(a,Q.USER,t),e))})}function qn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.updateMediaModifiers(a))})}function Jn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.changeOptions(a))})}function Yn(a,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),ha(a,t)})}function ha(a,e=null){return c(this,null,function*(){let t=x.current();if(t){let i=e?S.composeUserId(e,Q.USER):null;yield t.chatMessage(a,i)}})}function zn(a=10){return c(this,null,function*(){let e=x.current();if(e)return e.chatHistory(a)})}function Qn(a,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),_a(a,t,ue.getDeviceIdx(e))})}function _a(a,e=null,t=0){return c(this,null,function*(){let i=x.current();if(i){let r=e?S.composeParticipantId(e,Q.USER,t):null;yield i.customData(a,r)}})}function Xn(a="",e=!1){return c(this,null,function*(){return(yield ae.createConversation(S.uuid(),a,e)).join_link})}function Zn(){return c(this,null,function*(){let a=x.current();return a?a.createJoinLink():Promise.reject()})}function es(){return c(this,null,function*(){let a=x.current();return a?a.removeJoinLink():Promise.reject()})}function ts(a,e){return c(this,null,function*(){return ae.getAnonymTokenByLink(a,e)})}function is(a){let e=x.current();e&&e.setVolume(a)}function rs(a){d.forceRelayPolicy=a}function as(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return c(this,null,function*(){let n=x.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function ns(){return c(this,null,function*(){let a=x.current();return a?a.stopStream():Promise.reject()})}function ss(a,e){return c(this,null,function*(){let t=x.current();if(t){let i=yield ae.getOkIdsByExternalIds([a]),r=ue.getDeviceIdx(a);return t.recordSetRole(S.composeParticipantId(i[0],Q.USER,r),e)}return Promise.reject()})}function os(){return c(this,null,function*(){let a=x.current();return a?a.getStreamInfo():Promise.reject()})}function cs(a){return c(this,null,function*(){let e=x.current();return e?e.addMovie(a):Promise.reject()})}function ds(a,e,t,i){return c(this,null,function*(){let r=x.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function ls(a){return c(this,null,function*(){let e=x.current();return e?e.removeMovie(a):Promise.reject()})}function ps(a){d.statisticsInterval=a;let e=x.current();if(e)return e.updateStatisticsInterval()}function us(a){Bi.default.disableLog(!a),o.toggle(a)}function ms(a,...e){!d.debugLog||o.send(a,"[external]",...e)}function hs(a){return c(this,null,function*(){let e=x.current();if(e)return e.videoEffect(a)})}function _s(a){return c(this,null,function*(){let e=x.current();e&&(yield e.setAudioStream(a))})}function gs(a=null,e,t=!1){return c(this,null,function*(){let i=x.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(a,e,t)})}function fs(a,e=!1){return c(this,null,function*(){let t=x.current();if(!t)throw new Error("Conversation not found");let i=yield ae.getOkIdsByExternalIds([a]);return t.promoteParticipant(S.composeUserId(i[0],Q.USER),e)})}function Ss(a){return c(this,null,function*(){yield ae.removeHistoryRecords(a)})}
11
+ `,r=>{var n;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(n=r.data)==null?void 0:n.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:d.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(_e.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),o.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var ja=16*1024,Ka=11,Gr=ja-Ka,$a=65536,Ri=0,pt=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;o.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,n)=>{if(!this._destroyed){if(!r){o.warn("requestFrame failed, keyFrame: "+this._needKeyframe,n),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{o.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};lt.isBrowserSupported()?this._encoder=new lt(e,i):this._encoder=new It(e,i),this._datachannel.onmessage=r=>{Hr(r.data)&&(o.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>o.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,n){let s=Vr(e,t,i,r,Ri,this._encoder.isVP9(),n);return Ri=(Ri+1)%$a,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return c(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let n=e.data.slice(t,t+Gr),s=e.data.byteLength<=t+n.byteLength,l=this._wrapHeader(e.timestamp,!t,s,e.type==="key",n);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(l)}catch(p){o.warn("Error send data to DataChannel",p),r();return}s||window.setTimeout(()=>this._sendChunk(e,t+Gr,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),o.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return lt.isBrowserSupported()||It.isBrowserSupported()}};var Z=class{static get sessionKey(){return Z._sessionKey}static set sessionKey(e){Z._sessionKey=e}static get sessionSecretKey(){return Z._sessionSecretKey}static set sessionSecretKey(e){Z._sessionSecretKey=e}static get accessToken(){return Z._accessToken}static set accessToken(e){Z._accessToken=e}static isEmpty(){return!Z._sessionKey||!Z._sessionSecretKey}};var g=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(g._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(g._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(g._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(Z.accessToken=e.apiAuth.accessToken,Z.sessionKey=e.apiAuth.sessionKey,Z.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(g._params,e)}static get(e){return g._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.5.3-beta.3"}static get debug(){return undefined}static get protocolVersion(){return g._params.joinFromMultipleDevices?6:5}static get platform(){return g._params.platform}static set platform(e){g._params.platform=e}static get clientType(){return g._params.clientType}static set clientType(e){g._params.clientType=e}static get device(){return g._params.device}static get apiKey(){return g._params.apiKey}static get apiEnv(){return g._params.apiEnv}static get apiEndpoint(){switch(g.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return g._params.apiEnv}}static get authToken(){return g._params.authToken}static set authToken(e){g._params.authToken=e}static get anonymToken(){return g._params.anonymToken}static set anonymToken(e){g._params.anonymToken=e}static get domain(){return g._params.domain}static get iceServers(){return g._params.iceServers}static set iceServers(e){g._params.iceServers=e}static get wssBase(){return g._params.wssBase}static set wssBase(e){g._params.wssBase=e}static get wssToken(){return g._params.wssToken}static set wssToken(e){g._params.wssToken=e}static get signalingReconnectDelay(){return g._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return g._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return g._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return g._params.waitConnectionDelay}static get waitResponseDelay(){return g._params.waitResponseDelay}static get waitMessageDelay(){return g._params.waitMessageDelay}static get waitAnotherTabDelay(){return g._params.waitAnotherTabDelay}static get debugLog(){return g._params.debugLog}static get forceRelayPolicy(){return g._params.forceRelayPolicy}static set forceRelayPolicy(e){g._params.forceRelayPolicy=e}static get videoMinWidth(){return g._params.videoMinWidth}static get videoMaxWidth(){return g._params.videoMaxWidth}static set videoMaxWidth(e){g._params.videoMaxWidth=e}static get videoMinHeight(){return g._params.videoMinHeight}static get videoMaxHeight(){return g._params.videoMaxHeight}static set videoMaxHeight(e){g._params.videoMaxHeight=e}static get videoAspectRatio(){return g._params.videoAspectRatio}static get videoFrameRate(){return g._params.videoFrameRate}static get videoFacingMode(){return g._params.videoFacingMode}static get screenFrameRate(){return g._params.screenFrameRate}static get videoEffects(){return g._params.videoEffects}static set videoEffects(e){g._params.videoEffects=e}static get videoEffectMaxWidth(){return g._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){g._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return g._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){g._params.videoEffectMaxHeight=e}static get voiceParams(){return g._params.voiceParams}static get specListenerParams(){return g._params.specListenerParams}static get iceRestartWaitTime(){return g._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return g._params.transportConnectionWaitTime}static get statisticsInterval(){return g._params.statisticsInterval}static set statisticsInterval(e){g._params.statisticsInterval=e}static get networkStatisticsInterval(){return g._params.networkStatisticsInterval}static get perfStatReportEnabled(){return g._params.perfStatReportEnabled}static get callStatReportEnabled(){return g._params.callStatReportEnabled}static get producerNotificationDataChannel(){return g._params.producerNotificationDataChannel&&dt.isBrowserSupported()}static get producerCommandDataChannel(){return g._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return g._params.consumerScreenDataChannel&&pt.isBrowserSupported()}static get producerScreenDataChannel(){return g._params.producerScreenDataChannel&&g.producerNotificationDataChannel}static get screenShareWebmBuilder(){return g._params.screenShareWebmBuilder}static get noiseSuppression(){return g._params.noiseSuppression}static set noiseSuppression(e){g._params.noiseSuppression=e}static get preferH264(){return g._params.preferH264}static get preferVP9(){return g._params.preferVP9}static get audioNack(){return g._params.audioNack}static get consumerScreenTrack(){return g._params.consumerScreenTrack&&g.consumerScreenDataChannel}static get producerScreenTrack(){return g._params.producerScreenTrack&&g.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=g._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return g._params.movieShare&&g.videoTracksCount>0}static get videoTracksCount(){return g.producerNotificationDataChannel?g._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return g._params.breakVideoPayloadTypes}static get filteredMessages(){return g._params.filteredMessages}static get serverAudioRed(){return g._params.serverAudioRed}static get p2pAudioRed(){return g._params.p2pAudioRed}static get batchParticipantsOnStart(){return g._params.batchParticipantsOnStart}static get participantStateMapped(){return g._params.participantStateMapped}static get filterObservers(){return g._params.filterObservers}static get muteMode(){return g._params.muteMode}},d=g;d._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,serverAudioRed:!1,p2pAudioRed:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,participantStateMapped:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1};var Y=(p=>(p.WAITING_HALL="WAITING_HALL",p.WAITING="WAITING",p.CONNECTING="CONNECTING",p.CONNECTED="CONNECTED",p.RECONNECT="RECONNECT",p.ERROR="ERROR",p.HANGUP="HANGUP",p.PERMISSIONS="PERMISSIONS",p))(Y||{});function K(a,...e){let t=d.get(a);t&&setTimeout(t,0,...e)}function Ie(a,e,...t){if(d.filterObservers){if(Array.isArray(e)){if(e=e.filter(i=>!i.observer),!e.length)return}else if(e.observer)return}K(a,e,...t)}function Le(a){return Object.assign({},a)}function ut(a){return a.slice()}var bi;(ne=>{function a(v,R){K("onLocalStream",v,Le(R))}ne.onLocalStream=a;function e(v,R){K("onScreenStream",v,Le(R))}ne.onScreenStream=e;function t(v,R){K("onLocalStreamUpdate",Le(v),R)}ne.onLocalStreamUpdate=t;function i(v){K("onLocalStatus",v)}ne.onLocalStatus=i;function r(v,R){Ie("onRemoteStream",v,R)}ne.onRemoteStream=r;function n(v,R,F){Ie("onRemoteLive",v,R,F)}ne.onRemoteLive=n;function s(v,R){Ie("onRemoteScreenStream",v,R)}ne.onRemoteScreenStream=s;function l(v,R,F,J){Ie("onConversation",v,Le(R),Le(F),J)}ne.onConversation=l;function p(v,R){Ie("onRemoteMediaSettings",v,Le(R))}ne.onRemoteMediaSettings=p;function h(v,R){Ie("onRemoteParticipantState",v,Le(R))}ne.onRemoteParticipantState=h;function b(v,R,F=null){Ie("onRemoteStatus",v,R,F)}ne.onRemoteStatus=b;function P(v,R,F=null){Ie("onParticipantStatus",v,R,F)}ne.onParticipantStatus=P;function $(){K("onPermissionsRequested")}ne.onPermissionsRequested=$;function W(v){K("onPermissionsError",v)}ne.onPermissionsError=W;function L(v){Ie("onRemoteRemoved",v)}ne.onRemoteRemoved=L;function me(v,R,F){K("onCallState",v,R,Le(F))}ne.onCallState=me;function Ae(v,R){K("onDeviceSwitched",v,R)}ne.onDeviceSwitched=Ae;function le(v,R,F,J=!1,ie=!1,ti=null,ga=null){K("onMuteStates",Le(v),ut(R),ut(F),J,ie,ti,ga)}ne.onMuteStates=le;function Ge(v,R){Ie("onRolesChanged",v,ut(R))}ne.onRolesChanged=Ge;function ce(v){K("onLocalRolesChanged",ut(v))}ne.onLocalRolesChanged=ce;function Re(v,R){Ie("onPinnedParticipant",v,R)}ne.onPinnedParticipant=Re;function j(v){K("onLocalPin",v)}ne.onLocalPin=j;function ht(v){K("onOptionsChanged",ut(v))}ne.onOptionsChanged=ht;function Vi(){K("onCallAccepted")}ne.onCallAccepted=Vi;function Fi(){K("onRateNeeded")}ne.onRateNeeded=Fi;function Hi(v){Ie("onSpeakerChanged",v)}ne.onSpeakerChanged=Hi;function Gi(v){K("onVolumesDetected",ut(v))}ne.onVolumesDetected=Gi;function ei(v,R){K("onLocalVolume",v,R)}ne.onLocalVolume=ei;function u(v,R){K("onJoinStatus",v,R)}ne.onJoinStatus=u;function I(v,R){K("onHangup",v,R)}ne.onHangup=I;function y(v){K("onMultipartyChatCreated",Le(v))}ne.onMultipartyChatCreated=y;function V(){K("onDeviceChange")}ne.onDeviceChange=V;function A(v){K("onFingerprintChange",v)}ne.onFingerprintChange=A;function D(){K("onTokenExpired")}ne.onTokenExpired=D;function T(v,R,F=!1){K("onChatMessage",v,R,F)}ne.onChatMessage=T;function q(v,R,F=!1){K("onCustomData",v,R,F)}ne.onCustomData=q;function X(v,R,F,J,ie,ti){K("onRecordStarted",v,R,F,J,ie,ti)}ne.onRecordStarted=X;function O(){K("onRecordStopped")}ne.onRecordStopped=O;function te(v){K("onLocalNetworkStatusChanged",v)}ne.onLocalNetworkStatusChanged=te;function Oe(v){K("onNetworkStatusChanged",v)}ne.onNetworkStatusChanged=Oe;function be(v,...R){K("onDebugMessage",v,...R)}ne.onDebugMessage=be;function re(v,R){let F=Object.assign({},v,{memory:R});K("onStatistics",F)}ne.onStatistics=re;function ke(){K("onAutoplayError")}ne.onAutoplayError=ke;function At(v,R,F){K("onChatRoomUpdated",v,R,F)}ne.onChatRoomUpdated=At})(bi||(bi={}));var E=bi;var Pi=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(Pi||{}),Mi;(ce=>{let a="📞",e=(Re,...j)=>{E.onDebugMessage(Re,...j)},t=!1,i=(Re,j)=>(...ht)=>{Re(...ht),Cr(j,ht)},r=console.debug.bind(console,a),n=console.log.bind(console,a),s=console.warn.bind(console,a),l=console.error.bind(console,a),p=e.bind(null,"DEBUG"),h=e.bind(null,"LOG"),b=e.bind(null,"WARN"),P=e.bind(null,"ERROR");ce.debug=p,ce.log=h,ce.warn=b,ce.error=P;function Ae(){return t}ce.enabled=Ae;function le(Re){t=Re,d.debugLog&&si(),Re?(ce.debug=d.debugLog?i(r,"DEBUG"):r,ce.log=d.debugLog?i(n,"LOG"):n,ce.warn=d.debugLog?i(s,"WARN"):s,ce.error=d.debugLog?i(l,"ERROR"):l):(ce.debug=d.debugLog?i(p,"DEBUG"):p,ce.log=d.debugLog?i(h,"LOG"):h,ce.warn=d.debugLog?i(b,"WARN"):b,ce.error=d.debugLog?i(P,"ERROR"):P)}ce.toggle=le;function Ge(Re,...j){switch(Re){case"DEBUG":ce.debug(...j);break;case"LOG":ce.log(...j);break;case"WARN":ce.warn(...j);break;case"ERROR":ce.error(...j);break}}ce.send=Ge})(Mi||(Mi={}));var o=Mi;var ze=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(ze||{}),pe;(l=>{function a(p){return p.length?typeof p[0]=="object"?p:p.map(h=>e(h)):[]}l.fromIds=a;function e(p,h="USER"){return{id:p,type:h}}l.fromId=e;function t(p){return{id:p.id,type:p.type==="ANONYM"?"ANONYM":"USER"}}l.fromSignaling=t;function i(p){return`{"id":"${p.id}","type":"${p.type}"}`}l.toString=i;function r(p,h="USER"){return i(e(p,h))}l.fromIdToString=r;function n(p){try{return JSON.parse(p)}catch(h){throw new Error(`Failed to parse ExternalId from string '${p}'`)}}l.fromString=n;function s(p,h){return p.id===h.id&&p.type===h.type}l.compare=s})(pe||(pe={}));var ue;(r=>{function a(n,s="USER",l=0){return{id:n,type:s,deviceIdx:l}}r.fromId=a;function e(n){return`{"id":"${n.id}","type":"${n.type}","deviceIdx":"${n.deviceIdx}"}`}r.toString=e;function t(n,s){return Object.assign({deviceIdx:s},pe.fromSignaling(n))}r.fromSignaling=t;function i(n){return n&&typeof n=="object"?n.deviceIdx:0}r.getDeviceIdx=i})(ue||(ue={}));var Se=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(Se||{}),Wr="s",jr="m";function Fe(a){return a.participantId+(a.mediaType?ot+Wr+a.mediaType:"")+(a.streamName?ot+jr+a.streamName:"")}function Ct(a){let e=a.split(ot),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i=null,r,n=0;for(let l of e)switch(l.charAt(0)){case Wr:i=qa(l.slice(1));break;case jr:r=l.slice(1);break;case xt:n=Number.parseInt(l.slice(1),10);break;default:throw new Error("Unexpected parameter type "+l.charAt(0)+" in stream description "+a)}return{participantId:S.compose(t,n),mediaType:i,streamName:r}}function qa(a){for(let e of Object.keys(Se))if(e===a)return Se[e];return null}function Di(a,e){return a===null||e===null?a===null&&e===null:!(a.maxDimension!==e.maxDimension||a.maxBitrateK!==e.maxBitrateK||a.maxFramerate!==e.maxFramerate||a.degradationPreference!==e.degradationPreference)}function Kt(a,e){return!(!Di(a.camera,e.camera)||!Di(a.screenSharing,e.screenSharing))}function Ai(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function Kr(a){try{return btoa(JSON.stringify(a))}catch(e){o.warn("WaitingParticipant: failed convert to string",a,e)}return null}function $r(a){try{return JSON.parse(atob(a))}catch(e){o.warn("WaitingParticipant: failed convert from string",a,e)}return null}var yt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,m.log(_.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,m.log(_.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(o.log("Failed to fix RV"),m.log(_.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),m.log(_.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,o.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===de.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var $t=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(d.muteMode||!((s=this._output)==null?void 0:s.audioTrack))return;let e=C.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{o.warn("Error on play audio"),E.onAutoplayError()},r=l=>{t.srcObject=new MediaStream([l]),t.load();let p=t.play();p?p.catch(i):i()},n=()=>{var p;o.debug("Recover audio playback");let l=(p=this._output)==null?void 0:p.audioTrack;l?r(l):o.warn("Broken audio track")};t.onpause=n,t.onstalled=n,t.onerror=n,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return c(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=C.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw m.log(_.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var Ja=90,Ya=3,qt=class extends z{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),E.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>Ja?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Ya)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var za=44100,Rt=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=C.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=za/this._fftBins.length,t=Math.ceil(d.voiceParams.minFreq/e),i=Math.floor(d.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((n,s)=>n+s,0)/e.length/255,r=this._lastSmoothedLevel*d.voiceParams.smoothing+i*(1-d.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var Jt=class extends z{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&E.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,d.voiceParams.interval)};this._interval=window.setTimeout(t,d.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,ve.SOURCE_CHANGED,r=>{r.kind===de.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new Rt("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var qr="videochat-epi",Qa=5e3,Xa=3e4,Qe=class extends z{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,N.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(qr)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return c(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&d.perfStatReportEnabled&&this._previousTimestamp+Qa<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),d.callStatReportEnabled&&this._previousCallStatReportTimestamp+Xa<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return c(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(qr,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,n)=>(n.kind==="video"?(n.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+n.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+n.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=n.framesDropped,r.nack_sent+=n.nackCount,r.pli_sent+=n.pliCount,r.fir_sent+=n.firCount):(n.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+n.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+n.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=n.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=n.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=n.removedSamplesForAcceleration,r.concealed_audio_samples+=n.concealedSamples,r.silent_concealed_audio_samples+=n.silentConcealedSamples,r.audio_concealment_events+=n.concealmentEvents),r),t),e.outbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.nack_received+=n.nackCount,r.pli_received+=n.pliCount,r.fir_received+=n.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,n=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,l=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,p=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,h=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=n/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=l/r*1e3,i.concealed_silent_audio_samples=p/r*1e3,i.concealment_audio_avg_size=l/h,i.total_audio_energy=t.total_audio_energy}m.logCustom("callStat",i),o.log("Sent call stats",i),this._previousCallStatReport=t}};var Za=1e3;function oe(a,e,t=0){return e in a&&a[e]?a[e]:t}function Jr(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function He(a,e){return t=>t[a]===e}function en(a){return(e,t)=>e[a]-t[a]}function Yt(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function tn(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function rn(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Oi(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=rn(t[1])?Oi(t[1]):t[1],e),{})}function an(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function nn(a){return c(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...a.getReceivers().map(t=>t.getStats())),e.push(...a.getSenders().map(t=>t.getStats()))):e.push(a.getStats()),Promise.all(e).then(an).then(tn)})}function sn(a){let e=a.filter(He("type","candidate-pair")).sort(en("priority")).find(Jr(He("nominated",!0),He("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=a.find(He("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=a.find(He("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),Oi(t)}function on(a,e){let t=Yt("id",a),i=a.filter(Jr(He("type","inbound-rtp"),He("type","outbound-rtp")));C.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,s)=>{if(!n[s.ssrc])n[s.ssrc]=s;else{let l=Object.assign({},n[s.ssrc],s),p=n[s.ssrc].isRemote?s:n[s.ssrc];l.id=p.id,l.type=p.type,delete l.isRemote,delete l.remoteId,n[l.ssrc]=l}return n},{})));let r={};if(C.browserName()==="Safari"){let n=a.filter(He("type","track"));r=Yt("trackIdentifier",n)}return i.map(n=>{let s=Number(n.ssrc),l=n.mediaType||n.kind,p=n.trackId,h=n.type,b=n.codecId;if(C.browserName()==="Safari"){let $=/^.+_([\d]+)$/.exec(n.id);if($&&(s=parseInt($[1],10)),l=n.id.indexOf("Audio")>0?"audio":"video",e[s]){let W=l+"-"+e[s];r[W]&&(p=r[W].id)}}if(!h||!s||!l)return null;let P={ssrc:s,type:h,kind:l,bytesReceived:oe(n,"bytesReceived"),bytesSent:oe(n,"bytesSent"),jitter:oe(n,"jitter"),packetsLost:oe(n,"packetsLost"),packetsReceived:oe(n,"packetsReceived"),packetsSent:oe(n,"packetsSent"),fractionLost:oe(n,"fractionLost"),pliCount:oe(n,"pliCount"),firCount:oe(n,"firCount"),nackCount:oe(n,"nackCount"),userId:e[s]};if(l==="video"){let $=oe(n,"framesDecoded"),W=oe(n,"totalInterFrameDelay"),L=oe(n,"totalSquaredInterFrameDelay");P.interframeDelayVariance=(L-W*W/$)/$}if(l==="audio"&&(P.totalSamplesReceived=oe(n,"totalSamplesReceived"),P.concealedSamples=oe(n,"concealedSamples"),P.insertedSamplesForDeceleration=oe(n,"insertedSamplesForDeceleration"),P.removedSamplesForAcceleration=oe(n,"removedSamplesForAcceleration"),P.silentConcealedSamples=oe(n,"silentConcealedSamples"),P.concealmentEvents=oe(n,"concealmentEvents"),P.totalAudioEnergy=oe(n,"totalAudioEnergy")),b&&t[b]){let $=t[b];P.clockRate=$.clockRate,P.mimeType=$.mimeType}if(p&&t[p]){let $=t[p];P.frameHeight=$.frameHeight,P.frameWidth=$.frameWidth,P.framesDecoded=$.framesDecoded,P.framesReceived=$.framesReceived,P.framesDropped=$.framesDropped}return Oi(P)}).filter(n=>!!n)}function cn(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=Yt("ssrc",a.rtps),i=Yt("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let s=t[n],l=i[n];if(!(!s||!l)){if(s.bytesReceived&&s.bytesReceived>l.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-l.bytesReceived)/r)),s.bytesSent&&s.bytesSent>l.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-l.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>l.packetsReceived||s.packetsLost>l.packetsLost){let p=s.packetsLost-l.packetsLost,h=s.packetsReceived-l.packetsReceived;s.packetLoss=parseFloat((100*p/(p+h)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&l.framesDropped&&s.framesDropped>l.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-l.framesDropped)/r).toFixed(0)))}}),a}function bt(i,r){return c(this,arguments,function*(a,e,t={}){let n=yield nn(a),s={timestamp:Date.now(),transport:sn(n),rtps:on(n,t)};return e?cn(s,e):(yield S.delay(Za),bt(a,s,t))})}var zt=.8,Xe=class extends z{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=U.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=n,this._perfStatReporter=new Qe(this,i,!0),this.subscribe(this._signaling,he.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ve.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ve.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:d.iceServers,iceTransportPolicy:d.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(s){m.log(_.ERROR,"addTrack-direct"),o.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===U.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==U.IDLE&&e!==U.CLOSED&&e!==U.FAILED&&this._startStatInterval()}open(e=null){return c(this,null,function*(){if(this._isOpen){o.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(o.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0),this._applySettings()}catch(i){m.log(_.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(U.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(N.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Kt(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(o.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(U.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(U.CLOSED)),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case k.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case k.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case k.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((n=e.data.sdk)==null?void 0:n.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=S.getPeerIdString(e.peerId);S.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){o.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw m.log(_.ERROR,"addIceCandidate-direct"),o.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else o.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return c(this,null,function*(){if(!this._remoteCandidates[e]){o.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){o.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw m.log(_.ERROR,"setRemoteDescription-direct"),o.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){o.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(N.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return c(this,null,function*(){e.candidate&&this._signaling.ready&&(o.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(o.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>c(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(o.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===U.IDLE||e===U.OPENED?this._setState(U.CONNECTING):this._setState(U.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),m.log(_.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(U.CONNECTED),this._stopReconnection(),S.getPeerConnectionHostInfo(this._pc).then(e=>{e&&m.log(_.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(U.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(o.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},d.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(o.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(Te.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(m.log(_.ICE_RESTART),o.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):o.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,o.error("Ice restart failed",{participantId:this._participantId}),m.log(_.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},d.iceRestartWaitTime)}_createOffer(e){return c(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return o.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw o.error("Unable to create offer",i,{participantId:this._participantId}),m.log(_.ERROR,"createOffer-direct"),i}).then(i=>c(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=Xe._patchDescription(i),o.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw o.error("Unable to set local description",i,{participantId:this._participantId}),m.log(_.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return c(this,null,function*(){return o.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw o.error("Unable to create answer",e,{participantId:this._participantId}),m.log(_.ERROR,"createAnswer-direct"),e}).then(e=>c(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=Xe._patchDescription(e),o.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw o.error("Unable to set local description",e,{participantId:this._participantId}),m.log(_.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!C.baseChromeVersion();return e.sdp=S.patchSDP(e.sdp,d.preferH264&&C.canPreferH264(),C.isBrokenH264(),d.preferVP9,t&&d.audioNack,d.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{o.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),m.log(_.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}bt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:Te.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:Te.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(N.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,d.statisticsInterval)})};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=le=>le.rtt<=this._networkLimits.goodNet.rtt&&le.loss<=this._networkLimits.goodNet.loss,i=le=>le.rtt>=this._networkLimits.badNet.rtt||le.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((le,Ge)=>Math.max(le,Ge.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-zt)+r*zt,loss:this._lastNetworkStat.loss*(1-zt)+n*zt},l=i(s),p=t(s),h=i(this._remoteNetworkStat),b=t(this._remoteNetworkStat),P=i(this._lastNetworkStat),$=t(this._lastNetworkStat),me=l||h?.2:p&&b?1:0,Ae=Date.now();if((P!==l||$!==p||Ae-this._lastNetworkStat.date>d.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(le=>{o.warn("Unable to send [bad-net]",le)})),me){let le={};le[this._participantId]=le[""]=me,this._triggerEvent(N.NETWORK_STATUS,le)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=S.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(E.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=S.applySettings(this._pc,e,this._prevConsumerSettings))}};var Yr=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Yr||{}),Pt=Yr;var Ze=We(require("messagepack"));var ki=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var n,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let l=(0,Ze.decode)(r);return Object.entries(l).forEach(([L,me])=>{let Ae=Ct(L);this.streamDescriptionByCompactId.set(me,Ae)}),null;case 2:case 4:let p=(0,Ze.decode)(r),h=[];for(let L of p){let me=this.getStreamDescription(L);me&&h.push(me.participantId)}return i===2?{type:"notification",notification:k.AUDIO_ACTIVITY,activeParticipants:h}:{type:"notification",notification:k.STALLED_ACTIVITY,stalledParticipants:h};case 3:let b=(0,Ze.decode)(r);return{type:"notification",notification:k.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(b))==null?void 0:n.participantId};case 5:let P=(0,Ze.decode)(r);return{type:"notification",notification:k.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:P[0],maxDimension:P[1]}};case 6:let $=(0,Ze.decode)(r),W={};for(let[L,me]of Object.entries($)){let Ae=(s=this.getStreamDescription(Number(L)))==null?void 0:s.participantId;Ae&&(W[Ae]=me/100)}return{type:"notification",notification:k.NETWORK_STATUS,statuses:W};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return o.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,Ze.decode)(e),i=[];for(let[r,n]of Object.entries(t)){let s=n[0],l=n[1],p=n[2],h;if(s!==null){if(h=this.getStreamDescription(s),!h){o.error(`could not uncompress participant ID ${s}`);continue}}else h=null;if(p===null){o.error("unexpected null sequenceNumber",r,n);continue}let b=Pe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,P=l?l>>>0:null;i.push({participantStreamDescription:h,streamId:b,rtpTimestamp:P,sequenceNumber:p})}return{type:"notification",notification:k.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var dn=90,ln=4294967295,Ce=class extends z{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=U.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,he.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ve.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ve.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,ve.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Qe(this,e),this._serverSettings=i,o.debug("ServerTransport: Created")}getState(){return this._state||U.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==U.IDLE&&e!==U.CLOSED&&e!==U.FAILED&&this._startStatInterval()}open(e=!1){if(this._isOpen){o.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(o.error("ServerTransport: Closed",e),this._setState(U.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(U.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Kt(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,Ce._closeDataChannel(this._producerNotification),Ce._closeDataChannel(this._producerCommand),Ce._closeDataChannel(this._producerScreen),Ce._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){o.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let n=r.readyState;n==="open"?(o.debug(`[${t}] data channel opened`),r.onerror=s=>{o.error(`[${t}] data channel error`,s)},i(r)):o.error(`[${t}] data channel open failed, state [${n}]`)}}_openConnection(e=!1){o.debug("ServerTransport: Open single connection");let t={};C.baseChromeVersion()&&(t.sdpSemantics=Ce._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=S.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Ce._onSignalingStateChange.bind(this,this._pc),d.producerNotificationDataChannel&&this._createDataChannel(this._pc,Pt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new ki,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),d.producerCommandDataChannel&&this._createDataChannel(this._pc,Pt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),d.producerScreenDataChannel&&this._createDataChannel(this._pc,Pt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){o.error("ServerTransport: Unable to add media source tracks",i),m.log(_.ERROR,"addTrack-single"),this.close(i);return}d.consumerScreenDataChannel&&this._createDataChannel(this._pc,Pt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(U.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==U.OPENED&&(this._setState(U.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(N.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(N.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(N.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(N.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
+ `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Pe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!d.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new pt(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!d.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new dt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!d.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==de.video)return;let r=!this._disabledSenders.has(i),n=e.maxDimension!==0;if(r&&!n){o.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(C.getBlackMediaTrack()).catch(l=>{o.error("Could not disable video upload",l)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&n&&s){o.log("Enabling video upload"),this._disabledSenders.delete(i);let l=i.track;l.enabled=s.enabled,i.replaceTrack(s).then(()=>l.stop()).catch(p=>{o.error("Could not enable video upload",p)})}S.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,d.statisticsInterval)};this._statInterval=window.setTimeout(e,d.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return c(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield bt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(N.REMOTE_DATA_STATS,{inbound:{topology:Te.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:Te.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=Pe.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(N.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Qe.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:d.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:d.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:d.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:d.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:Ce._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:d.videoTracksCount,red:d.serverAudioRed};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return c(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,o.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(o.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw o.error("[single] unable to set remote offer",i),m.log(_.ERROR,"setRemoteDescription-single"),i}).then(()=>c(this,null,function*(){if(o.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw o.error("[single] unable to create answer",i),m.log(_.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=S.patchSDP(i.sdp,!1,C.isBrokenH264(),!1),i)).then(i=>c(this,null,function*(){if(o.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw o.error("[single] unable to set local answer",i),m.log(_.ERROR,"setLocalDescription-single"),i}).then(i=>c(this,null,function*(){o.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),o.debug("[single] remote offer has been processed")})).catch(i=>{o.warn("[single] unable to send local answer",i),m.log(_.ERROR,"acceptProducer")}).then(()=>c(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){o.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return c(this,null,function*(){if(!!this._isOpen)switch(e.notification){case k.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case k.REALLOC_CON:this._reconnect();break;case k.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case k.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case k.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case k.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return c(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),d.breakVideoPayloadTypes&&(o.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){o.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,i.id,i,n.track)}),i.getTracks().find(n=>n.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(N.REMOTE_TRACK_ADDED,i.id,i,t.track)):o.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){o.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(o.debug("[single] connection state changed",{state:e.connectionState},t),m.log(_.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===U.IDLE||i===U.OPENED?this._setState(U.CONNECTING):e.iceConnectionState==="checking"&&this._setState(U.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(U.RECONNECTING);break;case"connected":this._setState(U.CONNECTED),S.getPeerConnectionHostInfo(e).then(r=>{r&&m.log(_.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(d.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{o.error("ServerTransport: Unable to replace track",r),m.log(_.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=C.baseChromeVersion();return e?d.isUnifiedPlanSupported("Chrome",e):d.isUnifiedPlanSupported(C.browserName(),Number(C.browserVersion()))}getStreamWaitingTimeMs(e,t){if(!this._pc)return m.log(_.PAT_WAITING_TIME_ERROR,"noConnection"),o.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return m.log(_.PAT_WAITING_TIME_ERROR,"noReceiver"),o.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return o.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return m.log(_.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),o.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let l=t-s&ln,p=Math.ceil(l/dn);return Math.min(100,Math.max(0,p))}};var N=(L=>(L.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",L.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",L.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",L.REMOTE_ALL_STALL="REMOTE_ALL_STALL",L.REMOTE_DATA_STATS="REMOTE_DATA_STATS",L.STATE_CHANGED="STATE_CHANGED",L.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",L.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",L.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",L.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",L.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",L.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",L.NETWORK_STATUS="NETWORK_STATUS",L.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",L))(N||{}),U=(l=>(l.IDLE="IDLE",l.OPENED="OPENED",l.CONNECTING="CONNECTING",l.RECONNECTING="RECONNECTING",l.CONNECTED="CONNECTED",l.CLOSED="CLOSED",l.FAILED="FAILED",l))(U||{}),Te=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(Te||{}),wi=class extends z{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,he.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){o.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,i=!1){let r=!1;for(let n of e){if(this._opened.indexOf(n)!==-1){o.warn(`The participant [${n}] has already had opened transport`);continue}if(this._allocated.indexOf(n)===-1){o.warn(`The participant [${n}] has no allocated transport`);continue}this._opened.push(n),r=!0}!r||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),o.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&o.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===k.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===k.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(o.log(`Topology changed ${this._topology} -> ${e.topology}`),m.log(_.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],n=e.offerToDeviceIdxs||[],s=i.length&&r.length?S.composeParticipantId(i[0],r[0],n[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){o.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&o.warn("Topology changed to DIRECT, but the allocated participants count more then one");let l=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let p=s===l;this._directTransport=this._createDirectTransport(l,p)}this._opened.indexOf(l)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new Xe(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._dtListeners&&this._dtListeners.length>0&&o.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new Ce(this._signaling,this._mediaSource,this._serverSettings);return this._stListeners&&this._stListeners.length>0&&o.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("ACTIVE_PARTICIPANTS_NO_SIGNAL",this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;d.noiseSuppression!==e&&(d.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent("ACTIVE_PARTICIPANTS_NO_SIGNAL")}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(m.log(_.PAT_WAITING_TIME_ERROR,"wrongTopology"),o.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(m.log(_.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var et=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(et||{}),xi=class extends z{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===de.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Rt(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,d.voiceParams.interval)};this._interval=window.setTimeout(n,d.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===de.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===Pe.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var Ni=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(Ni||{}),Li=class extends z{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,et.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,N.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>d.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*d.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent("SPEAKER_CHANGED",e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var Qt=class extends z{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,et.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===U.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),d.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),d.specListenerParams.volumeTimeout))),t===U.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==U.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var pn=1e3,un=1e4;var mn=15,B=class extends z{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=G.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;m.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),m.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new $t,d.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),pn))}static current(){return B._current}static hangupAfterInit(){B._activationMutex&&!B._current&&(B._delayedHangup=!0)}static id(){var e,t;return((t=(e=B._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,s=!1){return c(this,null,function*(){if(B._activationMutex)throw m.log(_.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new w(M.FAILED);B._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let l=this._mediaSource.getMediaSettings();t===we.CHAT||e.length>1?this._logWithMediaSettings(_.OUTGOING_MULTIPARTY_CALL,l):this._logWithMediaSettings(_.OUTGOING_CALL,l);let p=yield this._startConversation(e,t,Ue.OUTGOING,i,r,n,s);if(!this._conversation)throw new w(M.UNKNOWN_ERROR);if(this._participantState=G.ACCEPTED,this._signaling.changeMediaSettings(l),yield this._registerParticipants(p.conversation.participants),this._processConnectionData(p),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new w(M.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let h=Object.values(this._participants),b;return d.batchParticipantsOnStart&&(b=S.mapSharedParticipants(h)),E.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,b),E.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),B._current=this,this._conversation.concurrent?yield this._acceptConcurrent():d.batchParticipantsOnStart||this._setParticipantsStatus(h,Y.WAITING),this._conversation}catch(l){throw this._close(l,"Unable to start conversation"),l}finally{B._activationMutex=!1}})}onJoin(e){return c(this,null,function*(){var t;if(B._activationMutex)throw m.log(_.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new w(M.FAILED);B._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.JOIN_CONVERSATION,r);let n=yield this._joinConversation(e);if(!this._conversation)throw new w(M.UNKNOWN_ERROR);return this._conversation.observer=i,E.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(o.log("In waiting hall"),B._current=this,B._activationMutex=!1,this._signaling.readyToSend(),E.onLocalStatus(Y.WAITING_HALL),this._conversation):this._onJoinPart2(n)}catch(i){throw B._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return c(this,null,function*(){o.debug("Join conversation part 2"),B._activationMutex=!0;try{if(this._participantState=G.ACCEPTED,!this._conversation||!this._mediaSource)throw new w(M.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new w(M.CANCELED);let t=Object.values(this._participants),i;return d.batchParticipantsOnStart&&(i=S.mapSharedParticipants(t)),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),E.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),B._current=this,d.batchParticipantsOnStart||this._setParticipantsStatus(t,Y.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{B._activationMutex=!1}})}onPush(r){return c(this,arguments,function*(e,t=Q.USER,i){if(B._activationMutex)throw o.warn("Conversation: there is already running activation"),new w(M.REJECTED);B._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new w(M.UNKNOWN_ERROR);if(!n.conversation.participants.find(l=>{var p;return l.state===G.CALLED&&l.id===((p=this._conversation)==null?void 0:p.userId)}))throw o.log("Push rejected (there is an active call)"),m.log(_.PUSH,"rejected"),new w(M.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),m.log(_.PUSH,"accepted"),B._current=this,B._delayedHangup)throw new w(M.CANCELED);B._activationMutex=!1}catch(n){throw B._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(kt.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>S.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return c(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new w(M.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),E.onCallAccepted(),this._state="ACTIVE",this._participantState=G.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return c(this,null,function*(){if(this._state!=="IDLE")throw m.log(_.ERROR,"acceptIncoming"),o.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new w(M.UNKNOWN_ERROR);this._state="PROCESSING",o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=G.ACCEPTED;let i=Object.values(this._participants),r;d.batchParticipantsOnStart&&(r=S.mapSharedParticipants(i)),E.onCallAccepted(),E.onLocalStream(this._mediaSource.getStream(),t),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),E.onLocalStatus(Y.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(Be.MUTE)||n.includes(Be.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),d.batchParticipantsOnStart||this._setParticipantsStatus(i,Y.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return c(this,null,function*(){var e;if(this._state!=="IDLE")throw m.log(_.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",o.debug("Decline incoming call"),this._logWithMediaSettings(_.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=G.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(M.REJECTED)),this._close(new w(M.REJECTED))})}hangup(){return c(this,null,function*(){o.debug("Hangup");let e=this._state==="ACTIVE"?M.HUNGUP:M.CANCELED;m.log(_.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new w(e))):E.onHangup(new w(M.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return c(this,null,function*(){if(!this._signaling.ready){this._close(new w(M.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=M.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(S.composeId(n),n,r)})}removeParticipant(e,t=!1){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let n of e)(n.state===G.CALLED||n.state===G.ACCEPTED)&&(this._transport.isAllocated(n.id)||this._transport.allocate(n.id,t)),n.state===G.ACCEPTED&&i.push(n.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&o.error(t,e),o.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(M.FAILED):m.log(_.ERROR,e.hangup),B._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([M.CANCELED,M.NOT_FRIENDS,M.CALLEE_IS_OFFLINE,M.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===M.REJECTED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===M.HUNGUP&&(!e.remote||this._participantState===G.CALLED)){E.onHangup(e,i),this.destroy();return}if(e.hangup===M.MISSED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===M.SOCKET_CLOSED&&B._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===M.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=G.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),m.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,E.onHangup(e||new w(M.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;o.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),m.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return c(this,null,function*(){let t=yield this._api.getConversationParams(e);o.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let s=r.urls.filter((l,p,h)=>h.indexOf(l)===p);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return d.iceServers=i,d.wssBase=t.endpoint,d.wssToken=t.token,t.client_type&&(d.clientType=t.client_type),t})}_startConversation(e,t,i,r,n="",s=!1,l=!1){return c(this,null,function*(){let p=S.uuid();o.debug("Conversation: start",{conversationId:p,opponentIds:e,opponentType:t,direction:i});let h=r.includes(se.VIDEO),b=yield this._api.startConversation(p,e,t,h,n,s,l);o.debug("Api.startConversation",b),yield this._getConversationParams(b.id);let P=yield this._connectSignaling(xe.START,b);return yield this._setConversation(b,P,i),P})}_joinConversation(e){return c(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n,observedIds:s}=e;o.debug("Conversation: join",{conversationId:t,joinLink:n,observedIds:s});let l=i.includes(se.VIDEO),p;if(t)p=yield this._api.joinConversation(t,l,r);else if(n)p=yield this._api.joinConversationByLink(n,l,s);else throw new w(M.UNKNOWN_ERROR);o.debug("Api.joinConversation",p),yield this._getConversationParams(p.id);let h=yield this._connectSignaling(xe.JOIN,p);return yield this._setConversation(p,h,Ue.JOINING),h})}_prepareConversation(r){return c(this,arguments,function*(e,t=Q.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let n=this._api.getUserId();if(!n)throw new w(M.UNKNOWN_ERROR);let l=(yield this._getConversationParams(e)).device_idx||0,p={id:e,peerId:i,endpoint:`${d.wssBase}?userId=${n}&entityType=${t}&deviceIdx=${l}&conversationId=${e}&token=${d.wssToken}`,is_concurrent:!1,p2p_forbidden:!1,device_idx:l},h=yield this._connectSignaling(xe.ACCEPT,p);return B._current&&(B._current._participantState===G.ACCEPTED||B._current._participantState===G.CALLED)?(o.log("Push rejected (busy)"),m.log(_.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(M.BUSY),Promise.reject({hangup:M.BUSY})):(B._current&&(B._current.destroy(),B._current=null),yield this._setConversation(p,h,Ue.INCOMING,t),h)})}_createParticipant(e){return c(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:ge(),participantState:{},state:G.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[]},e);if(e.externalId){let r=S.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(r,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return((i=t.observedIds)==null?void 0:i.length)&&(t.externalId.observer=!0),t})}_getParticipantId(e){return c(this,null,function*(){try{let t=S.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new w(M.NETWORK_ERROR),t),t}})}_setConversation(n,s,l){return c(this,arguments,function*(e,t,i,r=Q.USER){let p=t.conversation.participants.map(W=>W.id);yield this._api.prepareUserIds(p);let h=this._api.getUserId(),b=e.device_idx||0;if(!h){let W=(t.conversation.participants||[]).find(L=>S.comparePeerId(L.peerId,t.peerId));if(!W)throw new w(M.UNKNOWN_ERROR);h=Number(W.id),W.idType&&(r=W.idType),W.deviceIdx&&(b=W.deviceIdx),this._api.setUserId(h)}let P=S.composeParticipantId(h,r,b),$=yield this._getParticipantId(P);this._conversation={userId:h,compositeUserId:P,externalId:$,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||Te.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(d.forceRelayPolicy=e.p2p_forbidden),m.log(_.RELAY_POLICY,d.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new w(M.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||Te.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new ui;return this.subscribe(e,ve.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,ve.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new yt(e),e}_connectSignaling(e,t){return c(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,he.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,he.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,he.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return c(this,null,function*(){if(!!this._conversation)for(let t of e){let i=S.composeId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),E.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===G.HUNGUP||t.state===G.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],M.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&ue.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:ge(t.mediaSettings),participantState:S.mapParticipantState(t),state:t.state,roles:t.roles||[],status:d.batchParticipantsOnStart?Y.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),E.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){S.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Ot.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new wi(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new qt,this.subscribe(this._transport,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,N.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,N.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,N.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,N.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,N.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,N.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,N.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,N.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Ue.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===G.ACCEPTED||t.state===G.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new xi(this._transport),this.subscribe(this._volumesDetector,et.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Li(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,Ni.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Jt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Qt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=C.getCameras().length,t=C.getMicrophones().length;o.debug("Cameras: "+e+(C.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(C.hasMicrophonePermission()?"✔":"✖")),m.log(_.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){m.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===G.CALLED||e.state===G.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===M.HUNGUP?this._setParticipantsStatus([e],Y.HANGUP):this._setParticipantsStatus([e],Y.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Se.CAMERA,stopStream:!0}]),delete this._participants[e.id],E.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){o.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return c(this,null,function*(){o.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===G.ACCEPTED||r.state===G.CALLED)){o.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&ue.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:ge(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}),r=this._participants[e]),this._setParticipantsStatus([r],Y.WAITING),i?(r.state=G.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=G.CALLED,this._transport.allocate(r.id,!0),m.log(_.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){o.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=mn;i++){let r=S.compose(e,i),n=this._participants[r];n&&t.push(n)}if(!t.length){o.warn(`Participant [${e}] isn't in conversation`);return}if(this._transport)for(let i of t)this._transport.close(i.id);m.log(_.REMOVE_PARTICIPANT)}changeDevice(e){return c(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new yt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ee.UNKNOWN)})}toggleScreenCapturing(e){return c(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ee.UNKNOWN)})}setVideoStream(e,t=!1){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return c(this,null,function*(){if(this._mediaSource)return m.log(_.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return c(this,null,function*(){if(this._mediaSource)return m.log(_.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return c(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let n=typeof r.uid=="object"?r.uid:ue.fromId(r.uid),s=ue.toString(n);i[s]=r.priority}for(let r of Object.values(this._participants)){let n=ue.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return c(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return c(this,null,function*(){let t={};return t[Fe(e)]="kf",this._signaling.updateDisplayLayout(t)})}updateDisplayLayout(e){return c(this,null,function*(){if(e.length<1||!this._signaling.ready)return;o.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:ue.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(n);if(!s){let b=ue.toString(n);o.log(`Unknown participant external ID ${b}`);continue}let l=S.compose(s,n.deviceIdx),p=Fe({participantId:l,mediaType:r.mediaType,streamName:r.streamName}),h=this._participants[l];h&&(h.lastRequestedLayouts[p]=r),B._isStopStreaming(r)?this._streamIdByStreamDescription.has(p)&&!this._cooldownTimestampByStreamDescription.has(p)&&this._cooldownTimestampByStreamDescription.set(p,Date.now()):(this._cooldownTimestampByStreamDescription.delete(p),!this._streamIdByStreamDescription.has(p)&&d.videoTracksCount>0&&this._streamIdByStreamDescription.set(p,null),t[p]=B._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>d.videoTracksCount;){let r=i.next();if(r.done){o.error("Cannot accommodate all streaming requests: tracks available "+d.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]=B._layoutToString({stopStream:!0})}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(o.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Ct(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Se.STREAM||i.mediaType===Se.SCREEN)?E.onRemoteLive(r.externalId,i.streamName,null):E.onRemoteStream(r.externalId,null),m.log(_.PAT_DEALLOCATED)):o.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return c(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,n]of Object.entries(t.errorCodeByParticipantId||{})){let s=Ct(r),l=this._participants[s.participantId];if(l){let p;typeof n!="number"?(o.warn(`Unexpected error code ${n} received for participant ${s.participantId}`),p=hr.UNKNOWN_ERROR):p=_r(n),i.push({externalId:l.externalId,errorReason:p})}}if(i&&i.length)throw new Xt("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+un>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=B._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(B._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),t}_onParticipantSourcesUpdate(e){if(this._conversation){o.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return c(this,null,function*(){o.log("Promoted in waiting hall",!e.demote),e.demote?(o.log("Kicked from waiting hall"),this._close(new w(M.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return c(this,arguments,function*(e,t=0,i=[]){o.log(`Chat room updated: ${e}`);let n=[],s=[];i.length&&(i.forEach(l=>{if(l.externalId){let p=pe.fromSignaling(l.externalId);n.push(p),this._api.cacheExternalId(l.id.id,p)}else s.push(S.decomposeId(l.id.id).id)}),s.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(s))),E.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var l,p;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||d.producerScreenTrack&&t.mediaType===Se.SCREEN)return;let i=Fe(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){o.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),m.log(_.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let h=t.participantId,b=this._participants[h];if(!b){m.log(_.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${h}`);return}let P=this._streamByStreamId.get(n);if(!P){m.log(_.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}m.log(_.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let $=(l=e.participantStreamDescription)==null?void 0:l.mediaType;if($===Se.STREAM||$===Se.MOVIE)((p=e.participantStreamDescription)==null?void 0:p.streamName)&&E.onRemoteLive(b.externalId,e.participantStreamDescription.streamName,P);else{let W=(d.producerScreenTrack?null:b.secondStream)||P;E.onRemoteStream(b.externalId,W)}}else{o.debug(`Waiting for ${s} until stream ${n} for ${i} is switched`);let h=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,h)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Fe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Fe(i)))return i}else{let i={participantId:t,mediaType:Se.CAMERA};if(this._streamIdByStreamDescription.has(Fe(i)))return i;let r={participantId:t,mediaType:Se.SCREEN};if(this._streamIdByStreamDescription.has(Fe(r)))return r}return o.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?S.includesOneOf(this._conversation.roles,[je.ADMIN,je.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!S.includesOneOf(this._conversation.roles,[je.ADMIN,je.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return c(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return c(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return c(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=ir(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return c(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=$r(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let s=n.participants||[],l=[],p=[],h=null;return s.length&&(s.forEach(b=>{if(b.externalId){let P=pe.fromSignaling(b.externalId);l.push(P),this._api.cacheExternalId(b.id.id,P)}else p.push(S.decomposeId(b.id.id).id)}),p.length&&!l.length&&(l=yield this._api.getExternalIdsByOkIds(p)),n.hasMore&&(h=Kr(s[s.length-1].id))),{participants:l,pageMarker:h,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return c(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return c(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return c(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return c(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return c(this,null,function*(){var l;let n={movieId:e,participantId:(l=this._conversation)==null?void 0:l.compositeUserId};(t||t===0)&&(n.gain=t),i&&(n.offset=i),typeof r!==void 0&&(n.pause=r);let s=yield this._signaling.updateMovie(n);if(s.error)throw new Error(s.error)})}removeMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",n=null){return c(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},l=yield this._signaling.startStream(s);return l.error?Promise.reject(l.message):l})}stopStream(){return c(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return c(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return c(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return c(this,null,function*(){var r;if(e<d.videoMinWidth||t<d.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<d.videoMinWidth||i.effect.height<d.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");d.videoEffectMaxHeight=i.effect.height,d.videoEffectMaxWidth=i.effect.width}return d.videoMaxWidth=e,d.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return c(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return c(this,null,function*(){var t,i;!this._conversation||(o.debug("Local media stream changed",e.mediaSettings),E.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return c(this,null,function*(){var t,i;if(o.log("Screen sharing changed",e.track,e.mediaSettings),d.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;E.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){o.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&E.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){o.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&(d.participantStateMapped?E.onRemoteParticipantState(i.externalId,i.participantState):E.onRemoteParticipantState(i.externalId,S.mapLegacyParticipantState(i.participantState))))}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(o.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),E.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case k.ACCEPTED_CALL:return this._onAcceptedCall(e);case k.HUNGUP:return this._onHungup(e);case k.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case k.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case k.CLOSED_CONVERSATION:return this._onClosedConversation(e);case k.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case k.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case k.RATE_CALL_DATA:return this._onNeedRate();case k.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case k.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case k.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case k.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case k.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case k.REGISTERED_PEER:return this._onPeerRegistered(e);case k.SWITCH_MICRO:return this._onMicSwitched(e);case k.CHAT_MESSAGE:return this._onChatMessage(e);case k.CUSTOM_DATA:return this._onCustomData(e);case k.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case k.RECORD_STOPPED:return this._onRecordInfo(null);case k.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case k.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case k.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case k.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case k.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case k.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case k.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return c(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let s=S.composeId(n),l=n.roles||[];if(s===this._conversation.compositeUserId){t=ge(n.mediaSettings),gt(this._conversation.roles,l)||this._onRolesChanged(s,l);continue}r.push(s);let p=this._participants[s];if(!p)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let h=ge(n.mediaSettings);yr(h,p.mediaSettings)||this._changeRemoteMediaSettings(s,h);let b=S.mapParticipantState(n),P=p.participantState;S.isEqualParticipantState(b,P)||this._changeRemoteParticipantState(s,b),gt(l,p.roles)||this._onRolesChanged(p.id,l)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],M.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){o.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return c(this,null,function*(){let t=S.composeMessageId(e),i=S.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new w(M.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:ge(e.mediaSettings)}),r=this._participants[t]),r.state=G.ACCEPTED,r.mediaSettings=ge(e.mediaSettings),this._logWithMediaSettings(_.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Ue.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){o.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=S.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new w(e.reason,{remote:!0}));return}let i=this._participants[t];if(!i){o.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===M.REJECTED?G.REJECTED:G.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,M.HUNGUP)}_onAddedParticipant(e){return c(this,null,function*(){var r,n;o.debug(`Participant added [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state!==G.HUNGUP&&i.state!==G.REJECTED){o.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&ue.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}),i=this._participants[t]),i.state=G.CALLED,i.mediaSettings=ge((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=S.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],Y.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return c(this,null,function*(){var r,n;o.debug(`Participant joined [${e.participantId}]`);let t=S.composeMessageId(e),i=this._participants[t];if(i&&i.state===G.ACCEPTED){o.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&ue.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:S.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Ue.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=G.ACCEPTED,i.mediaSettings=ge(e.mediaSettings),i.participantState=S.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],Y.CONNECTED):this._setParticipantsStatus([i],Y.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((n=this._conversation)==null?void 0:n.observer))),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new w(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=S.composeMessageId(e);this._changeRemoteMediaSettings(t,ge(e.mediaSettings))}_onParticipantStateChanged(e){let t=S.composeMessageId(e);this._changeRemoteParticipantState(t,S.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),E.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return c(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ge(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),d.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Ai(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=Ai(this._serverSettings,r),o.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=S.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return c(this,null,function*(){E.onDeviceSwitched(se.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return c(this,null,function*(){let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),E.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return c(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=S.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),E.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return c(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getParticipantId(e.initiator);E.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else E.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!gt(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,E.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!gt(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,E.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return c(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){o.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let l=this._participants[e.participantId];l&&(o.debug(`Mute states for participant [${e.participantId}] changed`,i),E.onMuteStates(i,r,n,e.muteAll,e.unmute,l.externalId,s==null?void 0:s.externalId));return}S.isObjectsEquals(this._conversation.muteStates,i)&&S.isArraysEquals(this._conversation.unmuteOptions,r)&&!n.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(n,e.muteAll,e.unmute,t,s)))})}_processMuteState(){return c(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==G.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),l=this._conversation.unmuteOptions,p=this._mediaSource.getMediaSettings(),h=Object.entries(s);for(let[b,P]of h)if(!(P!==Be.MUTE&&P!==Be.MUTE_PERMANENT)&&(this._isCallAdmin()&&P===Be.MUTE_PERMANENT&&(s[b]=Be.MUTE),!(!e.includes(b)||i)))switch(b){case se.VIDEO:p.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(E.onDeviceSwitched(se.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case se.AUDIO:p.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(E.onDeviceSwitched(se.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case se.SCREEN_SHARING:p.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(E.onDeviceSwitched(se.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}E.onMuteStates(s,l,e,t,i,null,n==null?void 0:n.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?E.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&E.onLocalPin(!0)),this._participants[e]?E.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&E.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!tr(this._conversation.options,e)&&(this._conversation.options=e,E.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let n;if(i===this._conversation.compositeUserId||i==="")n=this._conversation.networkRating;else if(this._participants[i])n=this._participants[i].networkRating;else continue;if(n!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,E.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;o.log("Received network status update: ",e),E.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(d.producerScreenTrack){E.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,d.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){o.error("Received remote stream notification for a participant that has no track associated with it",r);return}let n=this._streamIdByStreamDescription.get(r);if(!n||this._streamWaitTimerByStreamDescription.has(r)){o.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(n);if(!s){m.log(_.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}E.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&E.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===Te.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Zi.ADD_PARTICIPANT);E.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&E.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}E.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return c(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===U.CONNECTED?i=Y.CONNECTED:t===U.CONNECTING||t===U.OPENED?i=Y.CONNECTING:t===U.RECONNECTING&&(i=Y.RECONNECT),!i)return;let r=e.reduce((n,s)=>{if(s in this._participants){let l=this._participants[s];n.push(l),t===U.CONNECTED&&(l.remoteStream||(l.mediaSettings&&this._changeRemoteMediaSettings(s,l.mediaSettings),this._changeRemoteParticipantState(s,l.participantState)),this._updateDisplayLayoutFromCache(s))}else o.warn(`Participant [${s}] isn't in conversation`);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return c(this,null,function*(){o.debug(`Local transport state has changed: ${e}`),e===U.CONNECTED&&E.onLocalStatus(Y.CONNECTED),e===U.CONNECTING&&E.onLocalStatus(Y.CONNECTING),e===U.RECONNECTING&&E.onLocalStatus(Y.RECONNECT),e===U.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(M.FAILED)),this._close(new w(M.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return c(this,null,function*(){if(e.endsWith(Pe.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(Pe.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))o.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{o.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(o.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],Y.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===de.audio&&(this._audioOutput.add(i),t.removeTrack(i)),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;E.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),d.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(o.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case de.audio:this._removeAudioTrack(e,t,i);break;case de.video:case de.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Pe.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onRemoteActivityNoSignal(){this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)}_onTopologyChanged(e){this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let n=this._participants[r];e||this._lastStalled[r]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,Y.RECONNECT),i.length&&this._setParticipantsStatus(i,Y.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let s=this._participants[n];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let s=this._participants[n];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,Y.RECONNECT),r.length&&this._setParticipantsStatus(r,Y.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!C.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),E.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return c(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==Te.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,s)=>(s.status!==t&&(s.status=t,d.batchParticipantsOnStart?n.push(s.externalId):E.onParticipantStatus(s.externalId,t,i)),n),[]);!r.length||d.batchParticipantsOnStart&&E.onRemoteStatus(r,t,i)}},x=B;x._delayedHangup=!1;var Xt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Xt.prototype),this.participantErrors=t}};var Zt;function hn(){return c(this,null,function*(){var a;if(d.apiEnv!=="AUTO")return d.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(a=i==null?void 0:i.Answer[0])==null?void 0:a.data;if(!r)throw new Error("Wrong DNS response");return o.debug("Resolved API endpoint",r),r}catch(e){return o.warn("Failed to resolve API endpoint using DNS, default is used",e),d.apiEndpoint}})}function zr(){if(!d.apiKey)throw new w(ee.API,{message:"Required argument apiAppKey not passed"})}function Ui(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Xr(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${Zt}/fb.do`,r)}function Qr(i){return c(this,arguments,function*(a,e={},t=!1){Zt||(Zt=yield hn());let r=Xr(a,e,t);return _n(r)})}function _n(a){return c(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${Zt}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(n){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(a)})})}function Xr(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=d.apiKey),t||(Z.sessionKey?e.session_key=Z.sessionKey:Z.accessToken&&(e.access_token=Z.accessToken));for(let[r,n]of Object.entries(e))typeof n=="object"&&(e[r]=JSON.stringify(n));let i="";for(let[r,n]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(n)}`;return i}var fn=10,Sn=700,vn=3e3,Mt=class extends tt{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return c(this,arguments,function*(e,t={},i=!1){let n=s=>c(this,null,function*(){try{return yield Qr(e,t,i)}catch(l){if(!l.hasOwnProperty("error_msg")&&(s++,o.debug(`${e} network error, attempt ${s}...`),s<fn))return yield S.delay(Math.min(s*Sn,vn)),n(s);throw o.warn(e,"error",l),l}});return n(0)})}_call(r){return c(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){o.warn("Api call error",n);let s=ee.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=M.SERVICE_DISABLED;break;case 1102:s=M.CALLEE_IS_OFFLINE;break;case 1103:s=M.NOT_FRIENDS;break;case 1104:case 1106:s=M.EXTERNAL_API_ERROR;break}throw new w(s,{message:n.error_msg,code:n.error_code})}})}userId(e){return c(this,null,function*(){let t=S.decomposeId(e).id;return Z.isEmpty()?pe.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),pe.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return c(this,null,function*(){Z.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return c(this,null,function*(){if(!this._uuid){let t=Ve.get("uuid");t||(t=S.uuid(),Ve.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:d.appVersion,client_type:"SDK_JS"}};return d.authToken&&(e.session_data.auth_token=d.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),Z.sessionKey=t.session_key,Z.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&E.onTokenExpired(),new w(ee.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${d.appName}:${d.sdkVersion}`,platform:d.platform,items:e})};Ui("log.externalLog",t)}init(){zr()}joinConversation(e,t=!1,i){return c(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:d.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return c(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1};return t&&(r.payload=t),d.domain&&(r.domainId=d.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,n="",s=!1,l=!1){return c(this,null,function*(){let p={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case we.USER:p.uids=t.join(",");break;case we.GROUP:p.gid=t[0];break;case we.CHAT:p.chatId=t[0];break}return s&&(p.createJoinLink=!0),n&&(p.payload=n),d.domain&&(p.domainId=d.domain),l&&(p.requireAuthToJoin=!0),this._startConversation(p)})}_startConversation(e){return c(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return c(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return c(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return c(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i){return c(this,null,function*(){let r={joinLink:e,isVideo:t,protocolVersion:d.protocolVersion};return(i==null?void 0:i.length)&&(r.observedIds=i.join(",")),d.anonymToken&&(r.anonymToken=d.anonymToken),this._call("vchat.joinConversationByLink",r)})}getOkIdsByExternalIds(e){return c(this,null,function*(){let t=pe.fromIds(e),i=[],r={methods:[]},n=[],s=Object.keys(this._externalUidsCache),l=Object.values(this._externalUidsCache);for(let h of t){let b=pe.toString(h),P=l.indexOf(b);P>-1?i.push(Number(s[P])):(n.push(b),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:h.id,anonym:h.type===ze.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((h,b)=>{if(h.ok){let P=Number(h.ok.ok_id);this._externalUidsCache[P]=n[b],i.push(P)}}),i})}getExternalIdsByOkIds(e){return c(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(pe.fromString(this._externalUidsCache[n])):i.push(n);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let n of i)r.hasOwnProperty(n)&&t.push(pe.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=pe.toString(e),n=i.indexOf(r);return n>-1?S.composeUserId(t[n],Q.USER):null}cacheExternalId(e,t){let i=S.decomposeId(e).id;this._externalUidsCache[i]=pe.toString(t)}getConversationParams(e){return c(this,null,function*(){let t={};return d.anonymToken&&(t.anonymToken=d.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:M.HUNGUP};d.anonymToken&&(t.anonymToken=d.anonymToken),Ui("vchat.hangupConversation",t)}removeHistoryRecords(e){return c(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return c(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,n]of Object.entries(i.external_ids))t[r]=pe.fromIdToString(n,ze.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=pe.fromIdToString(n,ze.ANONYM);return t}catch(i){return t}})}};var Zr=(T=>(T.RECOVER="recover",T.ACCEPT_CALL="accept-call",T.ADD_PARTICIPANT="add-participant",T.REMOVE_PARTICIPANT="remove-participant",T.HANGUP="hangup",T.TRANSMIT_DATA="transmit-data",T.ACCEPT_PRODUCER="accept-producer",T.ALLOCATE_CONSUMER="allocate-consumer",T.CHANGE_MEDIA_SETTINGS="change-media-settings",T.CHANGE_PARTICIPANT_STATE="change-participant-state",T.CHANGE_STREAM_PRIORITIES="change-streams-priorities",T.UPDATE_DISPLAY_LAYOUT="update-display-layout",T.REPORT_PERF_STAT="report-perf-stat",T.RECORD_START="record-start",T.RECORD_STOP="record-stop",T.RECORD_SET_ROLE="record-set-role",T.RECORD_GET_STATUS="record-get-status",T.SWITCH_MICRO="switch-micro",T.SWITCH_TOPOLOGY="switch-topology",T.REQUEST_REALLOC="request-realloc",T.CHAT_MESSAGE="chat-message",T.CHAT_HISTORY="chat-history",T.CUSTOM_DATA="custom-data",T.GRANT_ROLES="grant-roles",T.MUTE_PARTICIPANT="mute-participant",T.PIN_PARTICIPANT="pin-participant",T.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",T.CHANGE_OPTIONS="change-options",T.GET_WAITING_HALL="get-waiting-hall",T.PROMOTE_PARTICIPANT="promote-participant",T.REQUEST_TEST_MODE="request-test-mode",T.ADD_MOVIE="add-movie",T.UPDATE_MOVIE="update-movie",T.REMOVE_MOVIE="remove-movie",T))(Zr||{}),H=Zr;var ea="open",ta=[()=>d.producerScreenTrack,()=>d.videoTracksCount>0,()=>!0,()=>d.filteredMessages,()=>d.consumerScreenTrack,()=>!0,()=>d.movieShare],En=10,ye=class extends rt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+d.platform+"&appVersion="+d.appVersion+"&version="+d.protocolVersion+"&device="+d.device+"&capabilities="+ye._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null}static _getCapabilityFlags(){let e=0;for(let t=0;t<ta.length;t++)ta[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return c(this,null,function*(){return this.postfix+=`&clientType=${d.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){m.log(_.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return c(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=S.decomposeParticipantId(t.participantId),s=S.decomposeId(n.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),n.deviceIdx&&(t.deviceIdx=n.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return c(this,arguments,function*(e,t={},i=0){let n=s=>{var p;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((p=this.producerCommandDataChannel)==null?void 0:p.readyState)===ea&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){m.log(_.SOCKET_ACTION,"not_opened"),o.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(m.log(_.SOCKET_ACTION,"invalid_state"),o.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,l)=>{let p=(b,P=!1)=>{!i||P?l(b):(o.debug("Resending a signaling message",e,h.sequence),i--,n(h))},h={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:p};n(h)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return c(this,null,function*(){return this._send(H.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return c(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return c(this,null,function*(){return this._send(H.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return c(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return c(this,null,function*(){return this._send(H.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return c(this,null,function*(){return this._send(H.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},En)})}changeParticipantState(e){return c(this,null,function*(){return this._send(H.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return c(this,null,function*(){return this._send(H.ADD_PARTICIPANT,qi({participantId:e},t))})}removeParticipant(e,t=!1){return c(this,null,function*(){return this._send(H.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return c(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(H.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return c(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(H.ACCEPT_PRODUCER,i)})}changePriorities(e){return c(this,null,function*(){return this._send(H.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return c(this,null,function*(){return this._send(H.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return c(this,null,function*(){return this._send(H.ADD_MOVIE,e)})}updateMovie(e){return c(this,null,function*(){return this._send(H.UPDATE_MOVIE,e)})}removeMovie(e){return c(this,null,function*(){return this._send(H.REMOVE_MOVIE,e)})}startStream(e){return c(this,null,function*(){return this._send(H.RECORD_START,e)})}stopStream(){return c(this,null,function*(){return this._send(H.RECORD_STOP)})}recordSetRole(e,t){return c(this,null,function*(){return this._send(H.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return c(this,null,function*(){return this._send(H.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return c(this,null,function*(){return this._send(H.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return c(this,null,function*(){return this._send(H.REQUEST_REALLOC)})}reportPerfStat(e){return c(this,null,function*(){return this._send(H.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return c(this,null,function*(){return this._send(H.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return c(this,null,function*(){return this._send(H.CHAT_HISTORY,{count:e})})}customData(e,t){return c(this,null,function*(){return this._send(H.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return c(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(H.GRANT_ROLES,r)})}muteParticipant(e,t,i){return c(this,null,function*(){return this._sendRaw(H.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return c(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(H.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return c(this,null,function*(){return this._send(H.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return c(this,null,function*(){return this._send(H.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return c(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(H.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return c(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(H.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===xe.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),o.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){o.debug("Socket opened"),m.log(_.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){m.log(_.SOCKET_ACTION,"parse_error"),o.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(o.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(he.RECONNECT,e),e.conversation.topology&&this._triggerEvent(he.NOTIFICATION,{type:"notification",notification:k.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(he.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(m.log(_.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(m.log(_.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new w(M.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(he.NOTIFICATION,{notification:k.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new w(ee.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(m.log(_.SOCKET_ACTION,"unknown_message"),o.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(he.FAILED,e)}_onError(e){m.log(_.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){m.log(_.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<ye.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(ye.RECONNECT_MAX_DELAY,ye.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),m.log(_.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,xe.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],m.log(_.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),ye.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),n=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==ea){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}ye._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),ye.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(n))}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),ye.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(n))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new w(ee.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},ye.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{o.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(xe.RETRY)},ye.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},De=ye;De.RECONNECT_DELAY=d.signalingReconnectDelay,De.RECONNECT_MAX_DELAY=d.signalingReconnectMaxDelay,De.RECONNECT_MAX_COUNT=d.signalingReconnectMaxCount,De.WAIT_CONNECTION_DELAY=d.waitConnectionDelay,De.WAIT_RESPONSE_DELAY=d.waitResponseDelay,De.WAIT_MESSAGE_DELAY=d.waitMessageDelay;var ia=(t=>(t.KING="KING",t.PAWN="PAWN",t))(ia||{}),ra=ia;var mt,ae,Dt=null,Tn={getCameras:C.getCameras,getMicrophones:C.getMicrophones,getOutput:C.getOutput,hasCamera:C.hasCamera,hasMicrophone:C.hasMicrophone,getSavedCamera:C.getSavedCamera,getSavedMicrophone:C.getSavedMicrophone,getSavedOutput:C.getSavedOutput,hasCameraPermission:C.hasCameraPermission,hasMicrophonePermission:C.hasMicrophonePermission,hasPermissions:C.hasPermissions,getUserMedia:C.getUserMedia,getUserVideo:C.getUserVideo,getUserAudio:C.getUserAudio,saveDeviceId:C.saveDeviceId,isBrowserSupported:C.isBrowserSupported,isScreenCapturingSupported:C.isScreenCapturingSupported,os:C.os,isMobile:C.isMobile,browserName:C.browserName,browserVersion:C.browserVersion,baseChromeVersion:C.baseChromeVersion,getAudioContext:C.getAudioContext};function aa(a){ae=a}function na(a){mt=a}function In(a){Dt=a}function Cn(a){d.videoEffects=a}function yn(a){return c(this,null,function*(){if(d.set(a),C.browserName()==="Sferum"&&(d.platform=`SFERUM:${C.browserVersion()}`),ae||aa(new Mt),mt||na(()=>new De),d.debug&&(Bi.default.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${d.sdkVersion}`,a),yield C.init(),!C.isBrowserSupported())throw new w(ee.UNSUPPORTED);ae.init()})}function Rn(n){return c(this,arguments,function*(a,e=[se.AUDIO],t="",i=!1,r=!1){let s=[],l=[];if(Array.isArray(a)?s=a.length?a:[]:a&&(s=[a]),s.length&&(l=yield ae.getOkIdsByExternalIds(s),!l.length))throw new w(M.CALLEE_IS_OFFLINE);return sa(l,we.USER,e,t,i,r)})}function sa(s){return c(this,arguments,function*(a,e=we.USER,t,i="",r=!1,n=!1){if(x.current())throw o.error("There is already active call"),new w(M.FAILED);return new x(ae,mt(),Dt).onStart(a,e,t,i,r,n)})}function bn(a){return c(this,null,function*(){return oa(a)})}function oa(i){return c(this,arguments,function*(a,e=Q.USER,t){if(a===x.id())throw new Error("Push has already been processed");return new x(ae,mt(),Dt).onPush(a,e,t)})}function Pn(a){return c(this,null,function*(){return a&&(d.authToken=a),ae.authorize()})}function Mn(){return c(this,arguments,function*(a=[se.AUDIO]){let e=x.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function Dn(){return c(this,null,function*(){let a=x.current();if(a)return a.decline()})}function An(t){return c(this,arguments,function*(a,e=[se.AUDIO]){return ca(a,e)})}function ca(a,e,t){return c(this,null,function*(){if(x.current())throw o.error("There is already active call"),new w(M.FAILED);return new x(ae,mt(),Dt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function On(r){return c(this,arguments,function*(a,e=[se.AUDIO],t,i){if(x.current())throw o.error("There is already active call"),new w(M.FAILED);return t&&(d.anonymToken=t),new x(ae,mt(),Dt).onJoin({joinLink:a,mediaOptions:e,observedIds:i})})}function kn(){return c(this,null,function*(){let a=x.current();if(a)return a.hangup();x.hangupAfterInit()})}function wn(a,e){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return da(t[0],e)})}function da(a,e){return c(this,null,function*(){let t=x.current();t&&(yield t.addParticipant(S.composeUserId(a,Q.USER),e))})}function xn(a,e=!1){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);return la(t[0],e)})}function la(a,e=!1){return c(this,null,function*(){let t=x.current();t&&(yield t.removeParticipant(S.composeUserId(a,Q.USER),e))})}function Nn(a,e){return c(this,null,function*(){let t=yield C.saveDeviceId(a,e),i=x.current();return t&&i?i.changeDevice(a):Promise.reject()})}function Ln(a){return c(this,null,function*(){let e=x.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function Un(a,e=!1){return c(this,null,function*(){let t=x.current();t&&(yield t.setVideoStream(a,e))})}function Bn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalVideo(a))})}function Vn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.toggleLocalAudio(a))})}function Fn(a,e,t){return c(this,null,function*(){let i=x.current();if(i)return i.setLocalResolution(a,e,t)})}function Hn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.changePriorities(a))})}function Gn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.changeParticipantState(a))})}function Wn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.updateDisplayLayout(a))})}function jn(a,e,t=!1){return c(this,null,function*(){let i=yield ae.getOkIdsByExternalIds([a]);return pa(i[0],e,t)})}function pa(a,e,t=!1){return c(this,null,function*(){let i=x.current();i&&(yield i.grantRoles(S.composeUserId(a,Q.USER),e,t))})}function Kn(){return c(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield ae.getOkIdsByExternalIds([a]))[0]),ua(i,e,t,ue.getDeviceIdx(a))})}function ua(){return c(this,arguments,function*(a=null,e,t=[],i=0){let r=x.current();if(r){let n=a?S.composeParticipantId(a,Q.USER,i):null;yield r.muteParticipant(n,e,t)}})}function $n(a,e=!1){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([a]);return ma(t[0],e,ue.getDeviceIdx(a))})}function ma(a,e=!1,t=0){return c(this,null,function*(){let i=x.current();i&&(yield i.pinParticipant(S.composeParticipantId(a,Q.USER,t),e))})}function qn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.updateMediaModifiers(a))})}function Jn(a){return c(this,null,function*(){let e=x.current();e&&(yield e.changeOptions(a))})}function Yn(a,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),ha(a,t)})}function ha(a,e=null){return c(this,null,function*(){let t=x.current();if(t){let i=e?S.composeUserId(e,Q.USER):null;yield t.chatMessage(a,i)}})}function zn(a=10){return c(this,null,function*(){let e=x.current();if(e)return e.chatHistory(a)})}function Qn(a,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),_a(a,t,ue.getDeviceIdx(e))})}function _a(a,e=null,t=0){return c(this,null,function*(){let i=x.current();if(i){let r=e?S.composeParticipantId(e,Q.USER,t):null;yield i.customData(a,r)}})}function Xn(a="",e=!1){return c(this,null,function*(){return(yield ae.createConversation(S.uuid(),a,e)).join_link})}function Zn(){return c(this,null,function*(){let a=x.current();return a?a.createJoinLink():Promise.reject()})}function es(){return c(this,null,function*(){let a=x.current();return a?a.removeJoinLink():Promise.reject()})}function ts(a,e){return c(this,null,function*(){return ae.getAnonymTokenByLink(a,e)})}function is(a){let e=x.current();e&&e.setVolume(a)}function rs(a){d.forceRelayPolicy=a}function as(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return c(this,null,function*(){let n=x.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function ns(){return c(this,null,function*(){let a=x.current();return a?a.stopStream():Promise.reject()})}function ss(a,e){return c(this,null,function*(){let t=x.current();if(t){let i=yield ae.getOkIdsByExternalIds([a]),r=ue.getDeviceIdx(a);return t.recordSetRole(S.composeParticipantId(i[0],Q.USER,r),e)}return Promise.reject()})}function os(){return c(this,null,function*(){let a=x.current();return a?a.getStreamInfo():Promise.reject()})}function cs(a){return c(this,null,function*(){let e=x.current();return e?e.addMovie(a):Promise.reject()})}function ds(a,e,t,i){return c(this,null,function*(){let r=x.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function ls(a){return c(this,null,function*(){let e=x.current();return e?e.removeMovie(a):Promise.reject()})}function ps(a){d.statisticsInterval=a;let e=x.current();if(e)return e.updateStatisticsInterval()}function us(a){Bi.default.disableLog(!a),o.toggle(a)}function ms(a,...e){!d.debugLog||o.send(a,"[external]",...e)}function hs(a){return c(this,null,function*(){let e=x.current();if(e)return e.videoEffect(a)})}function _s(a){return c(this,null,function*(){let e=x.current();e&&(yield e.setAudioStream(a))})}function gs(a=null,e,t=!1){return c(this,null,function*(){let i=x.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(a,e,t)})}function fs(a,e=!1){return c(this,null,function*(){let t=x.current();if(!t)throw new Error("Conversation not found");let i=yield ae.getOkIdsByExternalIds([a]);return t.promoteParticipant(S.composeUserId(i[0],Q.USER),e)})}function Ss(a){return c(this,null,function*(){yield ae.removeHistoryRecords(a)})}