@vkontakte/calls-sdk 2.6.3-dev.bc23365.0 → 2.6.3-dev.c4e735f.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/calls-sdk.cjs.js +4 -4
- package/calls-sdk.esm.js +4 -4
- package/package.json +1 -1
package/calls-sdk.cjs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/calls-sdk v2.6.3-dev.
|
|
3
|
-
* Tue, 28 Feb 2023
|
|
2
|
+
* @vkontakte/calls-sdk v2.6.3-dev.c4e735f.0
|
|
3
|
+
* Tue, 28 Feb 2023 04:26:36 GMT
|
|
4
4
|
* https://st.mycdn.me/static/callssdk/2-6-3/doc/
|
|
5
5
|
*/
|
|
6
6
|
|
|
@@ -8,5 +8,5 @@ var dn=Object.create;var Lt=Object.defineProperty,ln=Object.defineProperties,pn=
|
|
|
8
8
|
`;if(!m&&!I&&!A&&!Z&&!j&&!P)return _;function Ge(z){let _e=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],Ie="a=rtcp-fb:111",ie=z.findIndex(X=>X.startsWith(Ie));return~ie&&(z[ie]=z[ie]+ke+_e.join(ke)),z}function ze(z,_e,Ie){let ie=z.split(" "),X=ie.slice(0,3),ce;for(ce=3;ce<ie.length;ce++)Ie.includes(ie[ce])&&X.push(ie[ce]);for(ce=3;ce<ie.length;ce++)!Ie.includes(ie[ce])&&!_e.includes(ie[ce])&&X.push(ie[ce]);return X.join(" ")}function xe(z,_e){let Ie=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),ie,X=[];for(ie=0;ie<z.length;++ie){let ce=z[ie].match(Ie);ce&&ce.length===3&&ce[2]===_e&&X.push(ce[1])}return X}function Le(z,_e,Ie,ie){let X,ce="m="+_e;for(X=0;X<z.length;++X)if(z[X].startsWith(ce)){z[X]=ze(z[X],Ie,ie);break}}function Ne(z,_e){let Ie=new RegExp(Ji+"(\\d+)");for(let ie=0;ie<z.length;++ie){let X=z[ie].match(Ie);if(X&&X.length===2&&_e.includes(X[1])){let ce=z[ie].trim()===Ji+X[1]?" ":";";z[ie]+=ce+Mn}}}function We(z){let _e=xe(z,"H264");if(I){let Ie=_e.slice(0),ie=new RegExp(Ji+"(\\d+) apt=(\\d+)"),X;for(X=0;X<z.length;++X){let Je=z[X].match(ie);Je&&Je.length===3&&Ie.includes(Je[2])&&Ie.push(Je[1])}let ce=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(X=z.length;X--;){let Je=z[X].match(ce);Je&&Je.length===3&&Ie.includes(Je[2])&&z.splice(X,1)}Le(z,"video",Ie,[])}else m&&Le(z,"video",[],_e),P&&Ne(z,_e)}function L(z){let _e=xe(z,"VP9");A&&Le(z,"video",[],_e)}function U(z){let _e=xe(z,"red");_e.length>0&&Le(z,"audio",[],_e)}let _t=_.split(Ee);return(I||m||P)&&We(_t),A&&L(_t),Z&&U(_t),j&&Ge(_t),_t.join(ke)}Li.patchLocalSDP=n;function e(_){return y.browserName()==="Firefox"&&Number(y.browserVersion())<60&&(_=_.replace("m=application 9 UDP/DTLS/SCTP webrtc-datachannel","m=application 9 DTLS/SCTP 5000").replace("a=sctp-port:5000","a=sctpmap:5000 webrtc-datachannel 256")),_}Li.patchRemoteSDP=e;function t(_){return _?`${_.type||"WEB_SOCKET"}_${_.id}`:"_"}Li.getPeerIdString=t;function i(_,m){return _&&_.id===m.id&&(_.type||"WEB_SOCKET")===(m.type||"WEB_SOCKET")}Li.comparePeerId=i;function r(_){return o(this,null,function*(){return!_||!_.getStats?Promise.resolve(null):_.getStats(null).then(m=>{let I=null,A=null;if(m.forEach(P=>{P.type==="transport"&&P.selectedCandidatePairId?A=m.get(P.selectedCandidatePairId):P.type==="candidate-pair"&&P.state==="succeeded"&&!A&&(!P.hasOwnProperty("selected")||P.selected)&&(A=P)}),A&&A.localCandidateId){let P=m.get(A.localCandidateId);P&&(I={type:P.candidateType,ip:P.ip||P.ipAddress,port:P.port||P.portNumber})}return I}).catch(()=>null)})}Li.getPeerConnectionHostInfo=r;let a=/^[0-9]+$/,s=/^([gu])([0-9]+)$/;function d(_,m){let I=String(_);return s.test(I)?(c.warn(`Already composite id [${_}] type supplied [${m}]`),I):m===te.GROUP?"g"+I:m===te.USER?"u"+I:(c.warn(`Unknown type [${m}] for id [${_}]`),I.match(a)?"u"+I:I)}Li.composeUserId=d;function l(_,m,I){let A=d(_,m);return u(A,I)}Li.composeParticipantId=l;function u(_,m){return m?_+Ct+si+m:_}Li.compose=u;function E(_){return l(_.id,_.idType||te.USER,_.deviceIdx||0)}Li.composeId=E;function C(_){return _.participant?E(_.participant):l(_.participantId,_.participantType||te.USER,_.deviceIdx||0)}Li.composeMessageId=C;function M(_){let m=String(_),I=m.match(s);return I?{id:Number(I[2]),type:I[1]==="g"?te.GROUP:te.USER}:(c.warn(`Unsupported compositeId [${_}]`),{id:Number(m),type:te.USER})}Li.decomposeId=M;function O(_){let m=_.split(Ct+si);return{compositeUserId:m[0],deviceIdx:m.length>1?parseInt(m[1],10):0}}Li.decomposeParticipantId=O;function w(){var Z,Ee;let _=(Ee=(Z=window.crypto)==null?void 0:Z.randomUUID)==null?void 0:Ee.call(Z);if(_)return _;let m="0123456789abcdefghijklmnopqrstuvwxyz".split(""),I=new Array(36),A=0,P,j;for(j=0;j<36;j++)j===8||j===13||j===18||j===23?I[j]="-":j===14?I[j]="4":(A<=2&&(A=33554432+Math.random()*16777216|0),P=A&15,A=A>>4,I[j]=m[j===19?P&3|8:P]);return I.join("")}Li.uuid=w;function F(_,m){let I;function A(){let P=this,j=arguments;I&&window.clearTimeout(I),I=window.setTimeout(()=>{_.apply(P,j)},m)}return A}Li.throttle=F;function de(_){if(!window.BigInt)return null;let m="",I=_.split(`
|
|
9
9
|
`);for(let j of I)if(j.startsWith("a=fingerprint")){let Z=j.split(" ");if(Z.length===2){m=Z[1];break}}if(!m)return BigInt(-1);let A=m.split(":"),P=BigInt(0);for(let j=Math.min(7,A.length-1);j>=0;j--){let Z=BigInt(parseInt(A[j],16));P<<=BigInt(8),P|=Z}return BigInt.asIntN(64,P)}Li.sdpFingerprint=de;function q(_){return o(this,null,function*(){return new Promise(m=>window.setTimeout(m,_))})}Li.delay=q;function De(_,m,I){let A=[];return _.getSenders().forEach(P=>re(m,P,P.track,I,A)),A}Li.applySettings=De;function re(_,m,I,A,P){var j;if(_&&I&&I.kind===pe.video){let Z=I.getSettings();if(Z){let Ee=_.maxBitrateK?_.maxBitrateK*1024:null,ke=Z.width,Ge=Z.height,ze=ke&&Ge&&_.maxDimension?Math.max(1,Math.max(ke,Ge)/_.maxDimension):null,xe=_.maxFramerate?_.maxFramerate:null;if(ke&&Ge&&_.maxDimension&&_.maxDimension>Math.max(ke,Ge)){let L=Math.round(ke*Ge/256),U=(Math.round(L*bn/1e4)+1)*1e4;Ee=Ee===null?U:Math.min(U,Ee)}let Le=_.degradationPreference?_.degradationPreference:"balanced",Ne=A[I.id];if(Ne&&Ne.bitrate===Ee&&Ne.scaleResolutionDownBy===ze&&Ne.maxFramerate===xe&&Ne.degradationPreference===Le){P[I.id]=Ne;return}P[I.id]={bitrate:Ee,scaleResolutionDownBy:ze,maxFramerate:xe,degradationPreference:Le};let We=m.getParameters();We.encodings||(We.encodings=[{}]),We.encodings.forEach(L=>{Ee?L.maxBitrate=Ee:delete L.maxBitrate,ze?L.scaleResolutionDownBy=ze:delete L.scaleResolutionDownBy,xe?L.maxFramerate=xe:delete L.maxFramerate}),We.degradationPreference=Le,(j=m.setParameters)==null||j.call(m,We)}}}Li.applyVideoTrackSettings=re;function Ce(_,m){Array.isArray(m)||(m=[m]);for(let I of m)if(_.includes(I))return!0;return!1}Li.includesOneOf=Ce;function be(_){var m;return Object.entries(((m=_.participantState)==null?void 0:m.state)||{}).reduce((I,[A,P])=>(_.participantState&&(I[A]={ts:_.participantState.stateUpdateTs[A],state:P}),I),{})}Li.mapParticipantState=be;function at(_){let m=_.map(I=>({uid:I.externalId,mediaSettings:I.mediaSettings,status:I.status,muteStates:I.muteStates,unmuteOptions:I.unmuteOptions,participantState:I.participantState,markers:I.markers,movieShareInfos:I.movieShareInfos}));return p.filterObservers?m.filter(I=>!I.uid.observer):m}Li.mapSharedParticipants=at;function ti(_,m){let I=Object.keys(_),A=Object.keys(m);if(I.length!==A.length)return!1;for(let P of I)if(!A.hasOwnProperty(P)||_[P].state!==m[P].state||_[P].ts!==m[P].ts)return!1;return!0}Li.isEqualParticipantState=ti;function Q(_,m){let I=Object.keys(_),A=Object.keys(m);if(I.length!==A.length)return!1;for(let P of I)if(!m.hasOwnProperty(P)||_[P]!==m[P])return!1;return!0}Li.isObjectsEquals=Q;function br(_,m){if(_.length!==m.length)return!1;for(let I of _)if(m.indexOf(I)<0)return!1;return!0}Li.isArraysEquals=br;function Oi(_){return!Object.keys(_).length}Li.isEmptyObject=Oi;function wi(_,m){if(!_&&!m)return 0;if(!_||!m)return _?-1:1;return A(m.rank,_.rank)||A(_.ts,m.ts)||I(_,m);function I(P,j){let Z={[te.USER]:0,[te.GROUP]:1},{compositeUserId:Ee,deviceIdx:ke}=O(P.id),{compositeUserId:Ge,deviceIdx:ze}=O(j.id),{id:xe,type:Le}=M(Ee),{id:Ne,type:We}=M(Ge);return A(Z[Le],Z[We])||A(xe,Ne)||A(ke,ze)}function A(P,j){return P<j?-1:P===j?0:1}}Li.participantMarkerCompare=wi;function Y(_,m){let I=Object.entries(_).filter(([,A])=>Array.isArray(m)?!m.includes(A):A!==m);return ha(I)}Li.objectFilterOutValues=Y;function xi(_,m,I){let A=I;for(let P in _)!_.hasOwnProperty(P)||(A=m(A,_[P],P));return A}Li.objectReduce=xi,Li.setImmediate=(()=>{let _=1,m={},I=null;return typeof MessageChannel!="undefined"&&(I=new MessageChannel,I.port1.onmessage=A=>{let P=A.data;m[P]&&(m[P](),delete m[P])}),function(A){if(I&&document.visibilityState==="hidden"){let j=_;return _=_>=Number.MAX_SAFE_INTEGER?1:_+1,m[j]=A,I.port2.postMessage(j),()=>{m[j]&&delete m[j]}}let P=setTimeout(A,0);return()=>clearTimeout(P)}})()})(Yi||(Yi={}));var v=Yi;var ot=null,Qi=null,oi=[],ci=[],Xi=[],Bt=null,Ft=null,Zi=null,er=!1,tr=!1,di,Rt,li,ir=null,rr="",pi=[],ar=null,ga=navigator.appVersion,An=navigator.appName,Ae=navigator.userAgent,nr=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(nr||{}),Vt=class{constructor(e,t=!1,i=p.videoMaxWidth,r=p.videoMaxHeight){let a=!1;if(e){a={noiseSuppression:p.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let d;Ft&&(d=Ft.deviceId),typeof e=="string"&&(d=e),d&&(a.deviceId={ideal:d})}let s=!1;if(t){s={width:{min:p.videoMinWidth,max:i,ideal:i},height:{min:p.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:p.videoAspectRatio},frameRate:{ideal:p.videoFrameRate}};let d;Bt&&(d=Bt.deviceId),typeof t=="string"&&(d=t),d&&(s.deviceId={ideal:d}),p.videoFacingMode&&(s.facingMode={ideal:p.videoFacingMode})}this.audio=a,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},fa=class extends Vt{constructor(e,t,i){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=p.screenFrameRate,tt.browserName()==="Safari"&&Number(tt.browserVersion())===16&&(delete this.video.width,delete this.video.height),i&&(this.audio={noiseSuppression:!1,echoCancellation:!1,autoGainControl:!1})}};function Dn(){return o(this,null,function*(){ot=null,yield ui()})}function kn(){ot=null,ui().then(()=>g.onDeviceChange())}function ui(){return o(this,null,function*(){return ot||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Qi&&navigator.mediaDevices.addEventListener&&(Qi=v.throttle(kn,1e3),navigator.mediaDevices.addEventListener("devicechange",Qi)),ot=navigator.mediaDevices.enumerateDevices().then(n=>{oi=n.filter(r=>r.kind==="videoinput"?(r.label&&(er=!0),!0):!1),ci=n.filter(r=>r.kind==="audioinput"?(r.label?tr=!0:tt.isMobile()&&tt.browserName()==="Firefox"&&(tr=er),!0):!1),Xi=n.filter(r=>r.kind==="audiooutput");let e=et.get("videoinput"),t=et.get("audioinput"),i=et.get("audiooutput");return Bt=oi.find(r=>r.deviceId===e)||null,Ft=ci.find(r=>r.deviceId===t)||null,Zi=Xi.find(r=>r.deviceId===i)||null,ot=Promise.resolve(n),n}).catch(()=>(ot=null,[]))))})}function mi(n,e){return o(this,null,function*(){c.debug("Try to get media",n.getNative());let t=tt.hasPermissions(n.isVideo());!t&&!e&&g.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(n.getNative());return t||(yield Dn()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=n.isVideo()?se.CAMERA_PERMISSION:se.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=n.isVideo()?se.CAMERA_ACCESS:se.MIC_ACCESS;break}if(n.canSimplify())return mi(n.simplify(),e);let r=e||se.UNKNOWN;throw g.onPermissionsError(r),r}})}function On(n){return o(this,null,function*(){c.debug("Try to get screen",n.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(n.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(c.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw se.SCREEN_PERMISSION;default:throw se.SCREEN_ACCESS}}})}function hi(){return pi.length||(pi=(()=>{let n,e=!1,t=0,i="0",r=Ae.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return n=/\brv[ :]+(\d+)/g.exec(Ae),["IE",n&&n[1]||"Unknown",e,t,i];if(r[1]==="Safari"){if(n=Ae.match(/\bEdge\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t,i];if(n=Ae.match(/\bCriOS\/(\d+)/),n)return["Chrome",n[1],!0,Number(n[1]),i];if(n=Ae.match(/\bFxiOS\/(\d+)/),n)return["Firefox",n[1],!1,t,i];if(n=Ae.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1],!1,t,i];if(n=Ae.match(/\bOPT\/(\d+)/),n)return["Opera",n[1],!1,t,i]}if(r[1]==="Chrome"){if(e=!0,t=Number(r[2]),n=Ae.match(/\bOPR\/(\d+)/),n)return["Opera",n[1]||"Unknown",e,t,i];if(n=Ae.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1]||"Unknown",e,t,i];if(n=Ae.match(/\bSferum\/((\d+)(?:\.\d+)*)/),n)return["Sferum",n[1]||"Unknown",e,t,i];if(n=Ae.match(/\bEdge?\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t,i];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t,i]}return n=Ae.match(/version\/(\d+)(?:(?:\.)(\d+))?/i),n&&n[2]!==void 0&&(i=n[2]),[r[2]?r[1]:An,n&&n[1]||r[2]||ga,e,t,i]})()),pi}var tt;(_=>{function n(){return o(this,null,function*(){let m=()=>{q(),document.removeEventListener("click",m),document.removeEventListener("touchstart",m)};return document.addEventListener("click",m),document.addEventListener("touchstart",m),ui()})}_.init=n;function e(){return oi}_.getCameras=e;function t(){return ci}_.getMicrophones=t;function i(){return Xi}_.getOutput=i;function r(){return oi.length>0}_.hasCamera=r;function a(){return ci.length>0}_.hasMicrophone=a;function s(){return Bt}_.getSavedCamera=s;function d(){return Ft}_.getSavedMicrophone=d;function l(){return Zi}_.getSavedOutput=l;function u(){return er}_.hasCameraPermission=u;function E(){return tr}_.hasMicrophonePermission=E;function C(m=!1){return E()?r()&&m?u():!0:!1}_.hasPermissions=C;function M(m=!1,I=!0,A=!0){return o(this,null,function*(){let P=a()&&I,j=r()&&m,Z;if(!P&&!j)Z=new MediaStream;else try{Z=yield mi(new Vt(P,j))}catch(Ee){Z=new MediaStream}return!Z.getVideoTracks().length&&A&&Z.addTrack(De()),!Z.getAudioTracks().length&&A&&Z.addTrack(q()),Z})}_.getUserMedia=M;function O(m){return o(this,null,function*(){return On(new fa(window.screen.width,window.screen.height,m))})}_.getScreenMedia=O;function w(m,I=!1){return o(this,null,function*(){let A=I?p.videoEffectMaxWidth:p.videoMaxWidth,P=I?p.videoEffectMaxHeight:p.videoMaxHeight;return mi(new Vt(!1,m||!0,A,P))})}_.getUserVideo=w;function F(m){return o(this,null,function*(){return mi(new Vt(m||!0,!1))})}_.getUserAudio=F;function de(m,I){return o(this,null,function*(){let P=(yield ui()).find(j=>j.kind===m&&j.deviceId===I);return P?(m==="videoinput"?Bt=P:m==="audioinput"?Ft=P:m==="audiooutput"&&(Zi=P),et.set(m,I),P):null})}_.saveDeviceId=de;function q(){if(!li||li.readyState==="ended"){let m=xi(),I=m.createMediaStreamDestination(),A=m.createGain();A.gain.value=1e-5,A.connect(I),A.connect(m.destination);let P=m.createOscillator();P.type="sine",P.frequency.value=0,P.connect(A),P.start(),li=I.stream.getAudioTracks()[0]}return Object.assign(li.clone(),{enabled:!1})}_.getSilentMediaTrack=q;function De(m=p.videoMinWidth,I=p.videoMinHeight){return Rt||(Rt=document.createElement("canvas"),Rt.getContext("2d")),Rt.width=m,Rt.height=I,(!di||di.readyState==="ended")&&(di=Rt.captureStream(p.videoFrameRate).getVideoTracks()[0]),Object.assign(di.clone(),{enabled:!1})}_.getBlackMediaTrack=De;function re(){if(Oi()==="Edge"&&Number(wi())<70)return!1;try{let m=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&m.RTCPeerConnection&&m.RTCIceCandidate&&m.RTCSessionDescription&&m.HTMLCanvasElement&&m.HTMLCanvasElement.prototype.captureStream&&m.RTCRtpSender&&m.RTCRtpSender.prototype.replaceTrack&&m.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(m){return!1}}_.isBrowserSupported=re;function Ce(){return!!navigator.mediaDevices.getDisplayMedia}_.isScreenCapturingSupported=Ce;function be(){let m=_.browserName()==="Safari"&&_.browserVersion()==="15"&&_.browserSubVersion()==="1",I=_.browserName()==="Opera"&&_.os()==="Windows";return m||I}_.isBrokenH264=be;function at(){return!(_.baseChromeVersion()&&_.isMobile())}_.canPreferH264=at;function ti(){var m;return((m=window.RTCRtpTransceiver)==null?void 0:m.prototype)&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype}_.canPreferRed=ti;function Q(){return rr||(rr=(()=>{let m={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let I in m)if(m.hasOwnProperty(I)&&m[I].test(Ae))return I;return"Unknown"})()),rr}_.os=Q;function br(){return ir===null&&(ir=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(ga)),ir}_.isMobile=br;function Oi(){return hi()[0]}_.browserName=Oi;function wi(){return hi()[1]}_.browserVersion=wi;function Y(){return hi()[3]}_.baseChromeVersion=Y;function xi(){return ar||(ar=new(window.AudioContext||window.webkitAudioContext)),ar}_.getAudioContext=xi;function Mr(){return hi()[4]}_.browserSubVersion=Mr;function Li(){return _.baseChromeVersion()>0&&!_.isMobile()}_.isAudioShareSupported=Li})(tt||(tt={}));var y=tt;var Ze=class extends $e{init(e){return o(this,null,function*(){c.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var i=Object.defineProperty;var b=a=>i(a,"__esModule",{value:!0});var E=(a,o)=>{b(a);for(var r in o)i(a,r,{get:o[r],enumerable:!0})};var D={};E(D,{default:()=>g});var s=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(s||{}),t=(e=>(e.INIT="init",e.READY="ready",e.FRAME="frame",e.SET_BITRATE="set_bitrate",e.ERROR="error",e.DEBUG="debug",e.LOG_ERROR="log_error",e))(t||{});var g=a=>{let o=null,r=!0;function l(){self.postMessage({type:t.READY})}function p(d,u,e,c=!1){if(!o||r!==e){if(!c){self.postMessage({type:t.DEBUG,message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}r=e,o?self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec changed to ${e?"VP9":"VP8"}`}):(self.postMessage({type:t.DEBUG,message:`WebCodecsDecoder codec ${e?"VP9":"VP8"}`}),o=new VideoDecoder({output:n=>{let m=a?[n]:[];self.postMessage({type:t.FRAME,data:n},m),n.close()},error:n=>{o&&o.state!=="closed"&&o.close(),o=null,self.postMessage({type:t.FRAME,error:"WebCodecsDecoder failed, reinitialize: "+String(n)})}})),o.configure({codec:e?s.VP9:s.VP8})}let f=new EncodedVideoChunk({type:c?"key":"delta",timestamp:d,data:u});o.decode(f)}self.onmessage=d=>{switch(d.data.type){case t.INIT:l();break;case t.FRAME:p(d.data.timestamp,d.data.data,d.data.isVP9,d.data.keyFrame);break}}};return D;})();\n',t=>{t.error?c.warn("WebCodecsDecoder",t.error):e(t.data)},[y.baseChromeVersion()>=92])})}decodeFrame(e,t,i,r=!1){this._sendToWorker(Se.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),c.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window}};var Sa=nt(require("bit-buffer"));var wn=65536,ct=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(c.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%wn!==e.sequence){c.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:a}=ct.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:a})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((a,s)=>a+s.data.byteLength,0),i=new Uint8Array(t),r=0;for(let a of e)i.set(new Uint8Array(a.data),r),r+=a.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new Sa.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 yt=class{constructor(e){this._onStream=e}drawFrame(e){return o(this,null,function*(){throw new Error("Method `drawFrame` is not supported by this implementation")})}drawImage(e){throw new Error("Method `drawImage` is not supported by this implementation")}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Ht=class extends yt{constructor(e){super(e);this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;c.debug("CanvasRenderer started"),this._useImageBitmap="ImageBitmap"in window}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}drawFrame(e){return o(this,null,function*(){let t="createImageBitmap"in e?yield e.createImageBitmap():yield createImageBitmap(e);this.drawImage(t),t.close()})}drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}destroy(){this._removeStream(),c.debug("CanvasRenderer destroyed")}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(y.browserName()==="Safari"&&Number(y.browserVersion())===15)&&!(y.browserName()==="Firefox"&&Number(y.browserVersion())<60)}};var Pt=class extends yt{constructor(e){super(e);c.debug("TrackGeneratorRenderer started"),this._generator=new MediaStreamTrackGenerator({kind:pe.video}),this._writer=this._generator.writable.getWriter(),this._stream=new MediaStream([this._generator]),this._onStream(this._stream)}drawFrame(e){return o(this,null,function*(){yield this._writer.write(e)})}destroy(){this._writer.releaseLock(),this._generator.writable.close().then(()=>this._generator.stop()),c.debug("TrackGeneratorRenderer destroyed")}static isBrowserSupported(){return"VideoFrame"in window&&"MediaStreamTrackGenerator"in window&&Ze.isBrowserSupported()}};var Gt=class extends ct{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];c.debug(`StreamBuilder started for participant [${e}]`),Pt.isBrowserSupported()?this._renderer=new Pt(t):this._renderer=new Ht(t),Ze.isBrowserSupported()?this._decoder=new Ze:this._decoder=new It;let i=r=>o(this,null,function*(){"VideoFrame"in window&&r instanceof VideoFrame?yield this._renderer.drawFrame(r):this._renderer.drawImage(r)});this._decoder.init(i).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._renderer.destroy(),c.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return Ht.isBrowserSupported()||Pt.isBrowserSupported()}};var Wt=1,xn=1,Ln=2,sr=0,_i=11,va=1,Ea=2,Ia=4,Ta=8;function Ca(n,e,t,i,r,a,s){let d=0;e&&(d|=va),t&&(d|=Ea),i&&(d|=Ia),s||(d|=Ta);let l=new ArrayBuffer(_i),u=new DataView(l);if(u.setUint8(0,Wt),u.setUint16(1,r),u.setUint32(3,n),u.setUint8(7,a?1:0),u.setUint16(8,sr),u.setUint8(10,d),!s)return l;let E=new Uint8Array(l.byteLength+s.byteLength);return E.set(new Uint8Array(l),0),E.set(new Uint8Array(s),l.byteLength),E.buffer}function Ra(n){let e=new DataView(n),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),a=e.getUint8(7)===1,s=e.getUint16(8),d=e.getUint8(10),l=!!(d&va),u=!!(d&Ea),E=!!(d&Ia),C=!!(d&Ta);if(t!==Wt)throw new Error(`Unexpected protocol version. Got ${t}, expected ${Wt}`);return{timestamp:r,start:l,end:u,keyframe:E,sequence:i,isVP9:a,ssrc:s,eos:C,data:n.slice(_i)}}function ya(n){if(!n||!n.byteLength||n.byteLength!==4)return!1;let e=new DataView(n);return!(e.getUint8(0)!==Wt||e.getUint8(1)!==xn||e.getUint16(2)!==sr)}function Pa(n){if(!n||!n.byteLength||n.byteLength!==10)return null;let e=new DataView(n);if(e.getUint8(0)!==Wt||e.getUint8(1)!==Ln||e.getUint16(2)!==sr)return null;let a=e.getUint16(4),s=e.getUint32(6);return{seq:a,ts2:s}}var R=nt(require("simple-ebml-builder"));var Nn=Or(2,15)-1,or=1,Un=5,Bn=5;var gi=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),c.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=gi._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return R.build(e[0])}else return new Uint8Array;let t=e.reduce((a,s)=>a+s.countSize(),0),i=new Uint8Array(t),r=0;for(let a of e){let s=R.build(a);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var a,s,d;((a=this._mediaSource)==null?void 0:a.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let e=(d=this._sourceBuffer)==null?void 0:d.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-Un);r-i>Bn&&(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}},Fe=class extends ct{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;c.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return R.element(R.ID.EBML,[R.element(R.ID.EBMLVersion,R.number(1)),R.element(R.ID.EBMLReadVersion,R.number(1)),R.element(R.ID.EBMLMaxIDLength,R.number(4)),R.element(R.ID.EBMLMaxSizeLength,R.number(8)),R.element(R.ID.DocType,R.string("webm")),R.element(R.ID.DocTypeVersion,R.number(2)),R.element(R.ID.DocTypeReadVersion,R.number(2))])}static _genSegmentHeader(e,t,i){let r=R.element(R.ID.Info,[R.element(R.ID.TimecodeScale,R.number(1e6)),R.element(R.ID.MuxingApp,R.string("vk-webm-builder")),R.element(R.ID.WritingApp,R.string("vk-webm-builder"))]),a=[R.element(R.ID.PixelWidth,R.number(e)),R.element(R.ID.PixelHeight,R.number(t))],s=R.element(R.ID.Tracks,R.element(R.ID.TrackEntry,[R.element(R.ID.TrackNumber,R.number(or)),R.element(R.ID.TrackUID,R.number(or)),R.element(R.ID.TrackType,R.number(1)),R.element(R.ID.FlagLacing,R.number(0)),R.element(R.ID.DefaultDuration,R.number(1e9)),R.element(R.ID.CodecID,R.string(`V_${i.toUpperCase()}`)),R.element(R.ID.Video,a)]));return R.unknownSizeElement(R.ID.Segment,[r,s])}static _genClusterHeader(e){return R.unknownSizeElement(R.ID.Cluster,[R.element(R.ID.Timecode,R.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new gi(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){c.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>c.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,c.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),c.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=Fe._genWebmHeader();this._mediaBuffer.append(s);let d=Fe._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(d)}let r=Math.round(i-this._clusterStartTime);if(r>Nn&&(this._clusterStartTime=i,r=0),r===0){c.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=Fe._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let a=R.element(R.ID.SimpleBlock,[R.vintEncodedNumber(or),R.bytes(Fe._intToU16BE(r)),R.number((e.keyframe?1:0)<<7),R.bytes(e.frameData)]);this._mediaBuffer.append(a,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),c.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var bt=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};c.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=a=>this._onDataChannelMessage(a.data)}_onDataChannelMessage(e){var a,s;let t=Ra(e),i=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){c.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];if(!r){let d=l=>this._onStream(i,l);p.screenShareWebmBuilder&&Fe.isBrowserSupported()?r=new Fe(i,d):r=new Gt(i,d),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,c.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(Ze.isBrowserSupported()||It.isBrowserSupported())&&(Gt.isBrowserSupported()||Fe.isBrowserSupported())}};var cr=nt(require("@vkontakte/libvpx"));var Fn=1e3,jt=class extends $e{constructor(e,t,i,r){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useCongestionControl=i,this._maxBitrate=r,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return o(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=d=>t(),r.onerror=()=>i(new Error("Video element error"));let a=r.play(),s=()=>i(new Error("Autoplay is disabled"));a?a.catch(s):s()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");this._video.paused&&this._video.play();let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return o(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return o(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;c.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var m=Object.defineProperty;var y=s=>m(s,"__esModule",{value:!0});var x=(s,i)=>{y(s);for(var d in i)m(s,d,{get:i[d],enumerable:!0})};var h={};x(h,{default:()=>V});var t=(a=>(a.INIT="init",a.READY="ready",a.FRAME="frame",a.SET_BITRATE="set_bitrate",a.ERROR="error",a.DEBUG="debug",a.LOG_ERROR="log_error",a))(t||{});var V=(s,i,d,E)=>{let r;function g(e,o){return s({locateFile:i}).then(n=>{if(r=new n.VpxEncoder,r.debug(o),!r.init(e?n.VpxType.VP9:n.VpxType.VP8))throw self.postMessage({type:t.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");if(d){let p=Math.round(E/1e3);r.setTargetBitrate(p)}else r.setMaxQuantizer(10),r.setTargetBitrate(1024)})}function R(e,o,n,c){let p=r.allocateImage(e,o);if(!p){self.postMessage({type:t.FRAME,error:"No buffer data"});return}p.set(new Uint8Array(n));let f=Math.round(performance.now()),u=150;if(!r.encode(f,u,c)){self.postMessage({type:t.FRAME,error:"Encode failed"});return}let l=r.readFrame();if(!l){self.postMessage({type:t.FRAME,error:"No encoded data"});return}r.readFrame()&&(self.postMessage({type:t.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxEncoder-drop"}));let b=new Uint8Array(l.byteLength);b.set(l),self.postMessage({type:t.FRAME,frameType:c?"key":"delta",timestamp:f,duration:u,width:e,height:o,data:b.buffer},[b.buffer])}function a(e,o){let n=Math.round(e/1e3);r.setTargetBitrate(n)}self.onmessage=e=>{switch(e.data.type){case t.INIT:g(e.data.isVP9,e.data.debug).then(()=>self.postMessage({type:t.READY})).catch(o=>self.postMessage({type:t.ERROR,error:String(o)}));break;case t.FRAME:R(e.data.width,e.data.height,e.data.imageData,e.data.keyFrame);break;case t.SET_BITRATE:a(e.data.bitrate,e.data.useCbr);break}}};return h;})();
|
|
10
10
|
`,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength,width:i.width,height:i.height})},[cr.default,cr.default.getUrl,this._useCongestionControl,this._maxBitrate],{isVP9:this.isVP9(),debug:c.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(Se.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},Fn),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}setBitrate(e,t=!1){this._sendToWorker(Se.SET_BITRATE,{bitrate:e,useCbr:t})}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),c.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var Mt=class extends $e{constructor(e,t,i,r){super();this._sourceTrack=e,this._onFrame=t,this._useCongestionControl=i,this._maxBitrate=r,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return o(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;c.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var A=Object.defineProperty;var B=n=>A(n,"__esModule",{value:!0});var x=(n,i)=>{B(n);for(var o in i)A(n,o,{get:i[o],enumerable:!0})};var P={};x(P,{default:()=>I});var c=(o=>(o.VP9="vp09.00.50.08",o.VP8="vp8",o))(c||{}),a=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.SET_BITRATE="set_bitrate",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(a||{});var I=()=>{let n=1e3,i,o,l,d,R,p,t=null,E=0,u=!1,s=0,g,V,y=!1;function F(e){i=e.readable,o=i.getReader(),l=e.width,d=e.height,R=e.isVP9,p=e.framerate,g=e.useCongestionControl,V=e.maxBitrate,g&&(s=V),f(),self.postMessage({type:a.READY})}function C(e){E=self.setTimeout(()=>{t&&h(t,e)},n),!u&&(u=!0,o.read().finally(()=>{u=!1,self.clearTimeout(E)}).then(({done:r,value:b})=>{if(t==null||t.close(),t=null,!(r||!b)){if(!m){o.releaseLock(),i.cancel();return}t=b,h(b,e)}}))}function h(e,r){(e.codedWidth!==l||e.codedHeight!==d)&&(l=e.codedWidth,d=e.codedHeight,f()),m.encode(e,{keyFrame:r})}function f(){let e={framerate:p,codec:R?c.VP9:c.VP8,width:l,height:d,latencyMode:"realtime",bitrateMode:y?"constant":"variable"};s>0&&(e.bitrate=s),m.configure(e)}function T(e,r=!1){s=e,y=r,f()}let m=new VideoEncoder({output:e=>{let r;e.data?r=e.data:(r=new ArrayBuffer(e.byteLength),e.copyTo(r)),self.postMessage({type:a.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,width:l,height:d,data:r},[r])},error:e=>{self.postMessage({type:a.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case a.INIT:F(e.data);break;case a.FRAME:C(e.data.keyFrame);break;case a.SET_BITRATE:T(e.data.bitrate,e.data.useCbr);break}}};return P;})();
|
|
11
|
-
`,r=>{var a;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(a=r.data)==null?void 0:a.byteLength,width:r.width,height:r.height})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:p.screenFrameRate,useCongestionControl:this._useCongestionControl,maxBitrate:this._maxBitrate},[i])})}requestFrame(e=!1){this._sendToWorker(Se.FRAME,{keyFrame:e})}setBitrate(e,t){this._sendToWorker(Se.SET_BITRATE,{bitrate:e,useCbr:t})}isVP9(){return!0}destroy(){this._removeWorker(),c.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var Vn=1.2,ba=.8,Hn=2e3,Gn=8e3,dr=8e3,Wn=16e3,jn=4,Kn=2e3,fi=(i=>(i[i.NONE=0]="NONE",i[i.UP=1]="UP",i[i.DOWN=2]="DOWN",i))(fi||{}),Si=class{constructor(e,t,i,r){this._upPenalty=0;this._delayAvgShort=-1;this._delayAvgLong=-1;this._minDelay=Number.MAX_VALUE;this._maxDelay=0;this._largeDelayDuration=0;this._onCongestion=e,this._ccEnabled=r,this._minBitrate=t,this._maxBitrate=i,this._targetBitrate=this._maxBitrate,this._probing=!1;let a=Date.now();this._lastDown=0,this._lastUp=a,this._lastProbing=a,this._lastCheckDelay=0}checkDelay(e,t,i){let r=Date.now();if(this._calcDelay(t,r),this._delayAvgShort<=0||this._delayAvgLong<=0||!this._ccEnabled)return;let a=0,s=this._delayAvgShort-this._delayAvgLong,d=Math.round(Math.abs(s)*100/this._delayAvgLong),l=s>40&&d>30&&this._delayAvgShort>700,u=this._delayAvgShort>2e3;l||u?a=2:Math.abs(s)<40&&d<10&&this._delayAvgShort<2e3&&(a=1);let E=Math.round(this._targetBitrate/1e3),C=i;e%100==0&&c.debug(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${fi[a]} tr=${E} br=${i}`);let M=r-this._lastDown;if(a===2&&M>Hn){this._probing&&(this._upPenalty=Math.min(++this._upPenalty,jn),this._probing=!1);let q=ba*C*1e3;if(q>=this._targetBitrate&&(q=this._targetBitrate*ba),q=Math.max(q,this._minBitrate),q<this._targetBitrate){let De=Math.round(q/1e3),re=Math.round(this._upPenalty*dr/1e3);c.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${fi[a]}`),c.log(`#${e}: cc: DOWN delay=${t} bitrate=${C} target=${E} -> newBitrate=${De} penalty=${re}s`),this._onCongestion(q,!0),this._targetBitrate=q}this._lastDown=r}let O=r-this._lastUp,w=Gn+this._upPenalty*dr;if(a===1&&O>w&&M>w){let q=Math.min(this._targetBitrate*Vn,this._maxBitrate);if(q>this._targetBitrate){let De=Math.round(q/1e3),re=Math.round(this._targetBitrate/1e3),Ce=Math.round(this._upPenalty*dr/1e3);c.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${fi[a]}`),c.log(`#${e}: cc: UP bitrate=${C} target=${re} -> newBitrate=${De} penalty=${Ce}s`),this._onCongestion(q,!1),this._targetBitrate=q,this._probing=!0,this._lastProbing=r,this._lastUp=r}}let F=r-this._lastProbing;this._probing&&F>Wn&&(this._probing=!1);let de=r-this._lastDown;this._upPenalty>0&&de>3*w&&(c.log(`#${e}: cc: UP reset penalty: oldPenalty=${this._upPenalty}`),this._upPenalty=0)}_calcDelay(e,t){if(!(e<=0)){if(this._delayAvgShort===-1&&(this._delayAvgShort=e,this._delayAvgLong=e),this._delayAvgShort=Math.round((this._delayAvgShort*3+e)/4),this._delayAvgLong=Math.round((this._delayAvgLong*23+e)/24),e>0&&e<this._minDelay?this._minDelay=e:e>this._maxDelay&&(this._maxDelay=e),this._lastCheckDelay===0&&(this._lastCheckDelay=t),e>Kn){let i=t-this._lastCheckDelay;this._largeDelayDuration+=i}this._lastCheckDelay=t}}reconfigure(e,t){this._minBitrate=e,this._maxBitrate=t}getStat(){if(this._minDelay===Number.MAX_VALUE||this._maxDelay===0||this._delayAvgLong<=0)return null;let e={minDelay:this._minDelay,maxDelay:this._maxDelay,avgDelay:this._delayAvgLong,largeDelayDuration:this._largeDelayDuration};return this._minDelay=Number.MAX_VALUE,this._maxDelay=0,this._largeDelayDuration=0,e}};var vi=class{constructor(e){this._size=0;this._head=0;this._tail=0;this._maxSize=e,this._buffer=new Array(e)}add(e,t,i,r,a){this._tail===this._head&&this._size>0&&(this._head=++this._head%this._maxSize);let s=this._tail;return this._buffer[this._tail]={seq:e,ts:t,size:i,sent:Date.now(),start:r,end:a,ts2:-1,recv:-1},this._tail=++this._tail%this._maxSize,this._size++,s}update(e,t){let i=this.get(e);return i===null?null:(i.ts2=t,i.recv=Date.now(),i)}get(e){let t=this._head;for(let i=0;i<this._maxSize;i++){if(e===this._buffer[t].seq)return this._buffer[t];if(t=++t%this._maxSize,t===this._tail)break}return null}getServerBitrateK(e){let t=0,i=0,r=-1,a=-1,s=this._tail;for(let d=0;d<this._maxSize;d++){s>0?--s:s=this._maxSize-1;let l=this._buffer[s];if(l===null||(a===-1&&(a=l.ts2,i=0),a>=0&&(i+=l.size),r=l.ts2,a-r>=e)||s===this._head)break}if(r>=0&&a>=0){let d=a-r;t=Math.round(d>0?i*8/d:0)}return t}getCurrentDelay(){let e=this._tail;for(let t=0;t<this._maxSize;t++){e>0?--e:e=this._maxSize-1;let i=this._buffer[e];if(i===null)break;if(i.recv>=0&&i.sent>=0)return i.recv-i.sent;if(e===this._head)break}return 0}getMaxBandwidth(){let e=0,t=0,i=-1,r=-1,a=this._tail;for(let s=0;s<this._maxSize;s++){if(a>0?--a:a=this._maxSize-1,r===-1&&this._buffer[a].end&&!this._buffer[a].start&&(r=this._buffer[a].ts2,t=0),i===-1&&r>=0&&this._buffer[a].start&&!this._buffer[a].end&&(i=this._buffer[a].ts2),i>=0&&r>=0){let d=r-i;e=d>0?t*8/d:0;break}if(r>=0&&(t+=this._buffer[a].size),a===this._head)break}return Math.round(e)}};var $n=65536,qn=50,zn=400,Jn=1e6,Yn=3e4,Ei=0,At=class{constructor(e,t,i){this._destroyed=!1;this._needKeyframe=!0;this._frameNum=0;this._feedback=new vi(1024);this._lastSharingStat=Date.now();this._congestionControlEnabled=!1;c.debug("ScreenCaptureSender started"),this.DATA_SIZE=p.consumerScreenDataChannelPacketSize-_i,this._datachannel=t,this._signaling=i,this._congestionControlEnabled=p.screenShareCongestionControl,this._width=e.getSettings().width,this._height=e.getSettings().height;let{minBitrate:r,maxBitrate:a}=this._calcMinMaxBitrate(this._width,this._height),s=this._onCongestionCallback.bind(this);c.log(`ScreenCaptureSender: CongestionControl: enabled=${this._congestionControlEnabled} minBitrate=${Math.round(r/1e3)}k maxBitrate=${Math.round(a/1e3)}k`),this._congestionControl=new Si(s,r,a,this._congestionControlEnabled);let d=(l,u)=>{if(!this._destroyed){if(!l){c.warn("requestFrame failed, keyFrame: "+this._needKeyframe,u),this._needKeyframe=!0,this._requestFrame();return}(l.width!==this._width||l.height!==this._height)&&(this._width=l.width,this._height=l.height,this._onResize(this._width,this._height)),this._send(l).catch(E=>{c.warn("sendFrame failed",E),this._needKeyframe=!0}).finally(()=>{this._frameNum++,l.type==="key";let E=this._feedback.getCurrentDelay(),C=this._feedback.getServerBitrateK(2e3);E>0&&this._congestionControl.checkDelay(this._frameNum,E,C),this._requestFrame()}),this._sendSharingStat()}};Mt.isBrowserSupported()?this._encoder=new Mt(e,d,p.screenShareCongestionControl,a):this._encoder=new jt(e,d,p.screenShareCongestionControl,a),this._datachannel.onmessage=l=>{ya(l.data)&&(c.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0);let u=Pa(l.data);u!==null&&this._checkCcFeedback(u)},this._encoder.init().then(()=>this._requestFrame()).catch(l=>c.warn("ScreenCaptureSender init failed",l))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,a){let s=Ca(e,t,i,r,Ei,this._encoder.isVP9(),a);return Ei=(Ei+1)%$n,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return o(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let a=e.data.slice(t,t+this.DATA_SIZE),s=e.data.byteLength<=t+a.byteLength;this._feedback.add(Ei,e.timestamp,a.byteLength,!t,s);let d=this._wrapHeader(e.timestamp,!t,s,e.type==="key",a);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(d)}catch(l){c.warn("Error send data to DataChannel",l),r();return}s||v.setImmediate(()=>this._sendChunk(e,t+this.DATA_SIZE,i,r))}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),c.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return Mt.isBrowserSupported()||jt.isBrowserSupported()}_onCongestionCallback(e,t){this._encoder.setBitrate(e,t)}_onResize(e,t){let{minBitrate:i,maxBitrate:r}=this._calcMinMaxBitrate(e,t),a=Math.round(i/1e3),s=Math.round(r/1e3);c.log(`cc: resize to ${e}x${t}, minBitrate=${a} maxBitrate=${s}`),this._congestionControl.reconfigure(i,r)}_calcMinMaxBitrate(e,t){(e===void 0||e<640)&&(e=640),(t===void 0||t<360)&&(t=360);let i=e*t/256,r=Math.min(Jn,Math.round(i*qn)),a=Math.round(i*zn);return{minBitrate:r,maxBitrate:a}}_checkCcFeedback(e){this._feedback.update(e.seq,e.ts2)===null&&c.debug(`cc: update failed, seq=${e.seq}`)}_sendSharingStat(){let e=Date.now();if(e-this._lastSharingStat>Yn){let i=this._congestionControl.getStat();i!==null&&(c.debug(`cc: send stats: ${JSON.stringify(i)}`),this._signaling.reportSharingStat(i)),this._lastSharingStat=e}}};var ne=class{static get sessionKey(){return ne._sessionKey}static set sessionKey(e){ne._sessionKey=e}static get sessionSecretKey(){return ne._sessionSecretKey}static set sessionSecretKey(e){ne._sessionSecretKey=e}static get accessToken(){return ne._accessToken}static set accessToken(e){ne._accessToken=e}static isEmpty(){return!ne._sessionKey||!ne._sessionSecretKey}};var S=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(S._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(S._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("apiAuth")&&(ne.accessToken=e.apiAuth.accessToken,ne.sessionKey=e.apiAuth.sessionKey,ne.sessionSecretKey=e.apiAuth.sessionSecretKey),e.hasOwnProperty("api")&&(Object.assign(S._params.api,e.api),delete e.api),Object.assign(S._params,v.objectFilterOutValues(e,void 0))}static get(e){return S._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.6.3-dev.bc23365.0"}static get debug(){return undefined}static get protocolVersion(){return S._params.joinFromMultipleDevices?6:5}static get platform(){return S._params.platform}static set platform(e){S._params.platform=e}static get clientType(){return S._params.clientType}static set clientType(e){S._params.clientType=e}static get externalUserType(){return S._params.externalUserType}static set externalUserType(e){S._params.externalUserType=e}static get device(){return S._params.device}static get apiKey(){return S._params.apiKey}static get apiEnv(){return S._params.apiEnv}static get apiEndpoint(){switch(S.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return S._params.apiEnv}}static get authToken(){return S._params.authToken}static set authToken(e){S._params.authToken=e}static get anonymToken(){return S._params.anonymToken}static set anonymToken(e){S._params.anonymToken=e}static get domain(){return S._params.domain}static get externalDomain(){return S._params.externalDomain}static get iceServers(){return S._params.iceServers}static set iceServers(e){S._params.iceServers=e}static get wssBase(){return S._params.wssBase}static set wssBase(e){S._params.wssBase=e}static get wssToken(){return S._params.wssToken}static set wssToken(e){S._params.wssToken=e}static get signalingReconnectDelay(){return S._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return S._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return S._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return S._params.waitConnectionDelay}static get waitResponseDelay(){return S._params.waitResponseDelay}static get waitMessageDelay(){return S._params.waitMessageDelay}static get waitAnotherTabDelay(){return S._params.waitAnotherTabDelay}static get debugLog(){return S._params.debugLog}static get forceRelayPolicy(){return S._params.forceRelayPolicy}static set forceRelayPolicy(e){S._params.forceRelayPolicy=e}static get videoMinWidth(){return S._params.videoMinWidth}static get videoMaxWidth(){return S._params.videoMaxWidth}static set videoMaxWidth(e){S._params.videoMaxWidth=e}static get videoMinHeight(){return S._params.videoMinHeight}static get videoMaxHeight(){return S._params.videoMaxHeight}static set videoMaxHeight(e){S._params.videoMaxHeight=e}static get videoAspectRatio(){return S._params.videoAspectRatio}static get videoFrameRate(){return S._params.videoFrameRate}static get videoFacingMode(){return S._params.videoFacingMode}static get screenFrameRate(){return S._params.screenFrameRate}static get videoEffects(){return S._params.videoEffects}static set videoEffects(e){S._params.videoEffects=e}static get videoEffectMaxWidth(){return S._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){S._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return S._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){S._params.videoEffectMaxHeight=e}static get voiceParams(){return S._params.voiceParams}static get specListenerParams(){return S._params.specListenerParams}static get iceRestartWaitTime(){return S._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return S._params.transportConnectionWaitTime}static get statisticsInterval(){return S._params.statisticsInterval}static set statisticsInterval(e){S._params.statisticsInterval=e}static get networkStatisticsInterval(){return S._params.networkStatisticsInterval}static get perfStatReportEnabled(){return S._params.perfStatReportEnabled}static get callStatReportEnabled(){return S._params.callStatReportEnabled}static get producerNotificationDataChannel(){return S._params.producerNotificationDataChannel}static get producerCommandDataChannel(){return S._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return S._params.consumerScreenDataChannel&&At.isBrowserSupported()}static get producerScreenDataChannel(){return S._params.producerScreenDataChannel&&S.producerNotificationDataChannel&&bt.isBrowserSupported()}static get asrDataChannel(){return S._params.asrDataChannel&&S.producerNotificationDataChannel}static get consumerScreenDataChannelPacketSize(){return S._params.consumerScreenDataChannelPacketSize}static get screenShareWebmBuilder(){return S._params.screenShareWebmBuilder}static get noiseSuppression(){return S._params.noiseSuppression}static set noiseSuppression(e){S._params.noiseSuppression=e}static get preferH264(){return S._params.preferH264}static get preferVP9(){return S._params.preferVP9}static get audioNack(){return S._params.audioNack}static get consumerScreenTrack(){return S._params.consumerScreenTrack&&S.consumerScreenDataChannel}static get producerScreenTrack(){return S._params.producerScreenTrack}static get movieShare(){return S._params.movieShare&&S.videoTracksCount>0}static get videoTracksCount(){return S.producerNotificationDataChannel?S._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return S._params.breakVideoPayloadTypes}static get filteredMessages(){return S._params.filteredMessages}static get useParticipantListChunk(){return S._params.useParticipantListChunk&&S._params.videoTracksCount>0}static get useRooms(){return S._params.useRooms}static get participantListChunkInitIndex(){var e;return(e=S._params.participantListChunkInitIndex)!=null?e:0}static get participantListChunkInitCount(){var e;return(e=S._params.participantListChunkInitCount)!=null?e:null}static get serverAudioRed(){return S._params.serverAudioRed&&y.canPreferRed()}static get p2pAudioRed(){return S._params.p2pAudioRed&&y.canPreferRed()}static get h264spsPpsIdrInKeyframe(){return S._params.h264spsPpsIdrInKeyframe}static get batchParticipantsOnStart(){return S._params.batchParticipantsOnStart}static get filterObservers(){return S._params.filterObservers}static get muteMode(){return S._params.muteMode}static get preserveAudioTracks(){return S._params.preserveAudioTracks}static get audioShareCapabilityEnabled(){return y.isAudioShareSupported()&&S._params.audioShareCapabilityEnabled}static get screenShareCongestionControl(){return S._params.screenShareCongestionControl}static get api(){return S._params.api}},p=S;p._params={platform:"WEB",clientType:"PORTAL",externalUserType:"",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",externalDomain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,asrDataChannel:!1,consumerScreenDataChannelPacketSize:16*1024,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,useParticipantListChunk:!1,useRooms:!1,participantListChunkInitIndex:0,participantListChunkInitCount:null,serverAudioRed:!1,p2pAudioRed:!1,h264spsPpsIdrInKeyframe:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1,audioShareCapabilityEnabled:!1,screenShareCongestionControl:!1,api:{userIdsByOkBatchedTimeout:1e3}};var J=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))(J||{});function W(n,...e){let t=p.get(n);t&&setTimeout(t,0,...e)}function ue(n,e,...t){if(p.filterObservers){if(Array.isArray(e)){if(e=e.filter(i=>!i.observer),!e.length)return}else if(e.observer)return}W(n,e,...t)}function ye(n){return Object.assign({},n)}function dt(n){return n.slice()}var lr;(tc=>{function n(h,b){W("onLocalStream",h,ye(b))}tc.onLocalStream=n;function e(h,b){W("onScreenStream",h,ye(b))}tc.onScreenStream=e;function t(h,b){W("onLocalStreamUpdate",ye(h),b)}tc.onLocalStreamUpdate=t;function i(h){W("onLocalStatus",h)}tc.onLocalStatus=i;function r(h,b){ue("onRemoteStream",h,b)}tc.onRemoteStream=r;function a(h,b){ue("onRemoteLive",h,b)}tc.onRemoteLive=a;function s(h,b){ue("onLocalLive",h,b)}tc.onLocalLive=s;function d(h,b){ue("onRemoteLiveUpdate",h,b)}tc.onRemoteLiveUpdate=d;function l(h,b){ue("onLocalLiveUpdate",h,b)}tc.onLocalLiveUpdate=l;function u(h,b){ue("onRemoteScreenStream",h,b)}tc.onRemoteScreenStream=u;function E(h,b,ee,Ye,xt){ue("onConversation",h,ye(b),ye(ee),Ye,xt)}tc.onConversation=E;function C(h){h&&W("onConversationParticipantListChunk",h)}tc.onConversationParticipantListChunk=C;function M(h,b,ee){ue("onRemoteMediaSettings",h,ye(b),ee)}tc.onRemoteMediaSettings=M;function O(h,b){ue("onLocalMediaSettings",h,ye(b))}tc.onLocalMediaSettings=O;function w(h,b){ue("onRemoteSharedMovieInfo",h,ye(b))}tc.onRemoteSharedMovieInfo=w;function F(h,b){ue("onRemoteSharedMovieStoppedInfo",h,ye(b))}tc.onRemoteSharedMovieStoppedInfo=F;function de(h,b){ue("onLocalSharedMovieInfo",h,ye(b))}tc.onLocalSharedMovieInfo=de;function q(h,b){ue("onLocalSharedMovieStoppedInfo",h,ye(b))}tc.onLocalSharedMovieStoppedInfo=q;function De(h,b){ue("onParticipantAdded",h,b)}tc.onParticipantAdded=De;function re(h,b){ue("onParticipantJoined",h,b)}tc.onParticipantJoined=re;function Ce(h,b,ee){ue("onRemoteParticipantState",h,ye(b),ee)}tc.onRemoteParticipantState=Ce;function be(h,b,ee=null){ue("onRemoteStatus",h,b,ee)}tc.onRemoteStatus=be;function at(h,b,ee=null){ue("onParticipantStatus",h,b,ee)}tc.onParticipantStatus=at;function ti(){W("onPermissionsRequested")}tc.onPermissionsRequested=ti;function Q(h){W("onPermissionsError",h)}tc.onPermissionsError=Q;function br(h,b){ue("onRemoteRemoved",h,b)}tc.onRemoteRemoved=br;function Oi(h,b,ee){W("onCallState",h,b,ye(ee))}tc.onCallState=Oi;function wi(h,b){W("onDeviceSwitched",h,b)}tc.onDeviceSwitched=wi;function Y(h,b,ee,Ye=!1,xt=!1,Ni=null,Ui=null,sn,Ar,on=null){let cn=Ar?dt(Ar):void 0;W("onMuteStates",ye(h),dt(b),dt(ee),Ye,xt,Ni,Ui,sn,cn,on)}tc.onMuteStates=Y;function xi(h,b){ue("onRolesChanged",h,dt(b))}tc.onRolesChanged=xi;function Mr(h){W("onLocalRolesChanged",dt(h))}tc.onLocalRolesChanged=Mr;function Li(h,b,ee){ue("onPinnedParticipant",h,b,ee)}tc.onPinnedParticipant=Li;function _(h){W("onLocalPin",h)}tc.onLocalPin=_;function m(h){W("onOptionsChanged",dt(h))}tc.onOptionsChanged=m;function I(){W("onCallAccepted")}tc.onCallAccepted=I;function A(){W("onRateNeeded")}tc.onRateNeeded=A;function P(h){ue("onSpeakerChanged",h)}tc.onSpeakerChanged=P;function j(h){W("onVolumesDetected",dt(h))}tc.onVolumesDetected=j;function Z(h,b){W("onLocalVolume",h,b)}tc.onLocalVolume=Z;function Ee(h,b){W("onJoinStatus",h,b)}tc.onJoinStatus=Ee;function ke(h,b){W("onHangup",h,b)}tc.onHangup=ke;function Ge(h){W("onMultipartyChatCreated",ye(h))}tc.onMultipartyChatCreated=Ge;function ze(){W("onDeviceChange")}tc.onDeviceChange=ze;function xe(h){W("onFingerprintChange",h)}tc.onFingerprintChange=xe;function Le(){W("onTokenExpired")}tc.onTokenExpired=Le;function Ne(h,b,ee=!1){W("onChatMessage",h,b,ee)}tc.onChatMessage=Ne;function We(h,b,ee=!1){W("onCustomData",h,b,ee)}tc.onCustomData=We;function L(h,b,ee,Ye,xt,Ni,Ui=null){W("onRecordStarted",h,b,ee,Ye,xt,Ni,Ui)}tc.onRecordStarted=L;function U(h=null){W("onRecordStopped",h)}tc.onRecordStopped=U;function _t(h){W("onLocalNetworkStatusChanged",h)}tc.onLocalNetworkStatusChanged=_t;function z(h){W("onNetworkStatusChanged",h)}tc.onNetworkStatusChanged=z;function _e(h,...b){W("onDebugMessage",h,...b)}tc.onDebugMessage=_e;function Ie(h,b){let ee=Object.assign({},h,{memory:b});W("onStatistics",ee)}tc.onStatistics=Ie;function ie(){W("onAutoplayError")}tc.onAutoplayError=ie;function X(h,b,ee){W("onChatRoomUpdated",h,b,ee)}tc.onChatRoomUpdated=X;function ce(h){W("onRemoteMixedAudioStream",h)}tc.onRemoteMixedAudioStream=ce;function Je(h){W("onJoinLinkChanged",h)}tc.onJoinLinkChanged=Je;function Ko(h){W("onRoomsUpdated",h)}tc.onRoomsUpdated=Ko;function $o(h,b,ee,Ye){W("onRoomUpdated",h,b,ee,Ye)}tc.onRoomUpdated=$o;function qo(h){W("onRoomParticipantsUpdated",h)}tc.onRoomParticipantsUpdated=qo;function zo(h){W("onRoomSwitched",h)}tc.onRoomSwitched=zo;function Jo(h){W("onRoomStart",h)}tc.onRoomStart=Jo;function Yo(h,b=null){W("onFeedback",h,b)}tc.onFeedback=Yo;function Qo(h){W("onFeaturesPerRoleChanged",h)}tc.onFeaturesPerRoleChanged=Qo;function Xo(h,b){W("onAsrStarted",h,b)}tc.onAsrStarted=Xo;function Zo(){W("onAsrStopped")}tc.onAsrStopped=Zo;function ec(h,b,ee,Ye){W("onAsrTranscription",h,b,ee,Ye)}tc.onAsrTranscription=ec})(lr||(lr={}));var g=lr;var pr=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(pr||{}),ur;(re=>{let n="📞",e=(Ce,...be)=>{g.onDebugMessage(Ce,...be)},t=!1,i=(Ce,be)=>(...at)=>{Ce(...at),da(be,at)},r=console.debug.bind(console,n),a=console.log.bind(console,n),s=console.warn.bind(console,n),d=console.error.bind(console,n),l=e.bind(null,"DEBUG"),u=e.bind(null,"LOG"),E=e.bind(null,"WARN"),C=e.bind(null,"ERROR");re.debug=l,re.log=u,re.warn=E,re.error=C;function de(){return t}re.enabled=de;function q(Ce){t=Ce,p.debugLog&&Gi(),Ce?(re.debug=p.debugLog?i(r,"DEBUG"):r,re.log=p.debugLog?i(a,"LOG"):a,re.warn=p.debugLog?i(s,"WARN"):s,re.error=p.debugLog?i(d,"ERROR"):d):(re.debug=p.debugLog?i(l,"DEBUG"):l,re.log=p.debugLog?i(u,"LOG"):u,re.warn=p.debugLog?i(E,"WARN"):E,re.error=p.debugLog?i(C,"ERROR"):C)}re.toggle=q;function De(Ce,...be){switch(Ce){case"DEBUG":re.debug(...be);break;case"LOG":re.log(...be);break;case"WARN":re.warn(...be);break;case"ERROR":re.error(...be);break}}re.send=De})(ur||(ur={}));var c=ur;var lt=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(lt||{}),ve;(d=>{function n(l){return l.length?typeof l[0]=="object"?l:l.map(u=>e(u)):[]}d.fromIds=n;function e(l,u="USER"){return{id:l,type:u}}d.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}d.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}d.toString=i;function r(l,u="USER"){return i(e(l,u))}d.fromIdToString=r;function a(l){try{return JSON.parse(l)}catch(u){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}d.fromString=a;function s(l,u){return l.id===u.id&&l.type===u.type}d.compare=s})(ve||(ve={}));var fe;(r=>{function n(a,s="USER",d=0){return{id:a,type:s,deviceIdx:d}}r.fromId=n;function e(a){return`{"id":"${a.id}","type":"${a.type}","deviceIdx":"${a.deviceIdx}"}`}r.toString=e;function t(a,s){return Object.assign({deviceIdx:s},ve.fromSignaling(a))}r.fromSignaling=t;function i(a){return a&&typeof a=="object"?a.deviceIdx:0}r.getDeviceIdx=i})(fe||(fe={}));var Qn="kf";function Kt(n){return n.stopStream}function mr(n){return n.keyFrameRequested}function Ma(n){if(Kt(n))return"ss";if(mr(n))return Qn;let e="";return n.priority!==void 0&&(e+="p="+n.priority),n.width!==void 0&&n.height!==void 0&&(e!==""&&(e+=":"),e+="sz="+Math.round(n.width)+"x"+Math.round(n.height)),n.fit!==void 0&&(e!==""&&(e+=":"),e+="fit="+n.fit),e}var Pe=(a=>(a.CAMERA="CAMERA",a.SCREEN="SCREEN",a.STREAM="STREAM",a.MOVIE="MOVIE",a.AUDIOSHARE="AUDIOSHARE",a))(Pe||{}),Aa="s",Da="m";function qe(n){return n.participantId+(n.mediaType?Ct+Aa+n.mediaType:"")+(n.streamName?Ct+Da+n.streamName:"")}function $t(n){let e=n.split(Ct),t=e.shift();if(!t)throw new Error("Illegal stream description: "+n);let i=null,r,a=0;for(let d of e)switch(d.charAt(0)){case Aa:i=Xn(d.slice(1));break;case Da:r=d.slice(1);break;case si:a=Number.parseInt(d.slice(1),10);break;default:throw new Error("Unexpected parameter type "+d.charAt(0)+" in stream description "+n)}return{participantId:v.compose(t,a),mediaType:i,streamName:r}}function Xn(n){for(let e of Object.keys(Pe))if(e===n)return Pe[e];return null}function hr(n,e){return n===null||e===null?n===null&&e===null:!(n.maxDimension!==e.maxDimension||n.maxBitrateK!==e.maxBitrateK||n.maxFramerate!==e.maxFramerate||n.degradationPreference!==e.degradationPreference)}function Ii(n,e){return!(!hr(n.camera,e.camera)||!hr(n.screenSharing,e.screenSharing))}function _r(n,e){return{camera:Object.assign({},n.camera,e.camera),screenSharing:Object.assign({},n.screenSharing,e.screenSharing)}}function ka(n){try{return btoa(JSON.stringify(n))}catch(e){c.warn("WaitingParticipant: failed convert to string",n,e)}return null}function Oa(n){try{return JSON.parse(atob(n))}catch(e){c.warn("WaitingParticipant: failed convert from string",n,e)}return null}var Dt=(n,e)=>v.objectReduce(n,(t,i,r)=>(i===e&&t.push(r),t),[]);var qt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,f.log(T.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,f.log(T.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(c.log("Failed to fix RV"),f.log(T.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),f.log(T.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,c.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===pe.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Ti=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(p.muteMode||!((s=this._output)==null?void 0:s.audioTrack))return;let e=y.browserName()!=="Safari"||y.isMobile(),t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{c.warn("Error on play audio"),g.onAutoplayError()},r=d=>{t.srcObject=new MediaStream([d]),t.load();let l=t.play();l&&l.catch(i)},a=()=>{var l;c.debug("Recover audio playback");let d=(l=this._output)==null?void 0:l.audioTrack;d?r(d):c.warn("Broken audio track")};t.onpause=a,t.onstalled=a,t.onerror=a,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return o(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=y.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw f.log(T.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var Zn=90,es=3,Ci=class extends ae{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),g.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>Zn?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=es)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var ts=44100,zt=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=y.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=ts/this._fftBins.length,t=Math.ceil(p.voiceParams.minFreq/e),i=Math.floor(p.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((a,s)=>a+s,0)/e.length/255,r=this._lastSmoothedLevel*p.voiceParams.smoothing+i*(1-p.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var Ri=class extends ae{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&g.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,p.voiceParams.interval)};this._interval=window.setTimeout(t,p.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,Me.SOURCE_CHANGED,r=>{r.kind===pe.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new zt("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 wa="videochat-epi",is=5e3,rs=3e4,pt=class extends ae{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,V.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(wa)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return o(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&p.perfStatReportEnabled&&this._previousTimestamp+is<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),p.callStatReportEnabled&&this._previousCallStatReportTimestamp+rs<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return o(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(wa,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,a)=>(a.kind==="video"?(a.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+a.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+a.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=a.framesDropped,r.nack_sent+=a.nackCount,r.pli_sent+=a.pliCount,r.fir_sent+=a.firCount):(a.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+a.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+a.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=a.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=a.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=a.removedSamplesForAcceleration,r.concealed_audio_samples+=a.concealedSamples,r.silent_concealed_audio_samples+=a.silentConcealedSamples,r.audio_concealment_events+=a.concealmentEvents),r),t),e.outbound.rtps.reduce((r,a)=>(a.kind==="video"&&(r.nack_received+=a.nackCount,r.pli_received+=a.pliCount,r.fir_received+=a.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,a=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,d=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,l=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,u=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=a/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=d/r*1e3,i.concealed_silent_audio_samples=l/r*1e3,i.concealment_audio_avg_size=d/u,i.total_audio_energy=t.total_audio_energy}f.logCustom("callStat",i),c.log("Sent call stats",i),this._previousCallStatReport=t}};var as=1e3;function he(n,e,t=0){return e in n&&n[e]?n[e]:t}function xa(...n){return e=>{for(let t of n)if(t(e))return!0;return!1}}function it(n,e){return t=>t[n]===e}function ns(n){return(e,t)=>e[n]-t[n]}function yi(n,e){return e.reduce((t,i)=>(t[i[n]]=i,t),{})}function ss(n){let e={},t=[];for(let i of n)e[i.id]||(e[i.id]=!0,t.push(i));return t}function os(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function gr(n){return Object.keys(n).filter(e=>n[e]!==void 0).map(e=>[e,n[e]]).reduce((e,t)=>(e[t[0]]=os(t[1])?gr(t[1]):t[1],e),{})}function cs(n){let e=[];for(let t of n)t.forEach(i=>e.push(i));return e}function ds(n){return o(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...n.getReceivers().map(t=>t.getStats())),e.push(...n.getSenders().map(t=>t.getStats()))):e.push(n.getStats()),Promise.all(e).then(cs).then(ss)})}function ls(n){let e=n.filter(it("type","candidate-pair")).sort(ns("priority")).find(xa(it("nominated",!0),it("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=n.find(it("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=n.find(it("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}})),gr(t)}function ps(n,e){let t=yi("id",n),i=n.filter(xa(it("type","inbound-rtp"),it("type","outbound-rtp")));y.browserName()==="Firefox"&&(i=Object.values(i.reduce((a,s)=>{if(!a[s.ssrc])a[s.ssrc]=s;else{let d=Object.assign({},a[s.ssrc],s),l=a[s.ssrc].isRemote?s:a[s.ssrc];d.id=l.id,d.type=l.type,delete d.isRemote,delete d.remoteId,a[d.ssrc]=d}return a},{})));let r={};if(y.browserName()==="Safari"){let a=n.filter(it("type","track"));r=yi("trackIdentifier",a)}return i.map(a=>{let s=Number(a.ssrc),d=a.mediaType||a.kind,l=a.trackId,u=a.type,E=a.codecId;if(y.browserName()==="Safari"){let M=/^.+_([\d]+)$/.exec(a.id);if(M&&(s=parseInt(M[1],10)),d=a.id.indexOf("Audio")>0?"audio":"video",e[s]){let O=d+"-"+e[s];r[O]&&(l=r[O].id)}}if(!u||!s||!d)return null;let C={ssrc:s,type:u,kind:d,bytesReceived:he(a,"bytesReceived"),bytesSent:he(a,"bytesSent"),jitter:he(a,"jitter"),packetsLost:he(a,"packetsLost"),packetsReceived:he(a,"packetsReceived"),packetsSent:he(a,"packetsSent"),fractionLost:he(a,"fractionLost"),pliCount:he(a,"pliCount"),firCount:he(a,"firCount"),nackCount:he(a,"nackCount"),userId:e[s]};if(d==="video"){let M=he(a,"framesDecoded"),O=he(a,"totalInterFrameDelay"),w=he(a,"totalSquaredInterFrameDelay");C.interframeDelayVariance=(w-O*O/M)/M}if(d==="audio"&&(C.totalSamplesReceived=he(a,"totalSamplesReceived"),C.concealedSamples=he(a,"concealedSamples"),C.insertedSamplesForDeceleration=he(a,"insertedSamplesForDeceleration"),C.removedSamplesForAcceleration=he(a,"removedSamplesForAcceleration"),C.silentConcealedSamples=he(a,"silentConcealedSamples"),C.concealmentEvents=he(a,"concealmentEvents"),C.totalAudioEnergy=he(a,"totalAudioEnergy")),E&&t[E]){let M=t[E];C.clockRate=M.clockRate,C.mimeType=M.mimeType}if(l&&t[l]){let M=t[l];C.frameHeight=M.frameHeight,C.frameWidth=M.frameWidth,C.framesDecoded=M.framesDecoded,C.framesReceived=M.framesReceived,C.framesDropped=M.framesDropped}return gr(C)}).filter(a=>!!a)}function us(n,e){if(!e||!e.rtps||!n.rtps)return n;let t=yi("ssrc",n.rtps),i=yi("ssrc",e.rtps),r=(n.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(a=>{let s=t[a],d=i[a];if(!(!s||!d)){if(s.bytesReceived&&s.bytesReceived>d.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-d.bytesReceived)/r)),s.bytesSent&&s.bytesSent>d.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-d.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>d.packetsReceived||s.packetsLost>d.packetsLost){let l=s.packetsLost-d.packetsLost,u=s.packetsReceived-d.packetsReceived;s.packetLoss=parseFloat((100*l/(l+u)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&d.framesDropped&&s.framesDropped>d.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-d.framesDropped)/r).toFixed(0)))}}),n}function Jt(i,r){return o(this,arguments,function*(n,e,t={}){let a=yield ds(n),s={timestamp:Date.now(),transport:ls(a),rtps:ps(a,t)};return e?us(s,e):(yield v.delay(as),Jt(n,s,t))})}var Pi=.8,ut=class extends ae{constructor(e,t,i,r,a){super();this._remoteSDP={};this._remoteCandidates={};this._state=H.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=a,this._perfStatReporter=new pt(this,i,!0),this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Me.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Me.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:p.iceServers,iceTransportPolicy:p.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,p.p2pAudioRed),this._applySettings()}catch(s){f.log(T.ERROR,"addTrack-direct"),c.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===H.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==H.IDLE&&e!==H.CLOSED&&e!==H.FAILED&&this._startStatInterval()}open(e=null){return o(this,null,function*(){if(this._isOpen){c.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(c.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,p.p2pAudioRed),this._applySettings()}catch(i){f.log(T.ERROR,"addTrack-direct"),c.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(H.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={}})}updateSettings(e){Ii(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(V.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(c.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(H.FAILED)):(c.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(H.CLOSED)),this._triggerEvent(V.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(V.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,a;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=((a=e.data.sdk)==null?void 0:a.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=v.getPeerIdString(e.peerId);v.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){c.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw f.log(T.ERROR,"addIceCandidate-direct"),c.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else c.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return o(this,null,function*(){if(!this._remoteCandidates[e]){c.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){c.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw f.log(T.ERROR,"setRemoteDescription-direct"),c.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){c.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(V.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(V.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return o(this,null,function*(){e.candidate&&this._signaling.ready&&(c.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(c.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>o(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(c.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===H.IDLE||e===H.OPENED?this._setState(H.CONNECTING):this._setState(H.RECONNECTING);break}}_onConnectionStateChange(){switch(c.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),f.log(T.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(H.CONNECTED),this._stopReconnection(),v.getPeerConnectionHostInfo(this._pc).then(e=>{e&&f.log(T.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(H.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(c.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},p.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(c.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(oe.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(f.log(T.ICE_RESTART),c.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):c.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,c.error("Ice restart failed",{participantId:this._participantId}),f.log(T.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},p.iceRestartWaitTime)}_createOffer(e){return o(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return c.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw c.error("Unable to create offer",i,{participantId:this._participantId}),f.log(T.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=ut._patchDescription(i),c.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw c.error("Unable to set local description",i,{participantId:this._participantId}),f.log(T.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return o(this,null,function*(){return c.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw c.error("Unable to create answer",e,{participantId:this._participantId}),f.log(T.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=ut._patchDescription(e),c.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw c.error("Unable to set local description",e,{participantId:this._participantId}),f.log(T.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=v.patchLocalSDP(e.sdp,p.preferH264&&y.canPreferH264(),y.isBrokenH264(),p.preferVP9,p.h264spsPpsIdrInKeyframe,t&&p.audioNack,p.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&t.track.contentHint===e.contentHint&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{c.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),f.log(T.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Jt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:oe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:oe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(V.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,p.statisticsInterval)})};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=q=>q.rtt<=this._networkLimits.goodNet.rtt&&q.loss<=this._networkLimits.goodNet.loss,i=q=>q.rtt>=this._networkLimits.badNet.rtt||q.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,a=e.inbound.rtps.reduce((q,De)=>Math.max(q,De.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-Pi)+r*Pi,loss:this._lastNetworkStat.loss*(1-Pi)+a*Pi},d=i(s),l=t(s),u=i(this._remoteNetworkStat),E=t(this._remoteNetworkStat),C=i(this._lastNetworkStat),M=t(this._lastNetworkStat),F=d||u?.2:l&&E?1:0,de=Date.now();if((C!==d||M!==l||de-this._lastNetworkStat.date>p.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(q=>{c.warn("Unable to send [bad-net]",q)})),F){let q={};q[this._participantId]=q[""]=F,this._triggerEvent(V.NETWORK_STATUS,q)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=v.sdpFingerprint(e);if(t===null){c.warn("Fingerprint calculation is unsupported");return}this._fingerprint===null?this._fingerprint=t:(g.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=v.applySettings(this._pc,e,this._prevConsumerSettings))}};var La=(a=>(a.producerNotification="producerNotification",a.producerCommand="producerCommand",a.consumerScreenShare="consumerScreenShare",a.producerScreenShare="producerScreenShare",a.asr="asr",a))(La||{}),kt=La;var ms=16,Yt=class{constructor(e,t,i){c.debug("AsrReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._asrCallback=i,this._textDecoder=new TextDecoder,this._datachannel.onmessage=r=>this._onDataChannelMessage(r.data)}static parse(e){let t=new DataView(e),i=t.getUint8(0),r=t.getUint8(1);if(r!==0)throw new Error(`Unsupported message type. Message type: ${r}`);let a=t.getUint16(2),s=t.getUint32(4),d=t.getUint32(8),l=t.getUint32(12);if(i!==1)throw new Error(`Unexpected protocol version. Got ${i}, expected 1`);return{sequence:a,ssrc:s,timestamp:d,duration:l,data:e.slice(ms)}}_onDataChannelMessage(e){var a,s;let t=Yt.parse(e),i=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){c.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}let r={participantId:i,text:this._textDecoder.decode(t.data),timestamp:t.timestamp,duration:t.duration};this._asrCallback(r)}destroy(){this._datachannel.onmessage=null}};var rt=nt(require("messagepack"));var fr=class{constructor(){this.streamDescriptionByCompactId=new Map;this.compactIdByStreamDescription=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}getCompactId(e){return this.compactIdByStreamDescription.get(e)}handleMessage(e){var a,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let d=(0,rt.decode)(r);return Object.entries(d).forEach(([w,F])=>{let de=$t(w);this.streamDescriptionByCompactId.set(F,de),this.compactIdByStreamDescription.set(w,F)}),null;case 2:case 4:let l=(0,rt.decode)(r),u=[];for(let w of l){let F=this.getStreamDescription(w);F&&u.push(F.participantId)}return i===2?{type:"notification",notification:k.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:k.STALLED_ACTIVITY,stalledParticipants:u};case 3:let E=(0,rt.decode)(r);return{type:"notification",notification:k.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(E))==null?void 0:a.participantId};case 5:let C=(0,rt.decode)(r);return{type:"notification",notification:k.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:C[0],maxDimension:C[1]}};case 6:let M=(0,rt.decode)(r),O={};for(let[w,F]of Object.entries(M)){let de=(s=this.getStreamDescription(Number(w)))==null?void 0:s.participantId;de&&(O[de]=F/100)}return{type:"notification",notification:k.NETWORK_STATUS,statuses:O};case 7:return this._createParticipantSourcesUpdateNotification(r);case 8:{let F=(0,rt.decode)(r).map(de=>{var Q;let[q,De,re,Ce,be,at,ti]=de;return{participantId:(Q=this.getStreamDescription(q))==null?void 0:Q.participantId,gain:De,pause:re,offset:Ce,mute:be,liveStatus:at,startTimeMs:ti}});return{type:"notification",notification:k.MOVIE_UPDATE_NOTIFICATION,data:F}}default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,rt.decode)(e),i=[];for(let[r,a]of Object.entries(t)){let s=a[0],d=a[1],l=a[2],u;if(s!==null){if(u=this.getStreamDescription(s),!u){c.error(`could not uncompress participant ID ${s}`);continue}}else u=null;if(l===null){c.error("unexpected null sequenceNumber",r,a);continue}let E=Be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,C=d?d>>>0:null;i.push({participantStreamDescription:u,streamId:E,rtpTimestamp:C,sequenceNumber:l})}return{type:"notification",notification:k.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var hs=90,_s=4294967295,Ve=class extends ae{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._asr=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=H.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._asrTrack=null;this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._newAudioShareTrack=null;this._signaling=e,this._mediaSource=t,this._newAudioShareTrack=t.getAudioShareTrack(),this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Me.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Me.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,Me.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new pt(this,e),this._serverSettings=i,c.debug("ServerTransport: Created")}getState(){return this._state||H.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==H.IDLE&&e!==H.CLOSED&&e!==H.FAILED&&this._startStatInterval()}open(e=!1){if(this._isOpen){c.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(c.error("ServerTransport: Closed",e),this._setState(H.FAILED)):(c.debug("ServerTransport: Closed"),this._setState(H.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Ii(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeAsrTrack(),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,Ve._closeDataChannel(this._producerNotification),Ve._closeDataChannel(this._producerCommand),Ve._closeDataChannel(this._producerScreen),Ve._closeDataChannel(this._consumerScreen),Ve._closeDataChannel(this._asr),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(V.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let a=r.readyState;a==="open"?(c.debug(`[${t}] data channel opened`),r.onerror=s=>{c.error(`[${t}] data channel error`,s)},i(r)):c.error(`[${t}] data channel open failed, state [${a}]`)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection"),this._pc=new RTCPeerConnection({},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=v.throttle(t=>{this._pc&&this._onConnectionStateChange(this._pc,t)},500),this._pc.onsignalingstatechange=Ve._onSignalingStateChange.bind(this,this._pc),this._participantIdRegistry=new fr,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),p.producerNotificationDataChannel&&this._createDataChannel(this._pc,kt.producerNotification,t=>{this._producerNotification=t,this._producerNotification.binaryType="arraybuffer",this._signaling.setProducerNotificationDataChannel(t)}),p.producerCommandDataChannel&&(this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,kt.producerCommand,t=>{this._producerCommand=t,this._signaling.setProducerCommandDataChannel(t)})),p.producerScreenDataChannel&&this._createDataChannel(this._pc,kt.producerScreenShare,t=>{this._producerScreen=t,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()}),p.asrDataChannel&&this._createDataChannel(this._pc,kt.asr,t=>{this._asr=t,this._asr.binaryType="arraybuffer",this._removeAsrTrack(),this._asrTrack=new Yt(t,this._participantIdRegistry,i=>{this._onAsrTranscription(i)}),this._signaling.setAsrDataChannel(t)});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,p.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(t){c.error("ServerTransport: Unable to add media source tracks",t),f.log(T.ERROR,"addTrack-single"),this.close(t);return}p.consumerScreenDataChannel&&this._createDataChannel(this._pc,kt.consumerScreenShare,t=>{this._consumerScreen=t,this._consumerScreen.binaryType="arraybuffer";let i=this._mediaSource.getScreenTrack();i&&this._createCaptureSender(i)}),e||this._allocateConsumer(),this._setState(H.OPENED),this._startStatInterval(),this._startSettingsInterval()}_removeAsrTrack(){var e;(e=this._asrTrack)==null||e.destroy(),this._asrTrack=null}_reconnect(){this.getState()!==H.OPENED&&(this._setState(H.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(V.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(V.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(V.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(V.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
|
|
12
|
-
`).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!p.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new At(e,this._consumerScreen,this._signaling))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!p.producerScreenDataChannel||!this._producerScreen||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new bt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(V.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(V.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!p.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==pe.video)return;let r=!this._disabledSenders.has(i),a=e.maxDimension!==0;if(r&&!a){c.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(y.getBlackMediaTrack()).catch(d=>{c.error("Could not disable video upload",d)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&a&&s){c.log("Enabling video upload"),this._disabledSenders.delete(i);let d=i.track;d.enabled=s.enabled,i.replaceTrack(s).then(()=>d.stop()).catch(l=>{c.error("Could not enable video upload",l)})}v.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(V.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,p.statisticsInterval)};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return o(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Jt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(V.REMOTE_DATA_STATS,{inbound:{topology:oe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:oe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=Be.AUDIO_MIX,r=this._statBytes[i],a=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(a=!0),r.stalled!==a&&this._triggerEvent(V.REMOTE_ALL_STALL,a)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:a}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:pt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:p.producerNotificationDataChannel?7:0,producerCommandDataChannelVersion:p.producerCommandDataChannel?3:0,consumerScreenDataChannelVersion:p.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:p.producerScreenDataChannel?1:0,asrDataChannelVersion:p.asrDataChannel?1:0,onDemandTracks:!0,unifiedPlan:!0,singleSession:!0,videoTracksCount:p.videoTracksCount,red:p.serverAudioRed,audioShare:p.audioShareCapabilityEnabled};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return o(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,c.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:v.patchRemoteSDP(e)});if(c.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw c.error("[single] unable to set remote offer",i),f.log(T.ERROR,"setRemoteDescription-single"),i}).then(()=>o(this,null,function*(){if(c.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this.handleTracks(),this._pc.createAnswer()})).catch(i=>{throw c.error("[single] unable to create answer",i),f.log(T.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=v.patchLocalSDP(i.sdp,!1,y.isBrokenH264(),!1,p.h264spsPpsIdrInKeyframe),i)).then(i=>o(this,null,function*(){if(c.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw c.error("[single] unable to set local answer",i),f.log(T.ERROR,"setLocalDescription-single"),i}).then(i=>o(this,null,function*(){c.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),c.debug("[single] remote offer has been processed")})).catch(i=>{c.warn("[single] unable to send local answer",i),f.log(T.ERROR,"acceptProducer")}).then(()=>o(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){c.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}handleTracks(){this._newAudioShareTrack&&(this._pc.getTransceivers().forEach(e=>{e.mid.endsWith("s")&&(e.sender.track!==null&&c.warn("Unexpected track assigned to audioshare"),e.direction="sendonly",e.sender.replaceTrack(this._newAudioShareTrack).catch(t=>{c.error("ServerTransport: Unable to replace track",t),f.log(T.ERROR,"replaceTrack-single")}),this._newAudioShareTrack=null)}),this._newAudioShareTrack&&c.warn("Cannot find audioshare transceiver"))}_onSignalingNotification(e){return o(this,null,function*(){if(!!this._isOpen)switch(e.notification){case 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}})}_onAsrTranscription(e){this._triggerEvent(V.ASR_TRANSCRIPTION,e)}_onProducerUpdated(e){return o(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),p.breakVideoPayloadTypes&&(c.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes",null)),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){c.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=a=>{this._triggerEvent(V.REMOTE_TRACK_REMOVED,i.id,i,a.track)}),i.getTracks().find(a=>a.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(V.REMOTE_TRACK_ADDED,i.id,i,t.track)):c.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){c.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(c.debug("[single] connection state changed",{state:e.connectionState},t),f.log(T.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===H.IDLE||i===H.OPENED?this._setState(H.CONNECTING):e.iceConnectionState==="checking"&&this._setState(H.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(H.RECONNECTING);break;case"connected":this._setState(H.CONNECTED),v.getPeerConnectionHostInfo(e).then(r=>{r&&f.log(T.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){if(this._pc){p.consumerScreenDataChannel&&t&&(e=t);let i=!1;this._pc.getSenders().forEach(r=>{r.track&&r.track.kind===e.kind&&!this._disabledSenders.has(r)&&r.track.contentHint===e.contentHint&&(r.track.enabled=e.enabled,r.replaceTrack(e).catch(a=>{c.error("ServerTransport: Unable to replace track",a),f.log(T.ERROR,"replaceTrack-single")}),i=!0)}),!i&&e.kind===pe.audio&&e.contentHint==="music"&&(this._newAudioShareTrack=e)}this._applyConsumerSettings()}getStreamWaitingTimeMs(e,t){if(!this._pc)return f.log(T.PAT_WAITING_TIME_ERROR,"noConnection"),c.error("Cannot get stream waiting time, peer connection is not initialized"),0;if(!RTCRtpReceiver.prototype.getSynchronizationSources)return f.log(T.PAT_WAITING_TIME_ERROR,"oldBrowser"),c.error("Cannot get stream waiting time, RTCRtpReceiver.getSynchronizationSources is not supported"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return f.log(T.PAT_WAITING_TIME_ERROR,"noReceiver"),c.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return c.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return f.log(T.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),c.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let d=t-s&_s,l=Math.ceil(d/hs);return Math.min(100,Math.max(0,l))}};var V=(w=>(w.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",w.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",w.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",w.REMOTE_ALL_STALL="REMOTE_ALL_STALL",w.REMOTE_DATA_STATS="REMOTE_DATA_STATS",w.STATE_CHANGED="STATE_CHANGED",w.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",w.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",w.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",w.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",w.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",w.NETWORK_STATUS="NETWORK_STATUS",w.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",w.ASR_TRANSCRIPTION="ASR_TRANSCRIPTION",w))(V||{}),H=(d=>(d.IDLE="IDLE",d.OPENED="OPENED",d.CONNECTING="CONNECTING",d.RECONNECTING="RECONNECTING",d.CONNECTED="CONNECTED",d.CLOSED="CLOSED",d.FAILED="FAILED",d))(H||{}),oe=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(oe||{}),Sr=class extends ae{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){c.log("Update transport settings",e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(c.log(`Trying allocate participant [${e}]`),this._allocated.indexOf(e)!==-1){c.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,i=!1,r=!1){c.log("Trying open participant",{participantIds:e});let a=r;for(let s of e){if(this._opened.indexOf(s)!==-1){c.warn(`The participant [${s}] has already had opened transport`);continue}if(this._allocated.indexOf(s)===-1){c.warn(`The participant [${s}] has no allocated transport`);continue}this._opened.push(s),a=!0}!a||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),c.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&c.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}getState(){var e,t;return this._topology==="SERVER"?(e=this._serverTransport)==null?void 0:e.getState():(t=this._directTransport)==null?void 0:t.getState()}_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)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),f.log(T.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],a=e.offerToDeviceIdxs||[],s=i.length&&r.length?v.composeParticipantId(i[0],r[0],a[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){c.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&c.warn("Topology changed to DIRECT, but the allocated participants count more then one");let d=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=s===d;this._directTransport=this._createDirectTransport(d,l)}this._opened.indexOf(d)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_createDirectTransport(e,t=!1){let i=new ut(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._dtListeners&&this._dtListeners.length>0&&c.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new Ve(this._signaling,this._mediaSource,this._serverSettings);return this._stListeners&&this._stListeners.length>0&&c.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER")),e.addEventListener("ASR_TRANSCRIPTION",this._onAsrTranscription.bind(this))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;p.noiseSuppression!==e&&(p.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onAsrTranscription(e){this._triggerEvent("ASR_TRANSCRIPTION",e)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(f.log(T.PAT_WAITING_TIME_ERROR,"wrongTopology"),c.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(f.log(T.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var mt=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(mt||{}),vr=class extends ae{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,V.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,V.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,V.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,V.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===pe.audio&&((r=this._detector)==null||r.destroy(),this._detector=new zt(e,t),!this._interval)){let a=()=>{this._collectVolumes(),this._interval=window.setTimeout(a,p.voiceParams.interval)};this._interval=window.setTimeout(a,p.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===pe.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===Be.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e===oe.DIRECT&&(this._activeParticipants=null)}};var Er=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(Er||{}),Ir=class extends ae{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i===oe.SERVER,this.subscribe(e,mt.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,V.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,V.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let a=e[r].smoothed;a>t&&a>p.voiceParams.threshold&&(t=a,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*p.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent("SPEAKER_CHANGED",e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e===oe.SERVER}};var bi=class extends ae{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,V.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,mt.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===H.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),p.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),p.specListenerParams.volumeTimeout))),t===H.FAILED&&this._connectionTimeout&&(c.warn("Transport failed, send callSpecError"),f.log(T.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==H.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(c.warn("There is not connected transport, send callSpecError"),f.log(T.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),f.log(T.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&c.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var gs=1e3,fs=1e4;var Ss=15,$=class extends ae{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._myLastRequestedLayouts={};this._state="IDLE";this._participantState=K.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;f.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),f.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new Ti,p.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),gs))}static current(){return $._current}static hangupAfterInit(){$._activationMutex&&!$._current&&($._delayedHangup=!0)}static id(){var e,t;return((t=(e=$._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",a=!1,s=!1,d){return o(this,null,function*(){if($._activationMutex)throw f.log(T.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new B(D.FAILED);$._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let l=this._mediaSource.getMediaSettings();t===je.CHAT||e.length>1?this._logWithMediaSettings(T.OUTGOING_MULTIPARTY_CALL,l):this._logWithMediaSettings(T.OUTGOING_CALL,l);let u=yield this._startConversation(e,t,Qe.OUTGOING,i,r,a,s,d);if(!this._conversation)throw new B(D.UNKNOWN_ERROR);if(this._participantState=K.ACCEPTED,this._signaling.changeMediaSettings(l),yield this._processConnection(u),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),$._delayedHangup)throw new B(D.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let E=Object.values(this._participants),C;return p.batchParticipantsOnStart&&(C=v.mapSharedParticipants(E)),yield this._processConnectionSharedMovieInfo(u),g.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),C),this._onConversationParticipantListChunk(u),g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),$._current=this,this._conversation.concurrent?yield this._acceptConcurrent():p.batchParticipantsOnStart||this._setParticipantsStatus(E,J.WAITING),this._conversation}catch(l){throw this._close(l,"Unable to start conversation"),l}finally{$._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){var t;if($._activationMutex)throw f.log(T.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new B(D.FAILED);$._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.JOIN_CONVERSATION,r);let a=yield this._joinConversation(e);if(!this._conversation)throw new B(D.UNKNOWN_ERROR);return this._conversation.observer=i,g.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(c.log("In waiting hall"),$._current=this,$._activationMutex=!1,this._signaling.readyToSend(),g.onLocalStatus(J.WAITING_HALL),this._conversation):this._onJoinPart2(a)}catch(i){throw $._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return o(this,null,function*(){var t,i,r,a,s,d,l;c.debug("Join conversation part 2"),$._activationMutex=!0;try{if(this._participantState=K.ACCEPTED,!this._conversation||!this._mediaSource)throw new B(D.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._processConnection(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),$._delayedHangup)throw new B(D.CANCELED);let u=Object.values(this._participants),E;p.batchParticipantsOnStart&&(E=v.mapSharedParticipants(u.filter(O=>!O.isInRoom)));let C=[];if((i=(t=e==null?void 0:e.rooms)==null?void 0:t.rooms)==null?void 0:i.length)for(let O of e.rooms.rooms)C.push({id:O.id,name:O.name,participantCount:O.participantCount,participantIds:yield Promise.all(((a=(r=O==null?void 0:O.participantIds)==null?void 0:r.map)==null?void 0:a.call(r,this._getExternalIdByParticipantId.bind(this)))||[]),participants:((s=O==null?void 0:O.participants)==null?void 0:s.participants)?this._participantListChunkToExternalChunk(O.participants):void 0,active:O.active,muteStates:O.muteStates});let M=(l=(d=e==null?void 0:e.rooms)==null?void 0:d.roomId)!=null?l:null;return yield this._processConnectionSharedMovieInfo(e),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),E,{rooms:C,roomId:M}),this._onConversationParticipantListChunk(e),g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),$._current=this,p.batchParticipantsOnStart||this._setParticipantsStatus(u,J.WAITING),this._openTransport(u,!1),this._conversation}catch(u){throw this._close(u,"Unable to join conversation"),u}finally{$._activationMutex=!1}})}onPush(r){return o(this,arguments,function*(e,t=te.USER,i){if($._activationMutex)throw c.warn("Conversation: there is already running activation"),new B(D.REJECTED);$._activationMutex=!0;try{let a=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new B(D.UNKNOWN_ERROR);if(!a.conversation.participants.find(d=>{var l;return d.state===K.CALLED&&d.id===((l=this._conversation)==null?void 0:l.userId)}))throw c.log("Push rejected (there is an active call)"),f.log(T.PUSH,"rejected"),new B(D.REJECTED);if(yield this._processConnection(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),f.log(T.PUSH,"accepted"),$._current=this,$._delayedHangup)throw new B(D.CANCELED);$._activationMutex=!1}catch(a){throw $._activationMutex=!1,this._close(a,"Unable to handle inbound call push"),a}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(ai.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>v.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return o(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new B(D.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.ACCEPT_CONCURRENT,e),c.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),g.onCallAccepted(),this._state="ACTIVE",this._participantState=K.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return o(this,null,function*(){var t;if(this._state!=="IDLE")throw f.log(T.ERROR,"acceptIncoming"),c.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new B(D.UNKNOWN_ERROR);this._state="PROCESSING",c.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let i=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.ACCEPT_INCOMING,i),this._signaling.changeMediaSettings(i),yield this._signaling.acceptCall(i),this._participantState=K.ACCEPTED;let r=Object.values(this._participants),a;if(p.batchParticipantsOnStart&&(a=v.mapSharedParticipants(r)),g.onCallAccepted(),g.onLocalStream(this._mediaSource.getStream(),i),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),a),p.useParticipantListChunk){let l=yield this._getInitialParticiapntListChunk();(t=l==null?void 0:l.participants)==null||t.forEach(u=>{let E=v.composeId(u),C=this._participants[E];C&&(C.movieShareInfos=u.movieShareInfos)}),this._onConversationParticipantListChunk({participants:l})}g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let s=Dt(this._getMuteStatesForCurrentRoom(),Oe.MUTE),d=Dt(this._getMuteStatesForCurrentRoom(),Oe.MUTE_PERMANENT);for(let l of[s,d])l.length&&(yield this._processMuteState({mediaOptions:l,stateUpdated:!0}));return this._state="ACTIVE",this._changeFeatureSet(),p.batchParticipantsOnStart||this._setParticipantsStatus(r,J.WAITING),this._openTransport(r,!0),this._conversation}catch(i){throw this._close(i,"Unable to accept call"),i}})}decline(){return o(this,null,function*(){var e;if(this._state!=="IDLE")throw f.log(T.ERROR,"declineIncoming"),c.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",c.debug("Decline incoming call"),this._logWithMediaSettings(T.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=K.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(D.REJECTED)),this._close(new B(D.REJECTED))})}hangup(){return o(this,null,function*(){c.debug("Hangup");let e=this._state==="ACTIVE"?D.HUNGUP:D.CANCELED;f.log(T.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new B(e))):g.onHangup(new B(D.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new B(D.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=D.UNKNOWN_ERROR);let a=i.participant;yield this._onAddParticipant(v.composeId(a),a,r)})}removeParticipant(e,t=!1){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let a of e)(a.state===K.CALLED||a.state===K.ACCEPTED)&&(this._transport.isAllocated(a.id)||this._transport.allocate(a.id,t)),a.state===K.ACCEPTED&&i.push(a.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&c.error(t,e),c.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(D.FAILED):f.log(T.ERROR,e.hangup),$._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([D.CANCELED,D.NOT_FRIENDS,D.CALLEE_IS_OFFLINE,D.CALLER_IS_BLOCKED,D.CALLER_IS_REJECTED].indexOf(e.hangup)!==-1||e.hangup===D.REJECTED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===D.HUNGUP&&(!e.remote||this._participantState===K.CALLED)){g.onHangup(e,i),this.destroy();return}if(e.hangup===D.MISSED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===D.SOCKET_CLOSED&&$._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===D.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=K.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),f.destroy(),this._conversation=null,this._myLastRequestedLayouts={},$._current=null,$._delayedHangup=!1,g.onHangup(e||new B(D.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;c.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),f.destroy(),this._conversation=null,this._myLastRequestedLayouts={},$._current=null,$._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return o(this,null,function*(){let t=yield this._api.getConversationParams(e);c.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:a}=t;if(a&&i.push(a),r){let s=r.urls.filter((d,l,u)=>u.indexOf(d)===l);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return p.iceServers=i,p.wssBase=t.endpoint,p.wssToken=t.token,t.client_type&&(p.clientType=t.client_type),p.externalUserType=t.external_user_type,t})}_addGeoParamsToEndpoint(e,t){return t.isp_as_no&&(e+=`&ispAsNo=${t.isp_as_no}`),t.isp_as_org&&(e+=`&ispAsOrg=${t.isp_as_org}`),t.loc_cc&&(e+=`&locCc=${t.loc_cc}`),t.loc_reg&&(e+=`&locReg=${t.loc_reg}`),e}_startConversation(e,t,i,r,a="",s=!1,d=!1,l){return o(this,null,function*(){let u=v.uuid();c.debug("Conversation: start",{conversationId:u,opponentIds:e,opponentType:t,direction:i});let E=r.includes(le.VIDEO),C=yield this._api.startConversation(u,e,t,E,a,s,d,{onlyAdminCanShareMovie:l});c.debug("Api.startConversation",C);let M=yield this._getConversationParams(C.id);C.endpoint=this._addGeoParamsToEndpoint(C.endpoint,M);let O=yield this._connectSignaling(Ke.START,C);return yield this._setConversation(C,O,i),O})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:a,observedIds:s,payload:d}=e;c.debug("Conversation: join",{conversationId:t,joinLink:a,observedIds:s});let l=i.includes(le.VIDEO),u;if(t)u=yield this._api.joinConversation(t,l,r);else if(a)u=yield this._api.joinConversationByLink(a,l,s,d);else throw new B(D.UNKNOWN_ERROR);c.debug("Api.joinConversation",u),yield this._getConversationParams(u.id);let E=yield this._connectSignaling(Ke.JOIN,u);return yield this._setConversation(u,E,Qe.JOINING),E})}_prepareConversation(r){return o(this,arguments,function*(e,t=te.USER,i){c.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let a=this._api.getUserId();if(!a)throw new B(D.UNKNOWN_ERROR);let s=yield this._getConversationParams(e),d=s.device_idx||0,l=`${p.wssBase}?userId=${a}&entityType=${t}&deviceIdx=${d}&conversationId=${e}&token=${p.wssToken}`;l=this._addGeoParamsToEndpoint(l,s);let u={id:e,peerId:i,endpoint:l,is_concurrent:!1,p2p_forbidden:!1,device_idx:d},E=yield this._connectSignaling(Ke.ACCEPT,u);return $._current&&($._current._participantState===K.ACCEPTED||$._current._participantState===K.CALLED)?(c.log("Push rejected (busy)"),f.log(T.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(D.BUSY),Promise.reject({hangup:D.BUSY})):($._current&&($._current.destroy(),$._current=null),yield this._setConversation(u,E,Qe.INCOMING,t),E)})}_createParticipant(e){return o(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:ge(),participantState:{},state:K.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[],isInRoom:!1},e);if(e.externalId){let r=v.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(r,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return((i=t.observedIds)==null?void 0:i.length)&&(t.externalId.observer=!0),this._setParticipantMarkers(t,t.markers),t})}_getParticipantId(e){return o(this,null,function*(){try{let t=v.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new B(D.NETWORK_ERROR),t),t}})}_setConversation(a,s,d){return o(this,arguments,function*(e,t,i,r=te.USER){yield this._prepareParticipants(t.conversation.participants);let l=this._api.getUserId(),u=e.device_idx||0;if(!l){let M=(t.conversation.participants||[]).find(O=>v.comparePeerId(O.peerId,t.peerId));if(!M)throw new B(D.UNKNOWN_ERROR);l=Number(M.id),M.idType&&(r=M.idType),M.deviceIdx&&(u=M.deviceIdx),this._api.setUserId(l)}let E=v.composeParticipantId(l,r,u),C=yield this._getParticipantId(E);this._conversation={userId:l,compositeUserId:E,externalId:C,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],featuresPerRole:t.conversation.featuresPerRole,id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||oe.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordsInfoByRoom:new Map,muteStates:new Map,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1,asrInfo:null,roomId:null},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(p.forceRelayPolicy=e.p2p_forbidden),f.log(T.RELAY_POLICY,p.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new B(D.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.featuresPerRole=e.conversation.featuresPerRole,this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||oe.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 zi;return this.subscribe(e,Me.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Me.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new qt(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,Te.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,Te.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_processConnection(e){return o(this,null,function*(){yield this._registerConnectionParticipants(e),this._processConnectionData(e)})}_prepareParticipants(e){return o(this,null,function*(){let t=e.map(i=>i.id);t.length&&(yield this._api.prepareUserIds(t))})}_onConversationParticipantListChunk(e){let t=e.participants;t&&g.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(this._createParticipantListChunk(t)))}_createParticipantListChunk(e){return Ue(Ue({},{participants:[],countBefore:0,countAfter:0,markerFound:!1}),e)}_participantListChunkToExternalChunk(e){let t=v.mapSharedParticipants(e.participants.map(i=>{let r=v.composeId(i);return this._participants[r]}));return gt(Ue({},e),{participants:t})}_registerConnectionParticipants(e){return o(this,null,function*(){var i,r,a,s,d,l;yield this._registerParticipants(e.conversation.participants),((i=e.participants)==null?void 0:i.participants)&&(yield this._registerParticipants((r=e.participants)==null?void 0:r.participants));let t=(s=(a=e==null?void 0:e.rooms)==null?void 0:a.rooms)!=null?s:[];for(let u of t)yield this._registerParticipants((l=(d=u==null?void 0:u.participants)==null?void 0:d.participants)!=null?l:[],!0)})}_registerParticipants(e,t=!1){return o(this,null,function*(){if(!!this._conversation)for(let i of e){let r=v.composeId(i);if(this._isMe(r)){this._conversation.roles=i.roles||[],this._conversation.roles.length&&(c.debug(`Local roles changed: ${i.roles}`),g.onLocalRolesChanged(this._conversation.roles)),yield this._registerParticipantLocalMuteState(i);continue}if(i.state===K.HUNGUP||i.state===K.REJECTED){this._participants[i.id]&&this._removeParticipant(this._participants[i.id],D.HUNGUP);continue}this._registerParticipantInCache(yield this._createParticipant({id:r,externalId:i.externalId&&fe.fromSignaling(i.externalId,i.deviceIdx||0),mediaSettings:ge(i.mediaSettings),participantState:v.mapParticipantState(i),state:i.state,roles:i.roles||[],status:p.batchParticipantsOnStart?J.WAITING:null,muteStates:i.muteStates||{},unmuteOptions:i.unmuteOptions||[],observedIds:i.observedIds||[],markers:this._denormalizeMarkers(r,i.markers),movieShareInfos:i.movieShareInfos,isInRoom:t})),i.roles&&i.roles.length&&(c.debug(`Roles for participant [${r}] changed: ${i.roles}`),g.onRolesChanged(this._participants[r].externalId,i.roles))}})}_registerParticipantLocalMuteState(e){return o(this,null,function*(){if(!e.muteStates)return Promise.resolve();let t=Dt(e.muteStates,Oe.MUTE),i=Dt(e.muteStates,Oe.MUTE_PERMANENT);for(let r of[t,i])!r.length||(yield this._onMuteParticipant({muteStates:e.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:r,stateUpdated:!0}))})}_getStatusByTransportState(e){let t;return e===H.CONNECTED?t=J.CONNECTED:e===H.CONNECTING||e===H.OPENED?t=J.CONNECTING:e===H.RECONNECTING&&(t=J.RECONNECT),t}_registerParticipantInCache(e){return this._participants[e.id]=e}_getExistedParticipantByIdOrCreate(e){return o(this,null,function*(){return this._participants[e]||this._createParticipant({id:e})})}_getExternalIdByParticipantId(e){return o(this,null,function*(){var t;if(this._isMe(e))return this._conversation.externalId;if(p.useParticipantListChunk)return(yield this._getExistedParticipantByIdOrCreate(e)).externalId;if((t=this._participants[e])==null?void 0:t.externalId)return this._participants[e].externalId;{let i=yield this._getParticipantId(e);return this._api.cacheExternalId(e,i),i}})}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){return o(this,null,function*(){if(p.useParticipantListChunk){let i=this._registerParticipantInCache(yield this._getExistedParticipantByIdOrCreate(e));return this._setParticipantMarkers(i,t),i}return this._participants[e]})}_warnParticipantNotInConversation(e){c.warn(`Participant [${e}] isn't in conversation`)}_setParticipantMarkers(e,t){return e.markers=this._denormalizeMarkers(e.id,t),e}_denormalizeMarkers(e,t){if(!t)return null;let i=Object.values(t).find(r=>"ts"in r&&"rank"in r);return Object.entries(t).reduce((r,[a,s])=>(r[a]=gt(Ue(Ue({},i),s),{id:e}),r),{})}_processConnectionData(e){return o(this,null,function*(){this._processRooms(e),this._processMuteStates(e),e.conversation.pinnedParticipantId&&(yield this._onPinParticipant(e.conversation.pinnedParticipantId)),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(ii.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)})}_processRooms(e){var i,r;let t=(r=(i=e.rooms)==null?void 0:i.roomId)!=null?r:null;this._onRoomSwitched(t,!0)}_processMuteStates(e){var i,r,a;this._setMuteStatesForRoomId((i=e.conversation)==null?void 0:i.muteStates,null);for(let s of(a=(r=e.rooms)==null?void 0:r.rooms)!=null?a:[])this._setMuteStatesForRoomId(s.muteStates,s.id);let t=this._getMuteStatesForCurrentRoom();this._onMuteParticipant({muteStates:t,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(t),muteAll:!0,stateUpdated:!0,roomId:this._conversation.roomId})}_processRecordInfos(e){var t,i,r,a;this._onRecordInfo((t=e.conversation.recordInfo)!=null?t:null);for(let s of(r=(i=e.rooms)==null?void 0:i.rooms)!=null?r:[])this._onRecordInfo((a=s.recordInfo)!=null?a:null,s.id)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Sr(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new Ci,this.subscribe(this._transport,V.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,V.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,V.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,V.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,V.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,V.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,V.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,V.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,V.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,V.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,V.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this)),this.subscribe(this._transport,V.ASR_TRANSCRIPTION,this._onAsrTranscription.bind(this));let e=this._conversation.direction===Qe.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===K.ACCEPTED||t.state===K.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new vr(this._transport),this.subscribe(this._volumesDetector,mt.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Ir(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,Er.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Ri(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new bi(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=y.getCameras().length,t=y.getMicrophones().length;c.debug("Cameras: "+e+(y.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(y.hasMicrophonePermission()?"✔":"✖")),f.log(T.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){f.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===K.CALLED||e.state===K.ACCEPTED||this._state==="CLOSE"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),!!this._participants[e.id]&&(t===D.HUNGUP?this._setParticipantsStatus([e],J.HANGUP):this._setParticipantsStatus([e],J.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Pe.CAMERA,stopStream:!0}]),delete this._participants[e.id],g.onRemoteRemoved(e.externalId,e.markers)))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(a=>a.stop()),(i=e.secondStream)==null||i.getTracks().forEach(a=>a.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){c.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return o(this,null,function*(){c.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===K.ACCEPTED||r.state===K.CALLED)){c.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(r=this._registerParticipantInCache(yield this._createParticipant({id:e,externalId:t.externalId&&fe.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:ge(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}))),this._setParticipantsStatus([r],J.WAITING),i?(r.state=K.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=K.CALLED,this._transport.allocate(r.id,!0),f.log(T.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){c.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=Ss;i++){let r=v.compose(e,i),a=this._participants[r];a&&t.push(a)}if(!t.length){this._warnParticipantNotInConversation(e);return}if(this._transport)for(let i of t)this._transport.close(i.id);f.log(T.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new qt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(se.UNKNOWN)})}toggleScreenCapturing(e,t){return o(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e,t):Promise.reject(se.UNKNOWN)})}setVideoStream(e,t=!1){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return o(this,null,function*(){if(this._mediaSource)return f.log(T.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return f.log(T.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return o(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let a=typeof r.uid=="object"?r.uid:fe.fromId(r.uid),s=fe.toString(a);i[s]=r.priority}for(let r of Object.values(this._participants)){let a=fe.toString(r.externalId);i.hasOwnProperty(a)&&(t[r.id]=i[a])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return o(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return o(this,null,function*(){let t={};return t[qe(e)]={keyFrameRequested:!0},this._signaling.updateDisplayLayout(t)})}requestTestMode(e,t){return o(this,null,function*(){return this._signaling.requestTestMode(e,t)})}updateDisplayLayout(e){return o(this,null,function*(){if(e.length<1||!this._signaling.ready)return;c.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let a=typeof r.uid=="object"?r.uid:fe.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(a);if(!s){let E=fe.toString(a);c.log(`Unknown participant external ID ${E}`);continue}let d=v.compose(s,a.deviceIdx),l=qe({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),u=this._participants[d];u?u.lastRequestedLayouts[l]=r:this._isMe(d)&&(this._myLastRequestedLayouts[l]=r),Kt(r)?(this._isMe(d)&&delete this._myLastRequestedLayouts[l],this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now())):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&p.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=r)}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>p.videoTracksCount;){let r=i.next();if(r.done){c.error("Cannot accommodate all streaming requests: tracks available "+p.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]={stopStream:!0}}yield this._sendUpdateDisplayLayout(t)})}feedback(e){return this._signaling.feedback(e)}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(c.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=$t(e),r=this._participants[i.participantId],{externalId:a}=this._conversation,s=this._isMe(i.participantId);if(r){if(i.streamName&&(i.mediaType===Pe.STREAM||i.mediaType===Pe.MOVIE)){let d={stream:null,streamName:i.streamName,mediaType:i.mediaType};s?g.onLocalLive(a,d):g.onRemoteLive(r.externalId,d)}else s||g.onRemoteStream(r.externalId,null);f.log(T.PAT_DEALLOCATED)}else c.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return o(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,a]of Object.entries(t.errorCodeByParticipantId||{})){let s=$t(r),d=this._participants[s.participantId];if(d){let l;typeof a!="number"?(c.warn(`Unexpected error code ${a} received for participant ${s.participantId}`),l=ea.UNKNOWN_ERROR):l=ta(a),i.push({externalId:d.externalId,errorReason:l})}}if(i&&i.length)throw new Mi("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+fs>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e)}_onParticipantSourcesUpdate(e){if(this._conversation){c.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){c.log("Promoted in waiting hall",!e.demote),e.demote?(c.log("Kicked from waiting hall"),this._close(new B(D.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return o(this,arguments,function*(e,t=0,i=[]){c.log(`Chat room updated: ${e}`);let a=[],s=[];i.length&&(i.forEach(d=>{if(d.externalId){let l=ve.fromSignaling(d.externalId);a.push(l),this._api.cacheExternalId(d.id.id,l)}else s.push(v.decomposeId(d.id.id).id)}),s.length&&!a.length&&(a=yield this._api.getExternalIdsByOkIds(s))),g.onChatRoomUpdated(e,t,a)})}_onSharedMovieUpdate(e){return o(this,null,function*(){let{externalId:t}=this._conversation,{data:i}=e;for(let r of i)if(this._isMe(r.participantId))g.onLocalLiveUpdate(t,r);else{let s=yield this._getExternalIdByParticipantId(r.participantId);s&&g.onRemoteLiveUpdate(s,r)}})}_onSharedMovieInfoStarted(e){return o(this,null,function*(){c.log(`Shared movie started data received: ${e.notification}`),yield this._processSharedMovieInfo(e.movieShareInfo)})}_processSharedMovieInfos(e){return o(this,null,function*(){e&&(yield Promise.all(e.map(t=>this._processSharedMovieInfo(t))))})}_processSharedMovieInfo(e){return o(this,null,function*(){var r;if(!e)return;let{externalId:t}=this._conversation;if(this._isMe(e.initiatorId))g.onLocalSharedMovieInfo(t,e);else{let a=yield this._getExternalIdByParticipantId(e.initiatorId);a&&g.onRemoteSharedMovieInfo(a,e)}this._transport.getTopology()===oe.SERVER&&this._transport.getState()===H.IDLE&&this._participantState!==K.CALLED&&this._transport.open(this._transport.allocated(),null,!!((r=this._conversation)==null?void 0:r.observer),!0)})}_processConnectionSharedMovieInfo(e){return o(this,null,function*(){let t=e.conversation.participants.find(i=>this._isMe(v.composeId(i)));yield this._processSharedMovieInfos(t==null?void 0:t.movieShareInfos)})}_onSharedMovieInfoStopped(e){return o(this,null,function*(){c.log(`Shared movie stopped data received: ${e.notification}`);let{externalId:t}=this._conversation,{initiatorId:i,movieId:r,source:a}=e,s={initiatorId:i,movieId:r,source:a};if(this._isMe(i))g.onLocalSharedMovieStoppedInfo(t,s);else{let l=yield this._getExternalIdByParticipantId(i);l&&g.onRemoteSharedMovieStoppedInfo(l,s)}})}_onFeaturesPerRoleChanged(e){c.log(`Features per role changed: ${e.notification}`),g.onFeaturesPerRoleChanged(e.featuresPerRole)}_waitForStreamIfNeeded(e){var d,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||p.producerScreenDataChannel&&t.mediaType===Pe.SCREEN)return;let i=qe(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){c.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),f.log(T.PAT_OUTDATED_RESPONSE);return}let a=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(a,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let u=t.participantId,E=this._participants[u],{externalId:C}=this._conversation,M=this._isMe(u);if(!E&&!M){f.log(T.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${u}`);return}let O=M?C:E.externalId,w=this._streamByStreamId.get(a);if(!w){f.log(T.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}f.log(T.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,a);let F=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(F===Pe.STREAM||F===Pe.MOVIE){if((l=e.participantStreamDescription)==null?void 0:l.streamName){let de={streamName:e.participantStreamDescription.streamName,stream:w,mediaType:F};M?g.onLocalLive(O,de):g.onRemoteLive(O,de)}}else if(p.producerScreenTrack&&F===Pe.SCREEN)g.onRemoteScreenStream(E.externalId,w);else if(!M){let de=(p.producerScreenTrack?null:E.secondStream)||w;g.onRemoteStream(E.externalId,de)}}else{c.debug(`Waiting for ${s} until stream ${a} for ${i} is switched`);let u=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,u)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(qe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(qe(i)))return i}else{let i={participantId:t,mediaType:Pe.CAMERA};if(this._streamIdByStreamDescription.has(qe(i)))return i;let r={participantId:t,mediaType:Pe.SCREEN};if(this._streamIdByStreamDescription.has(qe(r)))return r}return c.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?v.includesOneOf(this._conversation.roles,[Xe.ADMIN,Xe.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!v.includesOneOf(this._conversation.roles,[Xe.ADMIN,Xe.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}startAsr(){return o(this,null,function*(){yield this._signaling.startAsr()})}stopAsr(){return o(this,null,function*(){yield this._signaling.stopAsr()})}requestAsr(e){return o(this,null,function*(){yield this._signaling.requestAsr(e)})}muteParticipant(){return o(this,arguments,function*(e=null,t,i=[],r=null){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i,r)})}enableFeatureForRoles(e,t){return o(this,null,function*(){yield this._signaling.enableFeatureForRoles(e,t)})}pinParticipant(e,t){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return o(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return o(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Hr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return o(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Oa(e));let a=yield this._signaling.getWaitingHall(r,t,i);if(a.error)return Promise.reject(a.message);let s=a.participants||[],d=[],l=[],u=null;return s.length&&(s.forEach(E=>{if(E.externalId){let C=ve.fromSignaling(E.externalId);d.push(C),this._api.cacheExternalId(E.id.id,C)}else l.push(v.decomposeId(E.id.id).id)}),l.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(l)),a.hasMore&&(u=ka(s[s.length-1].id))),{participants:d,pageMarker:u,totalCount:a.totalCount||0}})}promoteParticipant(e,t){return o(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return o(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return o(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return o(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(r){return o(this,arguments,function*({movieId:e,gain:t,metadata:i}){let a={movieId:e};(t||t===0)&&(a.gain=t),i&&(a.metadata=i);let s=yield this._signaling.addMovie(a);if(s.error)throw new Error(s.error);return{movieId:s.movieId,streamType:s.streamType}})}updateMovie(e){return o(this,null,function*(){let t=yield this._signaling.updateMovie(e);if(t.error)throw new Error(t.error)})}removeMovie(e){return o(this,null,function*(){let t={movieId:e},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}updateRooms(e,t){return o(this,null,function*(){let i=yield this._signaling.updateRooms(e,t);if(i.error)throw new Error(i.error)})}activateRooms(e,t){return o(this,null,function*(){let i=yield this._signaling.activateRooms(e,t);if(i.error)throw new Error(i.error)})}switchRoom(e,t){return o(this,null,function*(){let i=yield this._signaling.switchRoom(e,t);if(i.error)throw new Error(i.error)})}removeRooms(e){return o(this,null,function*(){let t=yield this._signaling.removeRooms(e);if(t.error)throw new Error(t.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",a=null,s=null){return o(this,null,function*(){let d={movieId:i,name:t,privacy:r,groupId:a,roomId:s,streamMovie:!e},l=yield this._signaling.startStream(d);return l.error?Promise.reject(l.message):l})}stopStream(e=null){return o(this,null,function*(){let t=yield this._signaling.stopStream({roomId:e});return t.error?Promise.reject():t})}recordSetRole(e,t,i=null){return o(this,null,function*(){let r=yield this._signaling.recordSetRole(e,t,i);if(r.error)throw new Error(r.error)})}getStreamInfo(){return o(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return o(this,null,function*(){var r;if(e<p.videoMinWidth||t<p.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<p.videoMinWidth||i.effect.height<p.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");p.videoEffectMaxHeight=i.effect.height,p.videoEffectMaxWidth=i.effect.width}return p.videoMaxWidth=e,p.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return o(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}getParticipants(e){return o(this,null,function*(){let t=e.externalIds.map(s=>({id:s.id,type:p.externalUserType})),i=yield this._signaling.getParticipants(t);if(i.error)throw new Error(i.error);let r=i.participants,a=this._transport.getState();return Promise.all(r.map(s=>o(this,null,function*(){var l;let d=v.composeId(s);return this._createParticipant({id:d,externalId:s.externalId&&fe.fromSignaling(s.externalId,s.deviceIdx||0),mediaSettings:ge(s.mediaSettings),participantState:v.mapParticipantState(s),state:s.state,roles:s.roles||[],status:(l=this._getStatusByTransportState(a))!=null?l:J.WAITING,muteStates:s.muteStates||{},unmuteOptions:s.unmuteOptions||[],observedIds:s.observedIds||[],markers:this._denormalizeMarkers(d,s.markers)})}))).then(v.mapSharedParticipants)})}getParticipantListChunk(e){return o(this,null,function*(){var d;c.log("Request participant list chunk",e);let t=yield this._signaling.getParticipantListChunk(e);if(t.error)throw new Error(t.error);let i=this._createParticipantListChunk(t.chunk),r=i.participants.filter(l=>{let u=v.composeId(l);return!this._participants[u]});yield this._registerParticipants(r);let a=(d=this._transport)==null?void 0:d.getState();return i.participants.forEach(l=>{var C,M;let u=v.composeId(l),E=this._participants[u];E.status=(C=this._getStatusByTransportState(a))!=null?C:J.WAITING,E.movieShareInfos=l.movieShareInfos,Object.assign(E.mediaSettings,ge(l.mediaSettings)),Object.assign(E.muteStates,l.muteStates),E.unmuteOptions=(M=l.unmuteOptions)!=null?M:E.unmuteOptions,this._openTransport([E],!0)}),this._participantListChunkToExternalChunk(i)})}_getInitialParticiapntListChunk(){return o(this,null,function*(){let e=p.participantListChunkInitIndex,t=p.participantListChunkInitCount,i="GRID",r=yield this._signaling.getParticipantListChunk({listType:i,fromIdx:e,count:t});return c.debug("Get initial participant list chunk",r.chunk),r.chunk})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t,i;!this._conversation||(c.debug("Local media stream changed",e.mediaSettings),g.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return o(this,null,function*(){var t,i;if(c.log("Screen sharing changed",e.track,e.mediaSettings),p.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;g.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){c.debug(`Remote media settings changed [${e}]`,t);let{externalId:i}=this._conversation;if(this._isMe(e)){g.onLocalMediaSettings(i,t);return}let a=this._participants[e];if(!a){this._warnParticipantNotInConversation(e);return}a.mediaSettings=t,this._state==="ACTIVE"&&g.onRemoteMediaSettings(a.externalId,t,a.markers),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t)}_changeRemoteParticipantState(e,t){c.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];if(!i){this._warnParticipantNotInConversation(e);return}i.participantState=t||{},this._state==="ACTIVE"&&g.onRemoteParticipantState(i.externalId,i.participantState,i.markers)}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(c.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),g.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case 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,e.roomId);case k.RECORD_STOPPED:return this._onRecordInfo(null,e.roomId);case k.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case k.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case k.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin,e.markers);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);case k.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e);case k.FEEDBACK:return this._onFeedback(e);case k.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e);case k.MOVIE_SHARE_STARTED:return this._onSharedMovieInfoStarted(e);case k.MOVIE_SHARE_STOPPED:return this._onSharedMovieInfoStopped(e);case k.ROOMS_UPDATED:return this._onRoomsUpdated(e);case k.ROOM_UPDATED:return this._onRoomUpdated(e);case k.ROOM_PARTICIPANTS_UPDATED:return this._onRoomParticipantsUpdated(e);case k.FEATURES_PER_ROLE_CHANGED:return this._onFeaturesPerRoleChanged(e);case k.ASR_STARTED:return this._onAsrInfo(e.asrInfo);case k.ASR_STOPPED:return this._onAsrInfo(null)}}_onSignalingReconnect(e){return o(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._conversation.featuresPerRole=e.conversation.featuresPerRole,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?yield this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&(yield this._onPinParticipant(this._conversation.pinnedParticipantId,!0))),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let a of e.conversation.participants){let s=v.composeId(a),d=a.roles||[];if(this._isMe(s)){t=ge(a.mediaSettings),Nt(this._conversation.roles,d)||this._onRolesChanged(s,d);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:a.id,participant:a,mediaSettings:a.mediaSettings});else{let u=ge(a.mediaSettings);la(u,l.mediaSettings)||this._changeRemoteMediaSettings(s,u);let E=v.mapParticipantState(a),C=l.participantState;v.isEqualParticipantState(E,C)||this._changeRemoteParticipantState(s,E),Nt(d,l.roles)||this._onRolesChanged(l.id,d)}}for(let a of i)r.indexOf(a)<0&&this._removeParticipant(this._participants[a],D.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){c.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return o(this,null,function*(){let t=v.composeMessageId(e),i=v.getPeerIdString(e.peerId);if(c.debug(`Participant accepted call [${t}]`),this._conversation&&this._isMe(t)){this._close(new B(D.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(r=this._registerParticipantInCache(yield this._createParticipant({id:t,mediaSettings:ge(e.mediaSettings)}))),r.state=K.ACCEPTED,r.mediaSettings=ge(e.mediaSettings),this._logWithMediaSettings(T.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Qe.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){return o(this,null,function*(){c.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=v.composeMessageId(e);if(this._conversation&&this._isMe(t)){this._close(new B(e.reason,{remote:!0}));return}yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers);let i=this._participants[t];if(!i){this._warnParticipantNotInConversation(t);return}this._transport&&this._transport.close(t),i.state=e.reason===D.REJECTED?K.REJECTED:K.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,D.HUNGUP)})}_onAddedParticipant(e){return o(this,null,function*(){var r,a;c.debug(`Participant added [${e.participantId}]`);let t=v.composeMessageId(e),i=this._participants[t];if(i&&i.state!==K.HUNGUP&&i.state!==K.REJECTED){c.debug(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&fe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:v.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}))),i.state=K.CALLED,i.mediaSettings=ge((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=v.mapParticipantState(e.participant),i.roles=((a=e.participant)==null?void 0:a.roles)||[],this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),g.onParticipantAdded(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return o(this,null,function*(){var r,a;c.debug(`Participant joined [${e.participantId}]`);let t=v.composeMessageId(e),i=this._participants[t];if(i&&i.state===K.ACCEPTED){c.warn(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&fe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:v.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},movieShareInfos:e.participant.movieShareInfos,unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[],markers:this._denormalizeMarkers(t,e.participant.markers)}))),this._conversation&&this._conversation.direction===Qe.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=K.ACCEPTED,i.mediaSettings=ge(e.mediaSettings),i.participantState=v.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],J.CONNECTED):this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((a=this._conversation)==null?void 0:a.observer))),g.onParticipantJoined(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i),g.onMuteStates(i.muteStates,i.unmuteOptions,Object.keys(i.muteStates),!1,!1,i.externalId,void 0,!0),yield this._processSharedMovieInfos(i.movieShareInfos)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new B(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){return o(this,null,function*(){let t=v.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,ge(e.mediaSettings))})}_onParticipantStateChanged(e){return o(this,null,function*(){let t=v.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteParticipantState(t,v.mapParticipantState(e))})}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._conversation.featuresPerRole=e.featuresPerRole,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),g.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ge(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),p.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled,i.isAudioSharingEnabled))})}_onSettingsUpdate(e){c.debug("Got settings update notification",e);let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=_r(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){c.debug("Got video quality update notification",e);let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=_r(this._serverSettings,r),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=v.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return o(this,null,function*(){g.onDeviceSwitched(le.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return o(this,null,function*(){let t=v.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),g.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return o(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=v.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),g.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e,t=null){return o(this,null,function*(){var a;if(!this._conversation)return;let i=this._conversation.recordsInfoByRoom.get(t),r=!1;if(!i!=!e?r=!0:i&&e&&(r=i.recordMovieId!==e.recordMovieId),r)if(this._conversation.recordsInfoByRoom.set(t,e),e){let s=yield this._getParticipantId(e.initiator);g.onRecordStarted(s,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId,t)}else g.onRecordStopped(t);e&&this._transport.getTopology()===oe.SERVER&&this._participantState!==K.CALLED&&this._transport.open(this._transport.allocated(),null,!!((a=this._conversation)==null?void 0:a.observer),!0)})}_changeRecordInfoForRoom(){return o(this,null,function*(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.recordsInfoByRoom.get(e);if(t){let i=yield this._getParticipantId(t.initiator);g.onRecordStarted(i,t.recordMovieId,t.recordStartTime,t.recordType,t.recordExternalMovieId,t.recordExternalOwnerId,e)}else g.onRecordStopped(e)})}_onAsrInfo(e){return o(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.asrInfo!=!e?t=!0:this._conversation.asrInfo&&e&&(t=this._conversation.asrInfo.movieId!==e.movieId),t)if(e){let i=yield this._getParticipantId(e.initiatorId);g.onAsrStarted(i,e.movieId)}else g.onAsrStopped();this._conversation.asrInfo=e})}_onAsrTranscription(e){return o(this,null,function*(){if(!this._conversation)return;let t=yield this._getParticipantId(e.participantId);g.onAsrTranscription(t,e.text,e.timestamp,e.duration)})}_onRolesChanged(e,t){if(this._conversation&&this._isMe(e)&&!Nt(this._conversation.roles,t)){c.debug(`Local roles changed: ${t}`),this._conversation.roles=t,g.onLocalRolesChanged(t),this._processMuteState({mediaOptions:Dt(this._getMuteStatesForCurrentRoom(),Oe.MUTE_PERMANENT),stateUpdated:!0}),v.includesOneOf(t,[Xe.ADMIN,Xe.CREATOR])&&this._refreshRooms(!0);return}let i=this._participants[e];i&&!Nt(i.roles,t)&&(c.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,g.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){var u;if(!this._conversation)return;let i=(u=e.roomId)!=null?u:null,r=e.muteStates||{},a=e.unmuteOptions||[],s=e.mediaOptions||[],d=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&!this._isMe(e.participantId)){if(!this._isCallAdmin()){c.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let E=this._participants[e.participantId];E&&(c.debug(`Mute states for participant [${e.participantId}] changed`,r),g.onMuteStates(r,a,s,e.muteAll,e.unmute,E.externalId,d==null?void 0:d.externalId,e.stateUpdated,e.requestedMedia,e.roomId));return}let l=this._getMuteStatesForRoomId(i);if(!(v.isObjectsEquals(l,r)&&v.isArraysEquals(this._conversation.unmuteOptions,a)&&!s.length)){if(this._setMuteStatesForRoomId(r,i),this._conversation.unmuteOptions=a,this._isMe(e.adminId)){e.muteAll&&g.onMuteStates(r,a,s,e.muteAll,e.unmute,null,this._conversation.externalId,e.stateUpdated,e.requestedMedia,e.roomId);return}yield this._processMuteState({mediaOptions:s,muteAll:e.muteAll,unmute:e.unmute,serverSettings:t,admin:d,stateUpdated:e.stateUpdated,requestedMedia:e.requestedMedia,roomId:e.roomId})}})}_changeMuteStatesForRoom(e){if(!this._conversation)return;this._conversation.unmuteOptions=[];let t=this._getMuteStatesForRoomId(e),i=Object.keys(t);g.onMuteStates(this._getMuteStatesForCurrentRoom(),[],i,!0,!1,null,null,!0,void 0,this._conversation.roomId)}_processMuteState(u){return o(this,arguments,function*({mediaOptions:e=[],muteAll:t=!1,unmute:i=!1,serverSettings:r=null,admin:a=null,stateUpdated:s,requestedMedia:d,roomId:l=null}){if(!this._conversation||!this._mediaSource||this._participantState!==K.ACCEPTED)return;let E=Object.assign({},this._getMuteStatesForRoomId(l)),C=this._conversation.unmuteOptions,M=this._mediaSource.getMediaSettings(),O=Object.entries(E);for(let[w,F]of O)if(!(F!==Oe.MUTE&&F!==Oe.MUTE_PERMANENT)&&(this._isCallAdmin()&&F===Oe.MUTE_PERMANENT&&!t&&(E[w]=Oe.MUTE),!(!e.includes(w)||i)))switch(w){case le.VIDEO:M.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(g.onDeviceSwitched(le.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case le.AUDIO:M.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(g.onDeviceSwitched(le.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case le.SCREEN_SHARING:M.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(g.onDeviceSwitched(le.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1,!1));break;case le.AUDIO_SHARING:M.isAudioSharingEnabled&&!(r==null?void 0:r.isAudioSharingEnabled)&&(g.onDeviceSwitched(le.AUDIO_SHARING,!1),yield this.toggleScreenCapturing(M.isScreenSharingEnabled,!1));break}g.onMuteStates(E,C,e,t,i,null,a==null?void 0:a.externalId,s,d,l)})}_onPinParticipant(e,t=!1,i){return o(this,null,function*(){if(!this._conversation)return;let r=this._conversation.pinnedParticipantId;if(r&&r!==e)if(this._isMe(r))g.onLocalPin(!0);else{let a=yield this._getExternalIdByParticipantId(r);a&&g.onPinnedParticipant(a,!0,this._denormalizeMarkers(e,i))}if(this._isMe(e))g.onLocalPin(t);else{let a=yield this._getExternalIdByParticipantId(e);a&&g.onPinnedParticipant(a,t,this._denormalizeMarkers(e,i))}this._conversation.pinnedParticipantId=t?null:e})}_onOptionsChanged(e){this._conversation&&!Vr(this._conversation.options,e)&&(this._conversation.options=e,g.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let a;if(this._isMe(i)||i==="")a=this._conversation.networkRating;else if(this._participants[i])a=this._participants[i].networkRating;else continue;if(a!==r)if(this._isMe(i)||i==="")this._conversation.networkRating=r,g.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;c.log("Received network status update: ",e),g.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(p.producerScreenTrack){g.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,p.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){c.error("Received remote stream notification for a participant that has no track associated with it",r);return}let a=this._streamIdByStreamDescription.get(r);if(!a||this._streamWaitTimerByStreamDescription.has(r)){c.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(a);if(!s){f.log(T.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}g.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&g.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===oe.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(ri.ADD_PARTICIPANT);g.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&g.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let a=this._participants[i];a&&a.externalId&&t.push({uid:a.externalId,volume:r.real})}g.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){c.debug(`Transport state has changed: ${t}`,e);let i=this._getStatusByTransportState(t);if(!i)return;let r=e.reduce((a,s)=>{if(s in this._participants){let d=this._participants[s];a.push(d),t===H.CONNECTED&&(d.remoteStream||(d.mediaSettings&&this._changeRemoteMediaSettings(s,d.mediaSettings),this._changeRemoteParticipantState(s,d.participantState)),this._updateDisplayLayoutFromCache(s))}else this._warnParticipantNotInConversation(s);return a},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){var t;if(c.debug(`Local transport state has changed: ${e}`),e===H.CONNECTED&&(g.onLocalStatus(J.CONNECTED),((t=this._transport)==null?void 0:t.getTopology())===oe.SERVER)){let i=Object.values(this._myLastRequestedLayouts);yield this.updateDisplayLayout(i)}e===H.CONNECTING&&g.onLocalStatus(J.CONNECTING),e===H.RECONNECTING&&g.onLocalStatus(J.RECONNECT),e===H.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(D.FAILED)),this._close(new B(D.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(Be.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i),g.onRemoteMixedAudioStream(t);else if(e.startsWith(Be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))c.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{c.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(c.warn(`Conversation: track added before participant [${e}]`),r=this._registerParticipantInCache(yield this._createParticipant({id:e})),this._setParticipantsStatus([r],J.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===pe.audio&&(this._audioOutput.add(i),p.preserveAudioTracks||t.removeTrack(i)),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;g.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),p.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(c.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case pe.audio:this._removeAudioTrack(e,t,i);break;case pe.video:case pe.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Be.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e===oe.DIRECT&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let a=this._participants[r];e||this._lastStalled[r]?t.push(a):i.push(a)}t.length&&this._setParticipantsStatus(t,J.RECONNECT),i.length&&this._setParticipantsStatus(i,J.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(a=>{if(t[a]=!0,!this._lastStalled[a]){let s=this._participants[a];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[a]}),Object.keys(this._lastStalled).forEach(a=>{let s=this._participants[a];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,J.RECONNECT),r.length&&this._setParticipantsStatus(r,J.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!y.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(c.debug("Toggle join availability",{available:t,chatId:e}),g.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==oe.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((a,s)=>(s.status!==t&&(s.status=t,p.batchParticipantsOnStart?a.push(s.externalId):g.onParticipantStatus(s.externalId,t,i)),a),[]);!r.length||p.batchParticipantsOnStart&&g.onRemoteStatus(r,t,i)}_onJoinLinkChanged(e){g.onJoinLinkChanged(e.joinLink)}_onRoomsUpdated(e){return o(this,null,function*(){var i,r;let t={};for(let a of Object.keys(Et)){let s=e.updates[a];!s||(t[a]={rooms:yield Promise.all(((r=(i=s==null?void 0:s.rooms)==null?void 0:i.map)==null?void 0:r.call(i,this._convertRoomToExternal.bind(this)))||[]),roomIds:s==null?void 0:s.roomIds,deactivated:s==null?void 0:s.deactivated})}g.onRoomsUpdated(t)})}_onRoomUpdated(e){return o(this,null,function*(){let t=yield this._convertRoomToExternal(e.room);e.events.some(i=>i===Et.UPDATE)&&(e.muteStates!==void 0&&this._setMuteStatesForRoomId(e.muteStates,e.roomId),e.recordInfo!==void 0&&this._conversation.recordsInfoByRoom.set(e.roomId,e.recordInfo)),g.onRoomUpdated(e.events,e.roomId,t,e.deactivate)})}_convertRoomToExternal(e){return o(this,null,function*(){var a,s,d,l,u,E;if(!e)return null;let[t,i,r]=yield Promise.all([Promise.all(((s=(a=e==null?void 0:e.participantIds)==null?void 0:a.map)==null?void 0:s.call(a,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((l=(d=e==null?void 0:e.addParticipantIds)==null?void 0:d.map)==null?void 0:l.call(d,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((E=(u=e==null?void 0:e.removeParticipantIds)==null?void 0:u.map)==null?void 0:E.call(u,this._getExternalIdByParticipantId.bind(this)))||[])]);return{id:e.id,name:e.name,participantCount:e.participantCount,participantIds:t,addParticipantIds:i,removeParticipantIds:r,participants:e.participants,active:e.active,muteStates:e.muteStates}})}_onRoomParticipantsUpdated(e){return o(this,null,function*(){var E,C,M,O,w;let t=this._transport.getState(),i=(E=e.roomId)!=null?E:null,[r,a]=yield Promise.all([Promise.all(((M=(C=e.addedParticipantIds)==null?void 0:C.map)==null?void 0:M.call(C,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((w=(O=e==null?void 0:e.addedParticipants)==null?void 0:O.map)==null?void 0:w.call(O,F=>o(this,null,function*(){var q;let de=v.composeId(F);return this._createParticipant({id:de,externalId:F.externalId&&fe.fromSignaling(F.externalId,F.deviceIdx||0),mediaSettings:ge(F.mediaSettings),participantState:v.mapParticipantState(F),state:F.state,roles:F.roles||[],status:(q=this._getStatusByTransportState(t))!=null?q:J.WAITING,muteStates:F.muteStates||{},unmuteOptions:F.unmuteOptions||[],observedIds:F.observedIds||[],markers:this._denormalizeMarkers(de,F.markers)})})))||[])]),s=!1;for(let F of a)F.id===this._conversation.compositeUserId&&(s=!0),this._registerParticipantInCache(F);this._openTransport(a,!0);let d=[],l=[];if(e==null?void 0:e.removedParticipantMarkers){for(let F of e.removedParticipantMarkers)F.GRID&&l.push(this._getExternalIdByParticipantId(F.GRID.id));d=yield Promise.all(l)}s&&this._onRoomSwitched(i);let u={roomId:i,participantCount:e.participantCount,addedParticipantIds:r,addedParticipants:v.mapSharedParticipants(a),removedParticipantMarkers:e==null?void 0:e.removedParticipantMarkers,removedParticipantIds:d};g.onRoomParticipantsUpdated(u)})}_onRoomSwitched(e,t=!1){if(!this._conversation||this._conversation.roomId===e)return;let i=this._conversation.roomId;if(this._conversation.roomId=e,t){g.onRoomStart(e);return}g.onRoomSwitched(e),e!==null&&!this._isCallAdmin()&&this._refreshRooms(!1),this._changeRecordInfoForRoom(),this._changeMuteStatesForRoom(i)}_refreshRooms(e){return o(this,null,function*(){var r,a;let i=(a=(r=(yield this._signaling.getRooms(e)).rooms)==null?void 0:r.rooms)!=null?a:[];for(let s of i)this._setMuteStatesForRoomId(s.muteStates,s.id),this._conversation.recordsInfoByRoom.set(s.id,s.recordInfo);e&&g.onRoomsUpdated({[Et.UPDATE]:{rooms:yield Promise.all(i.map(this._convertRoomToExternal.bind(this)))}})})}_onFeedback(e){return o(this,null,function*(){let t=a=>o(this,null,function*(){return(yield this._registerParticipantAndSetMarkersIfChunkEnabled(a)).externalId}),i=e.feedback.map(a=>o(this,null,function*(){let s=a.items.map(l=>o(this,null,function*(){if(l.participantId===this._conversation.compositeUserId)return Promise.resolve(gt(Ue({},l),{participantId:this._conversation.externalId}));let u=yield t(l.participantId);return gt(Ue({},l),{participantId:u})})),d=yield Promise.all(s);return gt(Ue({},a),{items:d})})),r=yield Promise.all(i);g.onFeedback(r,e.roomId)})}_isMe(e){var t;return e===((t=this._conversation)==null?void 0:t.compositeUserId)}_getMuteStatesForRoomId(e=null){var i;return(i=this._conversation.muteStates.get(e))!=null?i:{}}_getMuteStatesForCurrentRoom(){return this._getMuteStatesForRoomId(this._conversation.roomId)}_setMuteStatesForRoomId(e={},t=null){this._conversation.muteStates.set(t,e)}},N=$;N._delayedHangup=!1;var Mi=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Mi.prototype),this.participantErrors=t}};var Ot,Qt=null;function vs(){return o(this,null,function*(){var n;if(p.apiEnv!=="AUTO")return p.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(n=i==null?void 0:i.Answer[0])==null?void 0:n.data;if(!r)throw new Error("Wrong DNS response");return c.debug("Resolved API endpoint",r),r}catch(e){return c.warn("Failed to resolve API endpoint using DNS, default is used",e),p.apiEndpoint}})}function Na(){return o(this,null,function*(){return Ot||Qt||(Qt=vs(),Ot=yield Qt,Qt=null,Ot)})}function Ua(){if(!p.apiKey)throw new B(se.API,{message:"Required argument apiAppKey not passed"})}function Tr(i){return o(this,arguments,function*(n,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;yield Na();let r=Fa(n,e,t),a=new window.Blob([r],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${Ot}/fb.do`,a)})}function Ba(i){return o(this,arguments,function*(n,e={},t=!1){yield Na();let r=Fa(n,e,t);return Es(r)})}function Es(n){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${Ot}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(a){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(n)})})}function Fa(n,e={},t=!1){e.method=n,e.format="JSON",e.application_key||(e.application_key=p.apiKey),t||(ne.sessionKey?e.session_key=ne.sessionKey:ne.accessToken&&(e.access_token=ne.accessToken));for(let[r,a]of Object.entries(e))typeof a=="object"&&(e[r]=JSON.stringify(a));let i="";for(let[r,a]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(a)}`;return i}var Ts=10,Cs=700,Rs=3e3,Xt=class extends ft{constructor(){super(...arguments);this._userId=null;this._externalUidsCache=new Map;this._extrnalUidsBatch=new Set;this._extrnalUidsBatchTimeout=null}_callUnsafe(r){return o(this,arguments,function*(e,t={},i=!1){let a=s=>o(this,null,function*(){try{return yield Ba(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<Ts))return yield v.delay(Math.min(s*Cs,Rs)),a(s);throw c.warn(e,"error",d),d}});return a(0)})}_call(r){return o(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(a){c.warn("Api call error",a);let s=se.API;switch(a.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=D.SERVICE_DISABLED;break;case 1102:s=D.CALLEE_IS_OFFLINE;break;case 1103:s=D.NOT_FRIENDS;break;case 1104:case 1106:s=D.EXTERNAL_API_ERROR;break;case 1113:s=D.CALLER_IS_REJECTED;break}throw new B(s,{message:a.error_msg,code:a.error_code})}})}userId(e){return o(this,null,function*(){let t=v.decomposeId(e).id;return ne.isEmpty()?ve.fromId(String(t)):(yield this._prepareUserIdsByOkIdsBatched([t]),ve.fromString(this._externalUidsCache.get(t)))})}prepareUserIds(e){return o(this,null,function*(){ne.isEmpty()||(yield this._prepareUserIdsByOkIdsBatched(e))})}_prepareUserIdsByOkIdsBatched(e){return e.some(i=>!this._externalUidsCache.has(i))?(e.forEach(i=>this._extrnalUidsBatch.add(i)),this._extrnalUidsBatchTimeout||(this._extrnalUidsBatchPromise=new Promise(i=>{this._extrnalUidsBatchTimeout=window.setTimeout(()=>{if(this._extrnalUidsBatch.size>0){let r=[...this._extrnalUidsBatch];this._extrnalUidsBatch.clear(),this._getExternalIdsByOkIds(r).then(a=>{for(let s in a)!a.hasOwnProperty(s)||this._externalUidsCache.set(parseInt(s,10),a[s]);i()})}this._extrnalUidsBatchTimeout=null},p.api.userIdsByOkBatchedTimeout)})),this._extrnalUidsBatchPromise):Promise.resolve()}authorize(){return o(this,null,function*(){if(!this._uuid){let t=et.get("uuid");t||(t=v.uuid(),et.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:p.appVersion,client_type:"SDK_JS"}};return p.authToken&&(e.session_data.auth_token=p.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),ne.sessionKey=t.session_key,ne.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&g.onTokenExpired(),new B(se.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${p.appName}:${p.sdkVersion}`,platform:p.platform,items:e})};Tr("log.externalLog",t)}init(){Ua()}joinConversation(e,t=!1,i){return o(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:p.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(a){return o(this,arguments,function*(e,t="",i=!1,{onlyAdminCanShareMovie:r}={}){let s=this._preareStartConversationData({conversationId:e,isVideo:!1,joiningAllowed:!0,payload:t,requireAuthToJoin:i,onlyAdminCanShareMovie:r});return this._startConversation(s)})}startConversation(u,E,C){return o(this,arguments,function*(e,t,i,r=!1,a="",s=!1,d=!1,{onlyAdminCanShareMovie:l}={}){let M=this._preareStartConversationData({conversationId:e,isVideo:r,joiningAllowed:s,payload:a,requireAuthToJoin:d,onlyAdminCanShareMovie:l});if(t&&t.length)switch(i){case je.USER:M.uids=t.join(",");break;case je.GROUP:M.gid=t[0];break;case je.CHAT:M.chatId=t[0];break}return this._startConversation(M)})}_preareStartConversationData({conversationId:e,isVideo:t,payload:i="",joiningAllowed:r=!1,requireAuthToJoin:a=!1,onlyAdminCanShareMovie:s}){let d={conversationId:e,isVideo:t,protocolVersion:p.protocolVersion};return r&&(d.createJoinLink=!0),i&&(d.payload=i),p.domain&&(d.domainId=p.domain),p.externalDomain&&(d.externalDomain=p.externalDomain),a&&(d.requireAuthToJoin=!0),s!==void 0&&(d.onlyAdminCanShareMovie=s),d}_startConversation(e){return o(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return o(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return o(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return o(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i,r){return o(this,null,function*(){let a={joinLink:e,isVideo:t,protocolVersion:p.protocolVersion};return(i==null?void 0:i.length)&&(a.observedIds=i.join(",")),p.anonymToken&&(a.anonymToken=p.anonymToken),r&&(a.payload=r),this._call("vchat.joinConversationByLink",a)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=ve.fromIds(e),i=[],r={methods:[]},a=[],s=[...this._externalUidsCache.keys()],d=[...this._externalUidsCache.values()];for(let u of t){let E=ve.toString(u),C=d.indexOf(E);C>-1?i.push(Number(s[C])):(a.push(E),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:u.id,anonym:u.type===lt.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((u,E)=>{if(u.ok){let C=Number(u.ok.ok_id);this._externalUidsCache.set(C,a[E]),i.push(C)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let a of e)this._externalUidsCache.has(a)?t.push(ve.fromString(this._externalUidsCache.get(a))):i.push(a);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);for(let a in r)!r.hasOwnProperty(a)||this._externalUidsCache.set(parseInt(a,10),r[a]);for(let a of i)r.hasOwnProperty(a)&&t.push(ve.fromString(r[a]));return t})}getCachedOkIdByExternalId(e){let t=[...this._externalUidsCache.keys()],i=[...this._externalUidsCache.values()],r=ve.toString(e),a=i.indexOf(r);return a>-1?v.composeUserId(t[a],te.USER):null}cacheExternalId(e,t){let i=v.decomposeId(e).id;this._externalUidsCache.set(i,ve.toString(t))}getConversationParams(e){return o(this,null,function*(){let t={};return p.anonymToken&&(t.anonymToken=p.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:D.HUNGUP};p.anonymToken&&(t.anonymToken=p.anonymToken),Tr("vchat.hangupConversation",t)}removeHistoryRecords(e){return o(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return o(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,a]of Object.entries(i.external_ids))t[r]=ve.fromIdToString(a,lt.USER);if(i.anonym_ids)for(let[r,a]of Object.entries(i.anonym_ids))t[r]=ve.fromIdToString(a,lt.ANONYM);return t}catch(i){return t}})}};var Cr=class{requestAsr(e){let t=new ArrayBuffer(2),i=new DataView(t);return i.setUint8(0,1),i.setUint8(1,e?0:1),t}};var G=nt(require("messagepack"));var Va=(L=>(L.RECOVER="recover",L.ACCEPT_CALL="accept-call",L.ADD_PARTICIPANT="add-participant",L.REMOVE_PARTICIPANT="remove-participant",L.HANGUP="hangup",L.TRANSMIT_DATA="transmit-data",L.ACCEPT_PRODUCER="accept-producer",L.ALLOCATE_CONSUMER="allocate-consumer",L.CHANGE_MEDIA_SETTINGS="change-media-settings",L.CHANGE_PARTICIPANT_STATE="change-participant-state",L.CHANGE_STREAM_PRIORITIES="change-streams-priorities",L.UPDATE_DISPLAY_LAYOUT="update-display-layout",L.REPORT_PERF_STAT="report-perf-stat",L.REPORT_SHARING_STAT="report-sharing-stat",L.RECORD_START="record-start",L.RECORD_STOP="record-stop",L.RECORD_SET_ROLE="record-set-role",L.RECORD_GET_STATUS="record-get-status",L.SWITCH_MICRO="switch-micro",L.SWITCH_TOPOLOGY="switch-topology",L.REQUEST_REALLOC="request-realloc",L.CHAT_MESSAGE="chat-message",L.CHAT_HISTORY="chat-history",L.CUSTOM_DATA="custom-data",L.GRANT_ROLES="grant-roles",L.MUTE_PARTICIPANT="mute-participant",L.ENABLE_FEATURE_FOR_ROLES="enable-feature-for-roles",L.PIN_PARTICIPANT="pin-participant",L.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",L.CHANGE_OPTIONS="change-options",L.GET_WAITING_HALL="get-waiting-hall",L.GET_PARTICIPANT_LIST_CHUNK="get-participant-list-chunk",L.GET_PARTICIPANTS="get-participants",L.PROMOTE_PARTICIPANT="promote-participant",L.REQUEST_TEST_MODE="request-test-mode",L.ADD_MOVIE="add-movie",L.UPDATE_MOVIE="update-movie",L.REMOVE_MOVIE="remove-movie",L.GET_ROOMS="get-rooms",L.UPDATE_ROOMS="update-rooms",L.ACTIVATE_ROOMS="activate-rooms",L.REMOVE_ROOMS="remove-rooms",L.SWITCH_ROOM="switch-room",L.FEEDBACK="feedback",L.ASR_START="asr-start",L.ASR_STOP="asr-stop",L.REQUEST_ASR="request-asr",L))(Va||{}),x=Va;function Zt(){let n=new DataView(new ArrayBuffer(64)),e=0;function t(i){if(e+i>n.byteLength){let r=new Uint8Array(Math.max(e+i,n.byteLength+64));r.set(new Uint8Array(n.buffer.slice(0,e))),n=new DataView(r.buffer)}}return{put(i){if(t(i.byteLength),ys(i)){let r=i.buffer;new Uint8Array(n.buffer).set(new Uint8Array(r),e)}else new Uint8Array(n.buffer).set(new Uint8Array(i),e);e+=i.byteLength},putI8(i){t(1),n.setInt8(e,i),++e},putI16(i){t(2),n.setInt16(e,i),e+=2},putI32(i){t(4),n.setInt32(e,i),e+=4},putI64(i){t(8);let r=i<0;r&&(i=-i);let a=i/4294967296|0,s=i%4294967296|0;r&&(s=~s+1|0,a=s===0?~a+1|0:~a),n.setUint32(e,a),n.setUint32(e+4,s),e+=8},putUi8(i){t(1),n.setUint8(e,i),++e},putUi16(i){t(2),n.setUint16(e,i),e+=2},putUi32(i){t(4),n.setUint32(e,i),e+=4},putUi64(i){t(8),n.setUint32(e,i/4294967296|0),n.setUint32(e+4,i%4294967296),e+=8},putF(i){t(8),n.setFloat64(e,i),e+=8},ui8array(){return new Uint8Array(n.buffer.slice(0,e))}}}function ys(n){return n.buffer!==void 0}function Ai(n){let e=ArrayBuffer.isView(n)?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),t=0;return{peek(){return e.getUint8(t)},get(i){t+=i;let r=e.byteOffset;return e.buffer.slice(r+t-i,r+t)},getI8(){return e.getInt8(t++)},getI16(){return t+=2,e.getInt16(t-2)},getI32(){return t+=4,e.getInt32(t-4)},getI64(){t+=8;let i=e.getInt32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getUi8(){return e.getUint8(t++)},getUi16(){return t+=2,e.getUint16(t-2)},getUi32(){return t+=4,e.getUint32(t-4)},getUi64(){t+=8;let i=e.getUint32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getF32(){return t+=4,e.getFloat32(t-4)},getF64(){return t+=8,e.getFloat64(t-8)}}}var Ha=0,Ga=1,Ps=2,bs=0,Ms=1,As=2,Di=0,Ds=0,ks=0,Os=1,Rr=class{constructor(){this.participantIdRegistry=null}setParticipantIdRegistry(e){this.participantIdRegistry=e}serializeUpdateDisplayLayout(e,t){let i=Zt();G.Int.enc(i,Ha),G.Int.enc(i,Di),G.Int.enc(i,e),G.Nil.enc(i,null);let r=[];for(let a in t)t.hasOwnProperty(a)&&this.writeLayout(t,a,r);return G.Arr.enc(i,r),G.Nil.enc(i,null),i.ui8array()}writeLayout(e,t,i){let r=e[t],a=Zt();if(this.writeStreamDesc(t,a),Kt(r))G.Int.enc(a,Ms);else if(mr(r))G.Int.enc(a,As);else if(G.Int.enc(a,bs),r.priority!==void 0?G.Int.enc(a,r.priority):G.Nil.enc(a,null),r.width!==void 0&&r.height!==void 0?(G.Int.enc(a,Math.round(r.width)),G.Int.enc(a,Math.round(r.height))):(G.Nil.enc(a,null),G.Nil.enc(a,null)),r.fit!==void 0)switch(r.fit){case"cv":G.Int.enc(a,ks);break;case"cn":G.Int.enc(a,Os);break;default:G.Nil.enc(a,null)}else G.Nil.enc(a,null);i.push(a.ui8array())}writeStreamDesc(e,t){if(this.participantIdRegistry){let i=this.participantIdRegistry.getCompactId(e);if(i!==void 0){G.Int.enc(t,i);return}}G.Str.enc(t,e)}serializePerfStatReport(e,t){let i=Zt();return G.Int.enc(i,Ga),G.Int.enc(i,Di),G.Int.enc(i,e),G.Int.enc(i,t.framesDecoded),G.Int.enc(i,t.framesReceived),i.ui8array()}serializeSharingStatReport(e,t){let i=Zt();return G.Int.enc(i,Ps),G.Int.enc(i,Di),G.Int.enc(i,e),G.Int.enc(i,t.minDelay),G.Int.enc(i,t.maxDelay),G.Int.enc(i,t.avgDelay),G.Int.enc(i,t.largeDelayDuration),i.ui8array()}deserializeCommandResponse(e){return o(this,null,function*(){let t;if(e instanceof Blob){let s=Blob.prototype.arrayBuffer?yield e.arrayBuffer():yield _a(e);t=Ai(s)}else t=Ai(e);let i=G.Int.dec(t),r=G.Int.dec(t);if(r!==Di){c.warn("Unsupported version for command type: "+i+", version "+r);return}if(G.Int.dec(t)!==Ds){c.warn("Error code: "+i+"received for command type: "+i+", version "+r);return}switch(i){case Ha:return this.deserializeUpdateDisplayLayoutResponse(t);case Ga:return this.deserializeReportPerfStatResponse(t);default:return c.warn("unsupported command response commandType: "+i),null}})}deserializeUpdateDisplayLayoutResponse(e){let t=G.Int.dec(e),i=G.Arr.dec(e),r={};return i.forEach(a=>{let s=Ai(a),d=G.Any.dec(s);if(typeof d=="string")r[d]=G.Int.dec(s);else{let l=d,u=qe(this.participantIdRegistry.getStreamDescription(l));r[u]=G.Int.dec(s)}}),{type:"response",sequence:t,response:x.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:r}}deserializeReportPerfStatResponse(e){let t=G.Int.dec(e),i=G.Int.dec(e);return{type:"response",sequence:t,response:x.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:i}}};var ki="open",Wa=[()=>p.producerScreenTrack,()=>p.videoTracksCount>0,()=>!0,()=>p.filteredMessages,()=>p.consumerScreenTrack,()=>!0,()=>p.movieShare,()=>p.useParticipantListChunk,()=>p.useRooms],ws=10,we=class extends vt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.asrCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+p.platform+"&appVersion="+p.appVersion+"&version="+p.protocolVersion+"&device="+p.device+"&capabilities="+we._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null;this.asrDataChannel=null;this.producerCommandDataChannelEnabled=!1;this.producerCommandSerializationService=new Rr;this.asrCommandSerializer=new Cr}static _getCapabilityFlags(){let e=0;for(let t=0;t<Wa.length;t++)Wa[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e,this.producerCommandSerializationService.setParticipantIdRegistry(e)}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=t=>{this.producerCommandSerializationService.deserializeCommandResponse(t.data).then(i=>{i&&this._handleMessage(i)}).catch(i=>{c.warn("Cannot parse message at producerCommandDataChannel",i)})},this._handleCommandsQueue(this.datachannelCommandsQueue)}useCommandDataChannel(e){this.producerCommandDataChannelEnabled=e}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return o(this,null,function*(){return this.postfix+=`&clientType=${p.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){f.log(T.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return o(this,arguments,function*(e,t={},i=0){if(t.participantId){let a=v.decomposeParticipantId(t.participantId),s=v.decomposeId(a.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),a.deviceIdx&&(t.deviceIdx=a.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return o(this,arguments,function*(e,t={},i=0){let a=s=>{var d,l;if(e===x.REQUEST_ASR)this.asrCommandsQueue.push(s),((d=this.asrDataChannel)==null?void 0:d.readyState)===ki&&this._handleCommandsQueue(this.asrCommandsQueue);else if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===ki&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){f.log(T.SOCKET_ACTION,"not_opened"),c.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(f.log(T.SOCKET_ACTION,"invalid_state"),c.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,d)=>{let l=(E,C=!1)=>{!i||C?d(E):(c.debug("Resending a signaling message",e,u.sequence),i--,a(u))},u={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};a(u)})})}_isDataChannelCommand(e){return this.producerCommandDataChannelEnabled?e===x.UPDATE_DISPLAY_LAYOUT||e===x.REPORT_PERF_STAT||e===x.REPORT_SHARING_STAT:!1}static _isDataChannelResponseRequired(e){return e===x.UPDATE_DISPLAY_LAYOUT||e===x.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(x.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(x.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e,t){return o(this,null,function*(){return this._send(x.REQUEST_TEST_MODE,{consumer:e,producer:t})})}sendSdp(e,t){return o(this,null,function*(){return this._send(x.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(x.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(x.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},ws)})}changeParticipantState(e){return o(this,null,function*(){return this._send(x.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(x.ADD_PARTICIPANT,Ue({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(x.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return o(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(x.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(x.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(x.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(x.UPDATE_DISPLAY_LAYOUT,e)})}addMovie(e){return o(this,null,function*(){return this._send(x.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(x.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(x.REMOVE_MOVIE,e)})}updateRooms(e,t){return o(this,null,function*(){return this._send(x.UPDATE_ROOMS,{rooms:e,assignRandomly:t})})}activateRooms(e,t){return o(this,null,function*(){return this._send(x.ACTIVATE_ROOMS,{roomIds:e,deactivate:t})})}switchRoom(e,t){return o(this,null,function*(){return this._sendRaw(x.SWITCH_ROOM,{toRoomId:e,participantId:t})})}getRooms(e){return o(this,null,function*(){return this._sendRaw(x.GET_ROOMS,{withParticipants:e})})}removeRooms(e){return o(this,null,function*(){return this._send(x.REMOVE_ROOMS,{roomIds:e})})}startStream(e){return o(this,null,function*(){return this._send(x.RECORD_START,e)})}stopStream(){return o(this,arguments,function*(e={roomId:null}){return this._send(x.RECORD_STOP,e)})}recordSetRole(e,t,i=null){return o(this,null,function*(){return this._send(x.RECORD_SET_ROLE,{participantId:e,role:t,roomId:i})})}getRecordStatus(){return o(this,null,function*(){return this._send(x.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(x.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(x.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(x.REPORT_PERF_STAT,e)})}reportSharingStat(e){return o(this,null,function*(){return this._send(x.REPORT_SHARING_STAT,e)})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(x.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(x.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(x.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return o(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(x.GRANT_ROLES,r)})}muteParticipant(e,t,i,r=null){return o(this,null,function*(){return this._sendRaw(x.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i,roomId:r})})}enableFeatureForRoles(e,t){return o(this,null,function*(){return this._sendRaw(x.ENABLE_FEATURE_FOR_ROLES,{feature:e,roles:t})})}pinParticipant(e,t){return o(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(x.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(x.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(x.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return o(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(x.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(x.PROMOTE_PARTICIPANT,i)})}feedback(e){return o(this,null,function*(){return this._sendRaw(x.FEEDBACK,{key:e})})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}getParticipantListChunk(e){return o(this,null,function*(){return this._send(x.GET_PARTICIPANT_LIST_CHUNK,e)})}getParticipants(e){return o(this,null,function*(){return this._send(x.GET_PARTICIPANTS,{externalIds:e})})}startAsr(){return o(this,null,function*(){return this._send(x.ASR_START)})}stopAsr(){return o(this,null,function*(){return this._send(x.ASR_STOP)})}requestAsr(e){return o(this,null,function*(){return this._send(x.REQUEST_ASR,{request:e})})}setAsrDataChannel(e){this.asrDataChannel=e,this._handleCommandsQueue(this.asrCommandsQueue)}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ke.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),t=i(t),c.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor();function i(r){if(!p.useParticipantListChunk)return r;r+=`&partIdx=${p.participantListChunkInitIndex}`;let s=p.participantListChunkInitCount;return s!==null&&(r+=`&partCount=${s}`),r}}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){c.debug("Socket opened"),f.log(T.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){f.log(T.SOCKET_ACTION,"parse_error"),c.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(c.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(Te.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Te.NOTIFICATION,{type:"notification",notification: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(Te.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(f.log(T.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(f.log(T.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new B(D.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(Te.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 B(se.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(f.log(T.SOCKET_ACTION,"unknown_message"),c.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(Te.FAILED,e)}_onError(e){f.log(T.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){f.log(T.SOCKET_ACTION,"closed"),c.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<we.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(we.RECONNECT_MAX_DELAY,we.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),f.log(T.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ke.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],f.log(T.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),we.WAIT_RESPONSE_DELAY)}_serializeAsrCommand(e){let t=e.params;return this.asrCommandSerializer.requestAsr(t.request)}_handleCommandsQueue(e){var t,i,r,a;for(;e.length>0;){let s=e.shift();if(s.name===x.REQUEST_ASR){if(((t=this.asrDataChannel)==null?void 0:t.readyState)!==ki){s.reject(new Error(`Invalid data channel state: ${(i=this.asrDataChannel)==null?void 0:i.readyState}`));return}let d=this._serializeAsrCommand(s);d!==null&&this.asrDataChannel.send(d)}else if(this._isDataChannelCommand(s.name)){if(((r=this.producerCommandDataChannel)==null?void 0:r.readyState)!==ki){s.reject(new Error(`Invalid data channel state: ${(a=this.producerCommandDataChannel)==null?void 0:a.readyState}`));return}we._isDataChannelResponseRequired(s.name)&&(s.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:s.name,sequence:s.sequence}),we.WAIT_RESPONSE_DELAY),this.responseHandlers[s.sequence]=s);let d=this._serializeBinary(s);d!==null&&this.producerCommandDataChannel.send(d)}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){s.reject(new Error("Invalid state or socket already closed"));continue}s.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:s.name,sequence:s.sequence}),we.WAIT_RESPONSE_DELAY),this.responseHandlers[s.sequence]=s,this.socket.send(this._serializeJson(s))}}}_serializeBinary(e){switch(e.name){case x.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case x.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params);case x.REPORT_SHARING_STAT:return this.producerCommandSerializationService.serializeSharingStatReport(e.sequence,e.params)}return c.warn("cannot get binary data for data channel command: "+e.name),null}_serializeJson(e){let t;e.name===x.UPDATE_DISPLAY_LAYOUT?t=this._convertDisplayLayout(e.params):t=e.params;let i=Object.assign({command:e.name,sequence:e.sequence},t);return JSON.stringify(i)}_convertDisplayLayout(e){let t=e,i={};for(let r in t)t.hasOwnProperty(r)&&(i[r]=Ma(t[r]));return{layouts:i}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new B(se.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},we.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{c.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Ke.RETRY)},we.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},He=we;He.RECONNECT_DELAY=p.signalingReconnectDelay,He.RECONNECT_MAX_DELAY=p.signalingReconnectMaxDelay,He.RECONNECT_MAX_COUNT=p.signalingReconnectMaxCount,He.WAIT_CONNECTION_DELAY=p.waitConnectionDelay,He.WAIT_RESPONSE_DELAY=p.waitResponseDelay,He.WAIT_MESSAGE_DELAY=p.waitMessageDelay;var ja=(t=>(t.KING="KING",t.PAWN="PAWN",t))(ja||{}),Ka=ja;var yr=class{constructor(e){this._queue=new Array(e).fill(null),this._readCursor=this._writeCursor=this._left=0,this._moveReadCursor=!1}get length(){return this._queue.length}get left(){return this._left}toArray(){return Array.from(this._queue)}add(e){this._moveReadCursor&&(this._readCursor=this.nextCursor(this._readCursor)),this._queue[this._writeCursor]===null&&(this._left+=1),this._queue[this._writeCursor]=e,this._writeCursor=this.nextCursor(this._writeCursor),this._moveReadCursor=this._writeCursor===this._readCursor}nextCursor(e){return(e+1)%this._queue.length}next(){let e=this._queue[this._readCursor];return e&&(this._moveReadCursor=!1,this._queue[this._readCursor]=null,this._readCursor=this.nextCursor(this._readCursor),this._left-=1),e}};var wt,me,ei=null,xs={getCameras:y.getCameras,getMicrophones:y.getMicrophones,getOutput:y.getOutput,hasCamera:y.hasCamera,hasMicrophone:y.hasMicrophone,getSavedCamera:y.getSavedCamera,getSavedMicrophone:y.getSavedMicrophone,getSavedOutput:y.getSavedOutput,hasCameraPermission:y.hasCameraPermission,hasMicrophonePermission:y.hasMicrophonePermission,hasPermissions:y.hasPermissions,getUserMedia:y.getUserMedia,getUserVideo:y.getUserVideo,getUserAudio:y.getUserAudio,saveDeviceId:y.saveDeviceId,isBrowserSupported:y.isBrowserSupported,isScreenCapturingSupported:y.isScreenCapturingSupported,os:y.os,isMobile:y.isMobile,browserName:y.browserName,browserVersion:y.browserVersion,baseChromeVersion:y.baseChromeVersion,getAudioContext:y.getAudioContext};function $a(n){me=n}function qa(n){wt=n}function Ls(n){ei=n}function Ns(n){p.videoEffects=n}function Us(n){return o(this,null,function*(){if(p.set(n),y.browserName()==="Sferum"&&(p.platform=`SFERUM:${y.browserVersion()}`),me||$a(new Xt),wt||qa(()=>new He),p.debug&&(Pr.default.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${p.sdkVersion}`,n),yield y.init(),!y.isBrowserSupported())throw new B(se.UNSUPPORTED);c.log("UserAgent:",navigator.userAgent),c.log("Screen resolution:",`${window.screen.width}x${window.screen.height}`),c.log("Permissions:",`Camera: ${y.hasCameraPermission()}, Mic: ${y.hasMicrophonePermission()}`),me.init()})}function Bs(s){return o(this,arguments,function*(n,e=[le.AUDIO],t="",i=!1,r=!1,a){let d=[],l=[];if(Array.isArray(n)?d=n.length?n:[]:n&&(d=[n]),d.length&&(l=yield me.getOkIdsByExternalIds(d),!l.length))throw new B(D.CALLEE_IS_OFFLINE);return za(l,je.USER,e,t,i,r,a)})}function za(d){return o(this,arguments,function*(n,e=je.USER,t,i="",r=!1,a=!1,s){if(N.current())throw c.error("There is already active call"),new B(D.FAILED);return new N(me,wt(),ei).onStart(n,e,t,i,r,a,s)})}function Fs(n){return o(this,null,function*(){return Ja(n)})}function Ja(i){return o(this,arguments,function*(n,e=te.USER,t){if(n===N.id())throw new Error("Push has already been processed");return new N(me,wt(),ei).onPush(n,e,t)})}function Vs(n){return o(this,null,function*(){return n&&(p.authToken=n),me.authorize()})}function Hs(){return o(this,arguments,function*(n=[le.AUDIO]){return ht().accept(n)})}function Gs(){return o(this,null,function*(){let n=N.current();if(n)return n.decline()})}function Ws(t){return o(this,arguments,function*(n,e=[le.AUDIO]){return Ya(n,e)})}function Ya(n,e,t){return o(this,null,function*(){if(N.current())throw c.error("There is already active call"),new B(D.FAILED);return new N(me,wt(),ei).onJoin({conversationId:n,mediaOptions:e,chatId:t})})}function js(a){return o(this,arguments,function*(n,e=[le.AUDIO],t,i,r){if(N.current())throw c.error("There is already active call"),new B(D.FAILED);return t&&(p.anonymToken=t),new N(me,wt(),ei).onJoin({joinLink:n,mediaOptions:e,observedIds:i,payload:r})})}function Ks(){return o(this,null,function*(){let n=N.current();if(n)return n.hangup();N.hangupAfterInit()})}function $s(n,e){return o(this,null,function*(){let t=yield me.getOkIdsByExternalIds([n]);if(!t.length)throw new Error("User not found");return Qa(t[0],e)})}function Qa(n,e){return o(this,null,function*(){let t=N.current();t&&(yield t.addParticipant(v.composeUserId(n,te.USER),e))})}function qs(n,e=!1){return o(this,null,function*(){let t=yield me.getOkIdsByExternalIds([n]);return Xa(t[0],e)})}function Xa(n,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.removeParticipant(v.composeUserId(n,te.USER),e))})}function zs(n,e){return o(this,null,function*(){let t=yield y.saveDeviceId(n,e),i=N.current();return t&&i?i.changeDevice(n):Promise.reject()})}function Js(n){return o(this,null,function*(){return Za(n,!1)})}function Za(n,e){return o(this,null,function*(){if(e){if(!p.audioShareCapabilityEnabled)throw new Error("Audio share capability is disabled");if(!n)throw new Error("Audio share without screen share is not allowed")}let t=N.current();return t?t.toggleScreenCapturing(n,e):Promise.reject()})}function Ys(n,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.setVideoStream(n,e))})}function Qs(n){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalVideo(n))})}function Xs(n){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalAudio(n))})}function Zs(n,e,t){return o(this,null,function*(){let i=N.current();if(i)return i.setLocalResolution(n,e,t)})}function eo(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changePriorities(n))})}function to(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changeParticipantState(n))})}function io(n){return o(this,null,function*(){let e=N.current();e&&(yield e.updateDisplayLayout(n))})}function ro(n,e,t=!1){return o(this,null,function*(){let i=yield me.getOkIdsByExternalIds([n]);return en(i[0],e,t)})}function en(n,e,t=!1){return o(this,null,function*(){let i=N.current();i&&(yield i.grantRoles(v.composeUserId(n,te.USER),e,t))})}function ao(r){return o(this,arguments,function*({externalId:n=null,muteStates:e,requestedMedia:t=[],roomId:i=null}){let a=null;return n&&(a=(yield me.getOkIdsByExternalIds([n]))[0]),tn({uid:a,muteStates:e,requestedMedia:t,deviceIdx:fe.getDeviceIdx(n),roomId:i})})}function tn(a){return o(this,arguments,function*({uid:n=null,muteStates:e,requestedMedia:t=[],deviceIdx:i=0,roomId:r=null}){let s=N.current();if(s){let d=n?v.composeParticipantId(n,te.USER,i):null;yield s.muteParticipant(d,e,t,r)}})}function no(n,e=!1){return o(this,null,function*(){let t=yield me.getOkIdsByExternalIds([n]);return rn(t[0],e,fe.getDeviceIdx(n))})}function rn(n,e=!1,t=0){return o(this,null,function*(){let i=N.current();i&&(yield i.pinParticipant(v.composeParticipantId(n,te.USER,t),e))})}function so(n){return o(this,null,function*(){let e=N.current();e&&(yield e.updateMediaModifiers(n))})}function oo(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changeOptions(n))})}function co(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield me.getOkIdsByExternalIds([e]))[0]),an(n,t)})}function an(n,e=null){return o(this,null,function*(){let t=N.current();if(t){let i=e?v.composeUserId(e,te.USER):null;yield t.chatMessage(n,i)}})}function lo(n=10){return o(this,null,function*(){let e=N.current();if(e)return e.chatHistory(n)})}function po(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield me.getOkIdsByExternalIds([e]))[0]),nn(n,t,fe.getDeviceIdx(e))})}function nn(n,e=null,t=0){return o(this,null,function*(){let i=N.current();if(i){let r=e?v.composeParticipantId(e,te.USER,t):null;yield i.customData(n,r)}})}function uo(){return o(this,arguments,function*(n="",e=!1,{onlyAdminCanShareMovie:t=!1}={}){return(yield me.createConversation(v.uuid(),n,e,{onlyAdminCanShareMovie:t})).join_link})}function mo(){return o(this,null,function*(){let n=N.current();return n?n.createJoinLink():Promise.reject()})}function ho(){return o(this,null,function*(){let n=N.current();return n?n.removeJoinLink():Promise.reject()})}function _o(n,e){return o(this,null,function*(){return me.getAnonymTokenByLink(n,e)})}function go(n){let e=N.current();e&&e.setVolume(n)}function fo(n){p.forceRelayPolicy=n}function So(n=!1,e=null,t=null,i="DIRECT_LINK",r=null,a=null){return o(this,null,function*(){let s=N.current();return s?s.startStream(n,e,t,i,r,a):Promise.reject()})}function vo(n=null){return o(this,null,function*(){let e=N.current();return e?e.stopStream(n):Promise.reject()})}function Eo(n,e,t=null){return o(this,null,function*(){let i=N.current();if(i){let r=yield me.getOkIdsByExternalIds([n]),a=fe.getDeviceIdx(n);return i.recordSetRole(v.composeParticipantId(r[0],te.USER,a),e,t)}return Promise.reject()})}function Io(){return o(this,null,function*(){let n=N.current();return n?n.getStreamInfo():Promise.reject()})}function To(n){return o(this,null,function*(){let e=N.current();return e?e.addMovie(n):Promise.reject()})}function Co(n){return o(this,null,function*(){let e=N.current();return e?e.updateMovie(n):Promise.reject()})}function Ro(n){return o(this,null,function*(){let e=N.current();return e?e.removeMovie(n):Promise.reject()})}function yo(n,e){return o(this,null,function*(){let t=N.current();return t?t.updateRooms(n,e):Promise.reject()})}function Po(n,e){return o(this,null,function*(){let t=N.current();return t?t.activateRooms(n,e):Promise.reject()})}function bo(n=null,e=null){return o(this,null,function*(){let t=null;if(e){let r=yield me.getOkIdsByExternalIds([e]);t=v.composeUserId(r[0],te.USER)}let i=N.current();return i?i.switchRoom(n,t):Promise.reject()})}function Mo(n){return o(this,null,function*(){let e=N.current();return e?e.removeRooms(n):Promise.reject()})}function Ao(n){p.statisticsInterval=n;let e=N.current();if(e)return e.updateStatisticsInterval()}function Do(n){Pr.default.disableLog(!n),c.toggle(n)}function ko(n,...e){!p.debugLog||c.send(n,"[external]",...e)}function Oo(n){return o(this,null,function*(){let e=N.current();if(e)return e.videoEffect(n)})}function wo(n){return o(this,null,function*(){let e=N.current();e&&(yield e.setAudioStream(n))})}function xo(n=null,e,t=!1){return o(this,null,function*(){return ht().getWaitingHall(n,e,t)})}function Lo(n,e=!1){return o(this,null,function*(){let t=ht(),i=yield me.getOkIdsByExternalIds([n]);return t.promoteParticipant(v.composeUserId(i[0],te.USER),e)})}function No(n){return o(this,null,function*(){return ht().getParticipantListChunk(n)})}function Uo(n){return o(this,null,function*(){return ht().getParticipants(n)})}function Bo(n){return o(this,null,function*(){return ht().feedback(n)})}function Fo(n,e){return o(this,null,function*(){return ht().enableFeatureForRoles(n,e)})}function ht(){let n=N.current();if(!n)throw new Error("Conversation not found");return n}function Vo(n){return o(this,null,function*(){yield me.removeHistoryRecords(n)})}function Ho(){return o(this,null,function*(){let n=N.current();n&&(yield n.startAsr())})}function Go(){return o(this,null,function*(){let n=N.current();n&&(yield n.stopAsr())})}function Wo(n){return o(this,null,function*(){let e=N.current();e&&(yield e.requestAsr(n))})}function jo(){return p.sdkVersion}
|
|
11
|
+
`,r=>{var a;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(a=r.data)==null?void 0:a.byteLength,width:r.width,height:r.height})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:p.screenFrameRate,useCongestionControl:this._useCongestionControl,maxBitrate:this._maxBitrate},[i])})}requestFrame(e=!1){this._sendToWorker(Se.FRAME,{keyFrame:e})}setBitrate(e,t){this._sendToWorker(Se.SET_BITRATE,{bitrate:e,useCbr:t})}isVP9(){return!0}destroy(){this._removeWorker(),c.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var Vn=1.2,ba=.8,Hn=2e3,Gn=8e3,dr=8e3,Wn=16e3,jn=4,Kn=2e3,fi=(i=>(i[i.NONE=0]="NONE",i[i.UP=1]="UP",i[i.DOWN=2]="DOWN",i))(fi||{}),Si=class{constructor(e,t,i,r){this._upPenalty=0;this._delayAvgShort=-1;this._delayAvgLong=-1;this._minDelay=Number.MAX_VALUE;this._maxDelay=0;this._largeDelayDuration=0;this._onCongestion=e,this._ccEnabled=r,this._minBitrate=t,this._maxBitrate=i,this._targetBitrate=this._maxBitrate,this._probing=!1;let a=Date.now();this._lastDown=0,this._lastUp=a,this._lastProbing=a,this._lastCheckDelay=0}checkDelay(e,t,i){let r=Date.now();if(this._calcDelay(t,r),this._delayAvgShort<=0||this._delayAvgLong<=0||!this._ccEnabled)return;let a=0,s=this._delayAvgShort-this._delayAvgLong,d=Math.round(Math.abs(s)*100/this._delayAvgLong),l=s>40&&d>30&&this._delayAvgShort>700,u=this._delayAvgShort>2e3;l||u?a=2:Math.abs(s)<40&&d<10&&this._delayAvgShort<2e3&&(a=1);let E=Math.round(this._targetBitrate/1e3),C=i;e%100==0&&c.debug(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${fi[a]} tr=${E} br=${i}`);let M=r-this._lastDown;if(a===2&&M>Hn){this._probing&&(this._upPenalty=Math.min(++this._upPenalty,jn),this._probing=!1);let q=ba*C*1e3;if(q>=this._targetBitrate&&(q=this._targetBitrate*ba),q=Math.max(q,this._minBitrate),q<this._targetBitrate){let De=Math.round(q/1e3),re=Math.round(this._upPenalty*dr/1e3);c.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${fi[a]}`),c.log(`#${e}: cc: DOWN delay=${t} bitrate=${C} target=${E} -> newBitrate=${De} penalty=${re}s`),this._onCongestion(q,!0),this._targetBitrate=q}this._lastDown=r}let O=r-this._lastUp,w=Gn+this._upPenalty*dr;if(a===1&&O>w&&M>w){let q=Math.min(this._targetBitrate*Vn,this._maxBitrate);if(q>this._targetBitrate){let De=Math.round(q/1e3),re=Math.round(this._targetBitrate/1e3),Ce=Math.round(this._upPenalty*dr/1e3);c.log(`#${e}: cc: delay=${t} short=${this._delayAvgShort} long=${this._delayAvgLong} delta=${s} percent=${d} -> ${fi[a]}`),c.log(`#${e}: cc: UP bitrate=${C} target=${re} -> newBitrate=${De} penalty=${Ce}s`),this._onCongestion(q,!1),this._targetBitrate=q,this._probing=!0,this._lastProbing=r,this._lastUp=r}}let F=r-this._lastProbing;this._probing&&F>Wn&&(this._probing=!1);let de=r-this._lastDown;this._upPenalty>0&&de>3*w&&(c.log(`#${e}: cc: UP reset penalty: oldPenalty=${this._upPenalty}`),this._upPenalty=0)}_calcDelay(e,t){if(!(e<=0)){if(this._delayAvgShort===-1&&(this._delayAvgShort=e,this._delayAvgLong=e),this._delayAvgShort=Math.round((this._delayAvgShort*3+e)/4),this._delayAvgLong=Math.round((this._delayAvgLong*23+e)/24),e>0&&e<this._minDelay?this._minDelay=e:e>this._maxDelay&&(this._maxDelay=e),this._lastCheckDelay===0&&(this._lastCheckDelay=t),e>Kn){let i=t-this._lastCheckDelay;this._largeDelayDuration+=i}this._lastCheckDelay=t}}reconfigure(e,t){this._minBitrate=e,this._maxBitrate=t}getStat(){if(this._minDelay===Number.MAX_VALUE||this._maxDelay===0||this._delayAvgLong<=0)return null;let e={minDelay:this._minDelay,maxDelay:this._maxDelay,avgDelay:this._delayAvgLong,largeDelayDuration:this._largeDelayDuration};return this._minDelay=Number.MAX_VALUE,this._maxDelay=0,this._largeDelayDuration=0,e}};var vi=class{constructor(e){this._size=0;this._head=0;this._tail=0;this._maxSize=e,this._buffer=new Array(e)}add(e,t,i,r,a){this._tail===this._head&&this._size>0&&(this._head=++this._head%this._maxSize);let s=this._tail;return this._buffer[this._tail]={seq:e,ts:t,size:i,sent:Date.now(),start:r,end:a,ts2:-1,recv:-1},this._tail=++this._tail%this._maxSize,this._size++,s}update(e,t){let i=this.get(e);return i===null?null:(i.ts2=t,i.recv=Date.now(),i)}get(e){let t=this._head;for(let i=0;i<this._maxSize;i++){if(e===this._buffer[t].seq)return this._buffer[t];if(t=++t%this._maxSize,t===this._tail)break}return null}getServerBitrateK(e){let t=0,i=0,r=-1,a=-1,s=this._tail;for(let d=0;d<this._maxSize;d++){s>0?--s:s=this._maxSize-1;let l=this._buffer[s];if(l===null||(a===-1&&(a=l.ts2,i=0),a>=0&&(i+=l.size),r=l.ts2,a-r>=e)||s===this._head)break}if(r>=0&&a>=0){let d=a-r;t=Math.round(d>0?i*8/d:0)}return t}getCurrentDelay(){let e=this._tail;for(let t=0;t<this._maxSize;t++){e>0?--e:e=this._maxSize-1;let i=this._buffer[e];if(i===null)break;if(i.recv>=0&&i.sent>=0)return i.recv-i.sent;if(e===this._head)break}return 0}getMaxBandwidth(){let e=0,t=0,i=-1,r=-1,a=this._tail;for(let s=0;s<this._maxSize;s++){if(a>0?--a:a=this._maxSize-1,r===-1&&this._buffer[a].end&&!this._buffer[a].start&&(r=this._buffer[a].ts2,t=0),i===-1&&r>=0&&this._buffer[a].start&&!this._buffer[a].end&&(i=this._buffer[a].ts2),i>=0&&r>=0){let d=r-i;e=d>0?t*8/d:0;break}if(r>=0&&(t+=this._buffer[a].size),a===this._head)break}return Math.round(e)}};var $n=65536,qn=50,zn=400,Jn=1e6,Yn=3e4,Ei=0,At=class{constructor(e,t,i){this._destroyed=!1;this._needKeyframe=!0;this._frameNum=0;this._feedback=new vi(1024);this._lastSharingStat=Date.now();this._congestionControlEnabled=!1;c.debug("ScreenCaptureSender started"),this.DATA_SIZE=p.consumerScreenDataChannelPacketSize-_i,this._datachannel=t,this._signaling=i,this._congestionControlEnabled=p.screenShareCongestionControl,this._width=e.getSettings().width,this._height=e.getSettings().height;let{minBitrate:r,maxBitrate:a}=this._calcMinMaxBitrate(this._width,this._height),s=this._onCongestionCallback.bind(this);c.log(`ScreenCaptureSender: CongestionControl: enabled=${this._congestionControlEnabled} minBitrate=${Math.round(r/1e3)}k maxBitrate=${Math.round(a/1e3)}k`),this._congestionControl=new Si(s,r,a,this._congestionControlEnabled);let d=(l,u)=>{if(!this._destroyed){if(!l){c.warn("requestFrame failed, keyFrame: "+this._needKeyframe,u),this._needKeyframe=!0,this._requestFrame();return}(l.width!==this._width||l.height!==this._height)&&(this._width=l.width,this._height=l.height,this._onResize(this._width,this._height)),this._send(l).catch(E=>{c.warn("sendFrame failed",E),this._needKeyframe=!0}).finally(()=>{this._frameNum++,l.type==="key";let E=this._feedback.getCurrentDelay(),C=this._feedback.getServerBitrateK(2e3);E>0&&this._congestionControl.checkDelay(this._frameNum,E,C),this._requestFrame()}),this._sendSharingStat()}};Mt.isBrowserSupported()?this._encoder=new Mt(e,d,p.screenShareCongestionControl,a):this._encoder=new jt(e,d,p.screenShareCongestionControl,a),this._datachannel.onmessage=l=>{ya(l.data)&&(c.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0);let u=Pa(l.data);u!==null&&this._checkCcFeedback(u)},this._encoder.init().then(()=>this._requestFrame()).catch(l=>c.warn("ScreenCaptureSender init failed",l))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,a){let s=Ca(e,t,i,r,Ei,this._encoder.isVP9(),a);return Ei=(Ei+1)%$n,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return o(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let a=e.data.slice(t,t+this.DATA_SIZE),s=e.data.byteLength<=t+a.byteLength;this._feedback.add(Ei,e.timestamp,a.byteLength,!t,s);let d=this._wrapHeader(e.timestamp,!t,s,e.type==="key",a);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(d)}catch(l){c.warn("Error send data to DataChannel",l),r();return}s||v.setImmediate(()=>this._sendChunk(e,t+this.DATA_SIZE,i,r))}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),c.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return Mt.isBrowserSupported()||jt.isBrowserSupported()}_onCongestionCallback(e,t){this._encoder.setBitrate(e,t)}_onResize(e,t){let{minBitrate:i,maxBitrate:r}=this._calcMinMaxBitrate(e,t),a=Math.round(i/1e3),s=Math.round(r/1e3);c.log(`cc: resize to ${e}x${t}, minBitrate=${a} maxBitrate=${s}`),this._congestionControl.reconfigure(i,r)}_calcMinMaxBitrate(e,t){(e===void 0||e<640)&&(e=640),(t===void 0||t<360)&&(t=360);let i=e*t/256,r=Math.min(Jn,Math.round(i*qn)),a=Math.round(i*zn);return{minBitrate:r,maxBitrate:a}}_checkCcFeedback(e){this._feedback.update(e.seq,e.ts2)===null&&c.debug(`cc: update failed, seq=${e.seq}`)}_sendSharingStat(){let e=Date.now();if(e-this._lastSharingStat>Yn){let i=this._congestionControl.getStat();i!==null&&(c.debug(`cc: send stats: ${JSON.stringify(i)}`),this._signaling.reportSharingStat(i)),this._lastSharingStat=e}}};var ne=class{static get sessionKey(){return ne._sessionKey}static set sessionKey(e){ne._sessionKey=e}static get sessionSecretKey(){return ne._sessionSecretKey}static set sessionSecretKey(e){ne._sessionSecretKey=e}static get accessToken(){return ne._accessToken}static set accessToken(e){ne._accessToken=e}static isEmpty(){return!ne._sessionKey||!ne._sessionSecretKey}};var S=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(S._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(S._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("apiAuth")&&(ne.accessToken=e.apiAuth.accessToken,ne.sessionKey=e.apiAuth.sessionKey,ne.sessionSecretKey=e.apiAuth.sessionSecretKey),e.hasOwnProperty("api")&&(Object.assign(S._params.api,e.api),delete e.api),Object.assign(S._params,v.objectFilterOutValues(e,void 0))}static get(e){return S._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.6.3-dev.c4e735f.0"}static get debug(){return undefined}static get protocolVersion(){return S._params.joinFromMultipleDevices?6:5}static get platform(){return S._params.platform}static set platform(e){S._params.platform=e}static get clientType(){return S._params.clientType}static set clientType(e){S._params.clientType=e}static get externalUserType(){return S._params.externalUserType}static set externalUserType(e){S._params.externalUserType=e}static get device(){return S._params.device}static get apiKey(){return S._params.apiKey}static get apiEnv(){return S._params.apiEnv}static get apiEndpoint(){switch(S.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return S._params.apiEnv}}static get authToken(){return S._params.authToken}static set authToken(e){S._params.authToken=e}static get anonymToken(){return S._params.anonymToken}static set anonymToken(e){S._params.anonymToken=e}static get domain(){return S._params.domain}static get externalDomain(){return S._params.externalDomain}static get iceServers(){return S._params.iceServers}static set iceServers(e){S._params.iceServers=e}static get wssBase(){return S._params.wssBase}static set wssBase(e){S._params.wssBase=e}static get wssToken(){return S._params.wssToken}static set wssToken(e){S._params.wssToken=e}static get signalingReconnectDelay(){return S._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return S._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return S._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return S._params.waitConnectionDelay}static get waitResponseDelay(){return S._params.waitResponseDelay}static get waitMessageDelay(){return S._params.waitMessageDelay}static get waitAnotherTabDelay(){return S._params.waitAnotherTabDelay}static get debugLog(){return S._params.debugLog}static get forceRelayPolicy(){return S._params.forceRelayPolicy}static set forceRelayPolicy(e){S._params.forceRelayPolicy=e}static get videoMinWidth(){return S._params.videoMinWidth}static get videoMaxWidth(){return S._params.videoMaxWidth}static set videoMaxWidth(e){S._params.videoMaxWidth=e}static get videoMinHeight(){return S._params.videoMinHeight}static get videoMaxHeight(){return S._params.videoMaxHeight}static set videoMaxHeight(e){S._params.videoMaxHeight=e}static get videoAspectRatio(){return S._params.videoAspectRatio}static get videoFrameRate(){return S._params.videoFrameRate}static get videoFacingMode(){return S._params.videoFacingMode}static get screenFrameRate(){return S._params.screenFrameRate}static get videoEffects(){return S._params.videoEffects}static set videoEffects(e){S._params.videoEffects=e}static get videoEffectMaxWidth(){return S._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){S._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return S._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){S._params.videoEffectMaxHeight=e}static get voiceParams(){return S._params.voiceParams}static get specListenerParams(){return S._params.specListenerParams}static get iceRestartWaitTime(){return S._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return S._params.transportConnectionWaitTime}static get statisticsInterval(){return S._params.statisticsInterval}static set statisticsInterval(e){S._params.statisticsInterval=e}static get networkStatisticsInterval(){return S._params.networkStatisticsInterval}static get perfStatReportEnabled(){return S._params.perfStatReportEnabled}static get callStatReportEnabled(){return S._params.callStatReportEnabled}static get producerNotificationDataChannel(){return S._params.producerNotificationDataChannel}static get producerCommandDataChannel(){return S._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return S._params.consumerScreenDataChannel&&At.isBrowserSupported()}static get producerScreenDataChannel(){return S._params.producerScreenDataChannel&&S.producerNotificationDataChannel&&bt.isBrowserSupported()}static get asrDataChannel(){return S._params.asrDataChannel&&S.producerNotificationDataChannel}static get consumerScreenDataChannelPacketSize(){return S._params.consumerScreenDataChannelPacketSize}static get screenShareWebmBuilder(){return S._params.screenShareWebmBuilder}static get noiseSuppression(){return S._params.noiseSuppression}static set noiseSuppression(e){S._params.noiseSuppression=e}static get preferH264(){return S._params.preferH264}static get preferVP9(){return S._params.preferVP9}static get audioNack(){return S._params.audioNack}static get consumerScreenTrack(){return S._params.consumerScreenTrack&&S.consumerScreenDataChannel}static get producerScreenTrack(){return S._params.producerScreenTrack}static get movieShare(){return S._params.movieShare&&S.videoTracksCount>0}static get videoTracksCount(){return S.producerNotificationDataChannel?S._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return S._params.breakVideoPayloadTypes}static get filteredMessages(){return S._params.filteredMessages}static get useParticipantListChunk(){return S._params.useParticipantListChunk&&S._params.videoTracksCount>0}static get useRooms(){return S._params.useRooms}static get participantListChunkInitIndex(){var e;return(e=S._params.participantListChunkInitIndex)!=null?e:0}static get participantListChunkInitCount(){var e;return(e=S._params.participantListChunkInitCount)!=null?e:null}static get serverAudioRed(){return S._params.serverAudioRed&&y.canPreferRed()}static get p2pAudioRed(){return S._params.p2pAudioRed&&y.canPreferRed()}static get h264spsPpsIdrInKeyframe(){return S._params.h264spsPpsIdrInKeyframe}static get batchParticipantsOnStart(){return S._params.batchParticipantsOnStart}static get filterObservers(){return S._params.filterObservers}static get muteMode(){return S._params.muteMode}static get preserveAudioTracks(){return S._params.preserveAudioTracks}static get audioShareCapabilityEnabled(){return y.isAudioShareSupported()&&S._params.audioShareCapabilityEnabled}static get screenShareCongestionControl(){return S._params.screenShareCongestionControl}static get api(){return S._params.api}},p=S;p._params={platform:"WEB",clientType:"PORTAL",externalUserType:"",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",externalDomain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,waitAnotherTabDelay:200,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,asrDataChannel:!1,consumerScreenDataChannelPacketSize:16*1024,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!0,producerScreenTrack:!0,videoTracksCount:0,movieShare:!1,filteredMessages:!0,useParticipantListChunk:!1,useRooms:!1,participantListChunkInitIndex:0,participantListChunkInitCount:null,serverAudioRed:!1,p2pAudioRed:!1,h264spsPpsIdrInKeyframe:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!0,joinFromMultipleDevices:!0,filterObservers:!1,muteMode:!1,preserveAudioTracks:!1,audioShareCapabilityEnabled:!1,screenShareCongestionControl:!1,api:{userIdsByOkBatchedTimeout:1e3}};var J=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))(J||{});function W(n,...e){let t=p.get(n);t&&setTimeout(t,0,...e)}function ue(n,e,...t){if(p.filterObservers){if(Array.isArray(e)){if(e=e.filter(i=>!i.observer),!e.length)return}else if(e.observer)return}W(n,e,...t)}function ye(n){return Object.assign({},n)}function dt(n){return n.slice()}var lr;(tc=>{function n(h,b){W("onLocalStream",h,ye(b))}tc.onLocalStream=n;function e(h,b){W("onScreenStream",h,ye(b))}tc.onScreenStream=e;function t(h,b){W("onLocalStreamUpdate",ye(h),b)}tc.onLocalStreamUpdate=t;function i(h){W("onLocalStatus",h)}tc.onLocalStatus=i;function r(h,b){ue("onRemoteStream",h,b)}tc.onRemoteStream=r;function a(h,b){ue("onRemoteLive",h,b)}tc.onRemoteLive=a;function s(h,b){ue("onLocalLive",h,b)}tc.onLocalLive=s;function d(h,b){ue("onRemoteLiveUpdate",h,b)}tc.onRemoteLiveUpdate=d;function l(h,b){ue("onLocalLiveUpdate",h,b)}tc.onLocalLiveUpdate=l;function u(h,b){ue("onRemoteScreenStream",h,b)}tc.onRemoteScreenStream=u;function E(h,b,ee,Ye,xt){ue("onConversation",h,ye(b),ye(ee),Ye,xt)}tc.onConversation=E;function C(h){h&&W("onConversationParticipantListChunk",h)}tc.onConversationParticipantListChunk=C;function M(h,b,ee){ue("onRemoteMediaSettings",h,ye(b),ee)}tc.onRemoteMediaSettings=M;function O(h,b){ue("onLocalMediaSettings",h,ye(b))}tc.onLocalMediaSettings=O;function w(h,b){ue("onRemoteSharedMovieInfo",h,ye(b))}tc.onRemoteSharedMovieInfo=w;function F(h,b){ue("onRemoteSharedMovieStoppedInfo",h,ye(b))}tc.onRemoteSharedMovieStoppedInfo=F;function de(h,b){ue("onLocalSharedMovieInfo",h,ye(b))}tc.onLocalSharedMovieInfo=de;function q(h,b){ue("onLocalSharedMovieStoppedInfo",h,ye(b))}tc.onLocalSharedMovieStoppedInfo=q;function De(h,b){ue("onParticipantAdded",h,b)}tc.onParticipantAdded=De;function re(h,b){ue("onParticipantJoined",h,b)}tc.onParticipantJoined=re;function Ce(h,b,ee){ue("onRemoteParticipantState",h,ye(b),ee)}tc.onRemoteParticipantState=Ce;function be(h,b,ee=null){ue("onRemoteStatus",h,b,ee)}tc.onRemoteStatus=be;function at(h,b,ee=null){ue("onParticipantStatus",h,b,ee)}tc.onParticipantStatus=at;function ti(){W("onPermissionsRequested")}tc.onPermissionsRequested=ti;function Q(h){W("onPermissionsError",h)}tc.onPermissionsError=Q;function br(h,b){ue("onRemoteRemoved",h,b)}tc.onRemoteRemoved=br;function Oi(h,b,ee){W("onCallState",h,b,ye(ee))}tc.onCallState=Oi;function wi(h,b){W("onDeviceSwitched",h,b)}tc.onDeviceSwitched=wi;function Y(h,b,ee,Ye=!1,xt=!1,Ni=null,Ui=null,sn,Ar,on=null){let cn=Ar?dt(Ar):void 0;W("onMuteStates",ye(h),dt(b),dt(ee),Ye,xt,Ni,Ui,sn,cn,on)}tc.onMuteStates=Y;function xi(h,b){ue("onRolesChanged",h,dt(b))}tc.onRolesChanged=xi;function Mr(h){W("onLocalRolesChanged",dt(h))}tc.onLocalRolesChanged=Mr;function Li(h,b,ee){ue("onPinnedParticipant",h,b,ee)}tc.onPinnedParticipant=Li;function _(h){W("onLocalPin",h)}tc.onLocalPin=_;function m(h){W("onOptionsChanged",dt(h))}tc.onOptionsChanged=m;function I(){W("onCallAccepted")}tc.onCallAccepted=I;function A(){W("onRateNeeded")}tc.onRateNeeded=A;function P(h){ue("onSpeakerChanged",h)}tc.onSpeakerChanged=P;function j(h){W("onVolumesDetected",dt(h))}tc.onVolumesDetected=j;function Z(h,b){W("onLocalVolume",h,b)}tc.onLocalVolume=Z;function Ee(h,b){W("onJoinStatus",h,b)}tc.onJoinStatus=Ee;function ke(h,b){W("onHangup",h,b)}tc.onHangup=ke;function Ge(h){W("onMultipartyChatCreated",ye(h))}tc.onMultipartyChatCreated=Ge;function ze(){W("onDeviceChange")}tc.onDeviceChange=ze;function xe(h){W("onFingerprintChange",h)}tc.onFingerprintChange=xe;function Le(){W("onTokenExpired")}tc.onTokenExpired=Le;function Ne(h,b,ee=!1){W("onChatMessage",h,b,ee)}tc.onChatMessage=Ne;function We(h,b,ee=!1){W("onCustomData",h,b,ee)}tc.onCustomData=We;function L(h,b,ee,Ye,xt,Ni,Ui=null){W("onRecordStarted",h,b,ee,Ye,xt,Ni,Ui)}tc.onRecordStarted=L;function U(h=null){W("onRecordStopped",h)}tc.onRecordStopped=U;function _t(h){W("onLocalNetworkStatusChanged",h)}tc.onLocalNetworkStatusChanged=_t;function z(h){W("onNetworkStatusChanged",h)}tc.onNetworkStatusChanged=z;function _e(h,...b){W("onDebugMessage",h,...b)}tc.onDebugMessage=_e;function Ie(h,b){let ee=Object.assign({},h,{memory:b});W("onStatistics",ee)}tc.onStatistics=Ie;function ie(){W("onAutoplayError")}tc.onAutoplayError=ie;function X(h,b,ee){W("onChatRoomUpdated",h,b,ee)}tc.onChatRoomUpdated=X;function ce(h){W("onRemoteMixedAudioStream",h)}tc.onRemoteMixedAudioStream=ce;function Je(h){W("onJoinLinkChanged",h)}tc.onJoinLinkChanged=Je;function Ko(h){W("onRoomsUpdated",h)}tc.onRoomsUpdated=Ko;function $o(h,b,ee,Ye){W("onRoomUpdated",h,b,ee,Ye)}tc.onRoomUpdated=$o;function qo(h){W("onRoomParticipantsUpdated",h)}tc.onRoomParticipantsUpdated=qo;function zo(h){W("onRoomSwitched",h)}tc.onRoomSwitched=zo;function Jo(h){W("onRoomStart",h)}tc.onRoomStart=Jo;function Yo(h,b=null){W("onFeedback",h,b)}tc.onFeedback=Yo;function Qo(h){W("onFeaturesPerRoleChanged",h)}tc.onFeaturesPerRoleChanged=Qo;function Xo(h,b){W("onAsrStarted",h,b)}tc.onAsrStarted=Xo;function Zo(){W("onAsrStopped")}tc.onAsrStopped=Zo;function ec(h,b,ee,Ye){W("onAsrTranscription",h,b,ee,Ye)}tc.onAsrTranscription=ec})(lr||(lr={}));var g=lr;var pr=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(pr||{}),ur;(re=>{let n="📞",e=(Ce,...be)=>{g.onDebugMessage(Ce,...be)},t=!1,i=(Ce,be)=>(...at)=>{Ce(...at),da(be,at)},r=console.debug.bind(console,n),a=console.log.bind(console,n),s=console.warn.bind(console,n),d=console.error.bind(console,n),l=e.bind(null,"DEBUG"),u=e.bind(null,"LOG"),E=e.bind(null,"WARN"),C=e.bind(null,"ERROR");re.debug=l,re.log=u,re.warn=E,re.error=C;function de(){return t}re.enabled=de;function q(Ce){t=Ce,p.debugLog&&Gi(),Ce?(re.debug=p.debugLog?i(r,"DEBUG"):r,re.log=p.debugLog?i(a,"LOG"):a,re.warn=p.debugLog?i(s,"WARN"):s,re.error=p.debugLog?i(d,"ERROR"):d):(re.debug=p.debugLog?i(l,"DEBUG"):l,re.log=p.debugLog?i(u,"LOG"):u,re.warn=p.debugLog?i(E,"WARN"):E,re.error=p.debugLog?i(C,"ERROR"):C)}re.toggle=q;function De(Ce,...be){switch(Ce){case"DEBUG":re.debug(...be);break;case"LOG":re.log(...be);break;case"WARN":re.warn(...be);break;case"ERROR":re.error(...be);break}}re.send=De})(ur||(ur={}));var c=ur;var lt=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(lt||{}),ve;(d=>{function n(l){return l.length?typeof l[0]=="object"?l:l.map(u=>e(u)):[]}d.fromIds=n;function e(l,u="USER"){return{id:l,type:u}}d.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}d.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}d.toString=i;function r(l,u="USER"){return i(e(l,u))}d.fromIdToString=r;function a(l){try{return JSON.parse(l)}catch(u){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}d.fromString=a;function s(l,u){return l.id===u.id&&l.type===u.type}d.compare=s})(ve||(ve={}));var fe;(r=>{function n(a,s="USER",d=0){return{id:a,type:s,deviceIdx:d}}r.fromId=n;function e(a){return`{"id":"${a.id}","type":"${a.type}","deviceIdx":"${a.deviceIdx}"}`}r.toString=e;function t(a,s){return Object.assign({deviceIdx:s},ve.fromSignaling(a))}r.fromSignaling=t;function i(a){return a&&typeof a=="object"?a.deviceIdx:0}r.getDeviceIdx=i})(fe||(fe={}));var Qn="kf";function Kt(n){return n.stopStream}function mr(n){return n.keyFrameRequested}function Ma(n){if(Kt(n))return"ss";if(mr(n))return Qn;let e="";return n.priority!==void 0&&(e+="p="+n.priority),n.width!==void 0&&n.height!==void 0&&(e!==""&&(e+=":"),e+="sz="+Math.round(n.width)+"x"+Math.round(n.height)),n.fit!==void 0&&(e!==""&&(e+=":"),e+="fit="+n.fit),e}var Pe=(a=>(a.CAMERA="CAMERA",a.SCREEN="SCREEN",a.STREAM="STREAM",a.MOVIE="MOVIE",a.AUDIOSHARE="AUDIOSHARE",a))(Pe||{}),Aa="s",Da="m";function qe(n){return n.participantId+(n.mediaType?Ct+Aa+n.mediaType:"")+(n.streamName?Ct+Da+n.streamName:"")}function $t(n){let e=n.split(Ct),t=e.shift();if(!t)throw new Error("Illegal stream description: "+n);let i=null,r,a=0;for(let d of e)switch(d.charAt(0)){case Aa:i=Xn(d.slice(1));break;case Da:r=d.slice(1);break;case si:a=Number.parseInt(d.slice(1),10);break;default:throw new Error("Unexpected parameter type "+d.charAt(0)+" in stream description "+n)}return{participantId:v.compose(t,a),mediaType:i,streamName:r}}function Xn(n){for(let e of Object.keys(Pe))if(e===n)return Pe[e];return null}function hr(n,e){return n===null||e===null?n===null&&e===null:!(n.maxDimension!==e.maxDimension||n.maxBitrateK!==e.maxBitrateK||n.maxFramerate!==e.maxFramerate||n.degradationPreference!==e.degradationPreference)}function Ii(n,e){return!(!hr(n.camera,e.camera)||!hr(n.screenSharing,e.screenSharing))}function _r(n,e){return{camera:Object.assign({},n.camera,e.camera),screenSharing:Object.assign({},n.screenSharing,e.screenSharing)}}function ka(n){try{return btoa(JSON.stringify(n))}catch(e){c.warn("WaitingParticipant: failed convert to string",n,e)}return null}function Oa(n){try{return JSON.parse(atob(n))}catch(e){c.warn("WaitingParticipant: failed convert from string",n,e)}return null}var Dt=(n,e)=>v.objectReduce(n,(t,i,r)=>(i===e&&t.push(r),t),[]);var qt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,f.log(T.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,f.log(T.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(c.log("Failed to fix RV"),f.log(T.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),f.log(T.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,c.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===pe.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Ti=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(p.muteMode||!((s=this._output)==null?void 0:s.audioTrack))return;let e=y.browserName()!=="Safari"||y.isMobile(),t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{c.warn("Error on play audio"),g.onAutoplayError()},r=d=>{t.srcObject=new MediaStream([d]),t.load();let l=t.play();l&&l.catch(i)},a=()=>{var l;c.debug("Recover audio playback");let d=(l=this._output)==null?void 0:l.audioTrack;d?r(d):c.warn("Broken audio track")};t.onpause=a,t.onstalled=a,t.onerror=a,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return o(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=y.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw f.log(T.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var Zn=90,es=3,Ci=class extends ae{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),g.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>Zn?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=es)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var ts=44100,zt=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=y.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=ts/this._fftBins.length,t=Math.ceil(p.voiceParams.minFreq/e),i=Math.floor(p.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((a,s)=>a+s,0)/e.length/255,r=this._lastSmoothedLevel*p.voiceParams.smoothing+i*(1-p.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var Ri=class extends ae{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&g.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,p.voiceParams.interval)};this._interval=window.setTimeout(t,p.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,Me.SOURCE_CHANGED,r=>{r.kind===pe.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new zt("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 wa="videochat-epi",is=5e3,rs=3e4,pt=class extends ae{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,V.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(wa)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return o(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&p.perfStatReportEnabled&&this._previousTimestamp+is<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),p.callStatReportEnabled&&this._previousCallStatReportTimestamp+rs<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return o(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(wa,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,a)=>(a.kind==="video"?(a.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+a.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+a.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=a.framesDropped,r.nack_sent+=a.nackCount,r.pli_sent+=a.pliCount,r.fir_sent+=a.firCount):(a.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+a.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+a.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=a.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=a.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=a.removedSamplesForAcceleration,r.concealed_audio_samples+=a.concealedSamples,r.silent_concealed_audio_samples+=a.silentConcealedSamples,r.audio_concealment_events+=a.concealmentEvents),r),t),e.outbound.rtps.reduce((r,a)=>(a.kind==="video"&&(r.nack_received+=a.nackCount,r.pli_received+=a.pliCount,r.fir_received+=a.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,a=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,d=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,l=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,u=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=a/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=d/r*1e3,i.concealed_silent_audio_samples=l/r*1e3,i.concealment_audio_avg_size=d/u,i.total_audio_energy=t.total_audio_energy}f.logCustom("callStat",i),c.log("Sent call stats",i),this._previousCallStatReport=t}};var as=1e3;function he(n,e,t=0){return e in n&&n[e]?n[e]:t}function xa(...n){return e=>{for(let t of n)if(t(e))return!0;return!1}}function it(n,e){return t=>t[n]===e}function ns(n){return(e,t)=>e[n]-t[n]}function yi(n,e){return e.reduce((t,i)=>(t[i[n]]=i,t),{})}function ss(n){let e={},t=[];for(let i of n)e[i.id]||(e[i.id]=!0,t.push(i));return t}function os(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function gr(n){return Object.keys(n).filter(e=>n[e]!==void 0).map(e=>[e,n[e]]).reduce((e,t)=>(e[t[0]]=os(t[1])?gr(t[1]):t[1],e),{})}function cs(n){let e=[];for(let t of n)t.forEach(i=>e.push(i));return e}function ds(n){return o(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...n.getReceivers().map(t=>t.getStats())),e.push(...n.getSenders().map(t=>t.getStats()))):e.push(n.getStats()),Promise.all(e).then(cs).then(ss)})}function ls(n){let e=n.filter(it("type","candidate-pair")).sort(ns("priority")).find(xa(it("nominated",!0),it("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=n.find(it("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=n.find(it("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}})),gr(t)}function ps(n,e){let t=yi("id",n),i=n.filter(xa(it("type","inbound-rtp"),it("type","outbound-rtp")));y.browserName()==="Firefox"&&(i=Object.values(i.reduce((a,s)=>{if(!a[s.ssrc])a[s.ssrc]=s;else{let d=Object.assign({},a[s.ssrc],s),l=a[s.ssrc].isRemote?s:a[s.ssrc];d.id=l.id,d.type=l.type,delete d.isRemote,delete d.remoteId,a[d.ssrc]=d}return a},{})));let r={};if(y.browserName()==="Safari"){let a=n.filter(it("type","track"));r=yi("trackIdentifier",a)}return i.map(a=>{let s=Number(a.ssrc),d=a.mediaType||a.kind,l=a.trackId,u=a.type,E=a.codecId;if(y.browserName()==="Safari"){let M=/^.+_([\d]+)$/.exec(a.id);if(M&&(s=parseInt(M[1],10)),d=a.id.indexOf("Audio")>0?"audio":"video",e[s]){let O=d+"-"+e[s];r[O]&&(l=r[O].id)}}if(!u||!s||!d)return null;let C={ssrc:s,type:u,kind:d,bytesReceived:he(a,"bytesReceived"),bytesSent:he(a,"bytesSent"),jitter:he(a,"jitter"),packetsLost:he(a,"packetsLost"),packetsReceived:he(a,"packetsReceived"),packetsSent:he(a,"packetsSent"),fractionLost:he(a,"fractionLost"),pliCount:he(a,"pliCount"),firCount:he(a,"firCount"),nackCount:he(a,"nackCount"),userId:e[s]};if(d==="video"){let M=he(a,"framesDecoded"),O=he(a,"totalInterFrameDelay"),w=he(a,"totalSquaredInterFrameDelay");C.interframeDelayVariance=(w-O*O/M)/M}if(d==="audio"&&(C.totalSamplesReceived=he(a,"totalSamplesReceived"),C.concealedSamples=he(a,"concealedSamples"),C.insertedSamplesForDeceleration=he(a,"insertedSamplesForDeceleration"),C.removedSamplesForAcceleration=he(a,"removedSamplesForAcceleration"),C.silentConcealedSamples=he(a,"silentConcealedSamples"),C.concealmentEvents=he(a,"concealmentEvents"),C.totalAudioEnergy=he(a,"totalAudioEnergy")),E&&t[E]){let M=t[E];C.clockRate=M.clockRate,C.mimeType=M.mimeType}if(l&&t[l]){let M=t[l];C.frameHeight=M.frameHeight,C.frameWidth=M.frameWidth,C.framesDecoded=M.framesDecoded,C.framesReceived=M.framesReceived,C.framesDropped=M.framesDropped}return gr(C)}).filter(a=>!!a)}function us(n,e){if(!e||!e.rtps||!n.rtps)return n;let t=yi("ssrc",n.rtps),i=yi("ssrc",e.rtps),r=(n.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(a=>{let s=t[a],d=i[a];if(!(!s||!d)){if(s.bytesReceived&&s.bytesReceived>d.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-d.bytesReceived)/r)),s.bytesSent&&s.bytesSent>d.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-d.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>d.packetsReceived||s.packetsLost>d.packetsLost){let l=s.packetsLost-d.packetsLost,u=s.packetsReceived-d.packetsReceived;s.packetLoss=parseFloat((100*l/(l+u)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&d.framesDropped&&s.framesDropped>d.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-d.framesDropped)/r).toFixed(0)))}}),n}function Jt(i,r){return o(this,arguments,function*(n,e,t={}){let a=yield ds(n),s={timestamp:Date.now(),transport:ls(a),rtps:ps(a,t)};return e?us(s,e):(yield v.delay(as),Jt(n,s,t))})}var Pi=.8,ut=class extends ae{constructor(e,t,i,r,a){super();this._remoteSDP={};this._remoteCandidates={};this._state=H.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=a,this._perfStatReporter=new pt(this,i,!0),this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Me.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Me.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:p.iceServers,iceTransportPolicy:p.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,p.p2pAudioRed),this._applySettings()}catch(s){f.log(T.ERROR,"addTrack-direct"),c.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===H.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==H.IDLE&&e!==H.CLOSED&&e!==H.FAILED&&this._startStatInterval()}open(e=null){return o(this,null,function*(){if(this._isOpen){c.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(c.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!1,!0,p.p2pAudioRed),this._applySettings()}catch(i){f.log(T.ERROR,"addTrack-direct"),c.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(H.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={}})}updateSettings(e){Ii(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(V.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(c.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(H.FAILED)):(c.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(H.CLOSED)),this._triggerEvent(V.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(V.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,a;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=((a=e.data.sdk)==null?void 0:a.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=v.getPeerIdString(e.peerId);v.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){c.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw f.log(T.ERROR,"addIceCandidate-direct"),c.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else c.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return o(this,null,function*(){if(!this._remoteCandidates[e]){c.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){c.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw f.log(T.ERROR,"setRemoteDescription-direct"),c.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){c.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(V.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(V.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return o(this,null,function*(){e.candidate&&this._signaling.ready&&(c.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(c.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>o(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(c.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===H.IDLE||e===H.OPENED?this._setState(H.CONNECTING):this._setState(H.RECONNECTING);break}}_onConnectionStateChange(){switch(c.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),f.log(T.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(H.CONNECTED),this._stopReconnection(),v.getPeerConnectionHostInfo(this._pc).then(e=>{e&&f.log(T.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(H.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(c.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},p.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(c.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(oe.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(f.log(T.ICE_RESTART),c.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):c.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,c.error("Ice restart failed",{participantId:this._participantId}),f.log(T.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},p.iceRestartWaitTime)}_createOffer(e){return o(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return c.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw c.error("Unable to create offer",i,{participantId:this._participantId}),f.log(T.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=ut._patchDescription(i),c.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw c.error("Unable to set local description",i,{participantId:this._participantId}),f.log(T.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return o(this,null,function*(){return c.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw c.error("Unable to create answer",e,{participantId:this._participantId}),f.log(T.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=ut._patchDescription(e),c.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw c.error("Unable to set local description",e,{participantId:this._participantId}),f.log(T.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=v.patchLocalSDP(e.sdp,p.preferH264&&y.canPreferH264(),y.isBrokenH264(),p.preferVP9,p.h264spsPpsIdrInKeyframe,t&&p.audioNack,p.p2pAudioRed),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&t.track.contentHint===e.contentHint&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{c.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),f.log(T.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Jt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:oe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:oe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(V.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,p.statisticsInterval)})};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=q=>q.rtt<=this._networkLimits.goodNet.rtt&&q.loss<=this._networkLimits.goodNet.loss,i=q=>q.rtt>=this._networkLimits.badNet.rtt||q.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,a=e.inbound.rtps.reduce((q,De)=>Math.max(q,De.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-Pi)+r*Pi,loss:this._lastNetworkStat.loss*(1-Pi)+a*Pi},d=i(s),l=t(s),u=i(this._remoteNetworkStat),E=t(this._remoteNetworkStat),C=i(this._lastNetworkStat),M=t(this._lastNetworkStat),F=d||u?.2:l&&E?1:0,de=Date.now();if((C!==d||M!==l||de-this._lastNetworkStat.date>p.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(q=>{c.warn("Unable to send [bad-net]",q)})),F){let q={};q[this._participantId]=q[""]=F,this._triggerEvent(V.NETWORK_STATUS,q)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=v.sdpFingerprint(e);if(t===null){c.warn("Fingerprint calculation is unsupported");return}this._fingerprint===null?this._fingerprint=t:(g.onFingerprintChange((this._fingerprint^t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=v.applySettings(this._pc,e,this._prevConsumerSettings))}};var La=(a=>(a.producerNotification="producerNotification",a.producerCommand="producerCommand",a.consumerScreenShare="consumerScreenShare",a.producerScreenShare="producerScreenShare",a.asr="asr",a))(La||{}),kt=La;var ms=16,Yt=class{constructor(e,t,i){c.debug("AsrReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._asrCallback=i,this._textDecoder=new TextDecoder,this._datachannel.onmessage=r=>this._onDataChannelMessage(r.data)}static parse(e){let t=new DataView(e),i=t.getUint8(0),r=t.getUint8(1);if(r!==0)throw new Error(`Unsupported message type. Message type: ${r}`);let a=t.getUint16(2),s=t.getUint32(4),d=t.getUint32(8),l=t.getUint32(12);if(i!==1)throw new Error(`Unexpected protocol version. Got ${i}, expected 1`);return{sequence:a,ssrc:s,timestamp:d,duration:l,data:e.slice(ms)}}_onDataChannelMessage(e){var a,s;let t=Yt.parse(e),i=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){c.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}let r={participantId:i,text:this._textDecoder.decode(t.data),timestamp:t.timestamp,duration:t.duration};this._asrCallback(r)}destroy(){this._datachannel.onmessage=null}};var rt=nt(require("messagepack"));var fr=class{constructor(){this.streamDescriptionByCompactId=new Map;this.compactIdByStreamDescription=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}getCompactId(e){return this.compactIdByStreamDescription.get(e)}handleMessage(e){var a,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let d=(0,rt.decode)(r);return Object.entries(d).forEach(([w,F])=>{let de=$t(w);this.streamDescriptionByCompactId.set(F,de),this.compactIdByStreamDescription.set(w,F)}),null;case 2:case 4:let l=(0,rt.decode)(r),u=[];for(let w of l){let F=this.getStreamDescription(w);F&&u.push(F.participantId)}return i===2?{type:"notification",notification:k.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:k.STALLED_ACTIVITY,stalledParticipants:u};case 3:let E=(0,rt.decode)(r);return{type:"notification",notification:k.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(E))==null?void 0:a.participantId};case 5:let C=(0,rt.decode)(r);return{type:"notification",notification:k.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:C[0],maxDimension:C[1]}};case 6:let M=(0,rt.decode)(r),O={};for(let[w,F]of Object.entries(M)){let de=(s=this.getStreamDescription(Number(w)))==null?void 0:s.participantId;de&&(O[de]=F/100)}return{type:"notification",notification:k.NETWORK_STATUS,statuses:O};case 7:return this._createParticipantSourcesUpdateNotification(r);case 8:{let F=(0,rt.decode)(r).map(de=>{var Q;let[q,De,re,Ce,be,at,ti]=de;return{participantId:(Q=this.getStreamDescription(q))==null?void 0:Q.participantId,gain:De,pause:re,offset:Ce,mute:be,liveStatus:at,startTimeMs:ti}});return{type:"notification",notification:k.MOVIE_UPDATE_NOTIFICATION,data:F}}default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,rt.decode)(e),i=[];for(let[r,a]of Object.entries(t)){let s=a[0],d=a[1],l=a[2],u;if(s!==null){if(u=this.getStreamDescription(s),!u){c.error(`could not uncompress participant ID ${s}`);continue}}else u=null;if(l===null){c.error("unexpected null sequenceNumber",r,a);continue}let E=Be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,C=d?d>>>0:null;i.push({participantStreamDescription:u,streamId:E,rtpTimestamp:C,sequenceNumber:l})}return{type:"notification",notification:k.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var hs=90,_s=4294967295,Ve=class extends ae{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._asr=null;this._isOpen=!1;this._observer=!1;this._reconnectionPrevented=!1;this._state=H.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._asrTrack=null;this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._newAudioShareTrack=null;this._signaling=e,this._mediaSource=t,this._newAudioShareTrack=t.getAudioShareTrack(),this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Me.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Me.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,Me.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new pt(this,e),this._serverSettings=i,c.debug("ServerTransport: Created")}getState(){return this._state||H.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==H.IDLE&&e!==H.CLOSED&&e!==H.FAILED&&this._startStatInterval()}open(e=!1){if(this._isOpen){c.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._observer=e,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(c.error("ServerTransport: Closed",e),this._setState(H.FAILED)):(c.debug("ServerTransport: Closed"),this._setState(H.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Ii(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeAsrTrack(),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,Ve._closeDataChannel(this._producerNotification),Ve._closeDataChannel(this._producerCommand),Ve._closeDataChannel(this._producerScreen),Ve._closeDataChannel(this._consumerScreen),Ve._closeDataChannel(this._asr),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(V.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{let a=r.readyState;a==="open"?(c.debug(`[${t}] data channel opened`),r.onerror=s=>{c.error(`[${t}] data channel error`,s)},i(r)):c.error(`[${t}] data channel open failed, state [${a}]`)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection"),this._pc=new RTCPeerConnection({},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=v.throttle(t=>{this._pc&&this._onConnectionStateChange(this._pc,t)},500),this._pc.onsignalingstatechange=Ve._onSignalingStateChange.bind(this,this._pc),this._participantIdRegistry=new fr,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),p.producerNotificationDataChannel&&this._createDataChannel(this._pc,kt.producerNotification,t=>{this._producerNotification=t,this._producerNotification.binaryType="arraybuffer",this._signaling.setProducerNotificationDataChannel(t)}),p.producerCommandDataChannel&&(this._signaling.useCommandDataChannel(!0),this._createDataChannel(this._pc,kt.producerCommand,t=>{this._producerCommand=t,this._signaling.setProducerCommandDataChannel(t)})),p.producerScreenDataChannel&&this._createDataChannel(this._pc,kt.producerScreenShare,t=>{this._producerScreen=t,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()}),p.asrDataChannel&&this._createDataChannel(this._pc,kt.asr,t=>{this._asr=t,this._asr.binaryType="arraybuffer",this._removeAsrTrack(),this._asrTrack=new Yt(t,this._participantIdRegistry,i=>{this._onAsrTranscription(i)}),this._signaling.setAsrDataChannel(t)});try{this._mediaSource.addTrackToPeerConnection(this._pc,this._observer,!1,p.serverAudioRed),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(t){c.error("ServerTransport: Unable to add media source tracks",t),f.log(T.ERROR,"addTrack-single"),this.close(t);return}p.consumerScreenDataChannel&&this._createDataChannel(this._pc,kt.consumerScreenShare,t=>{this._consumerScreen=t,this._consumerScreen.binaryType="arraybuffer";let i=this._mediaSource.getScreenTrack();i&&this._createCaptureSender(i)}),e||this._allocateConsumer(),this._setState(H.OPENED),this._startStatInterval(),this._startSettingsInterval()}_removeAsrTrack(){var e;(e=this._asrTrack)==null||e.destroy(),this._asrTrack=null}_reconnect(){this.getState()!==H.OPENED&&(this._setState(H.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(V.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(V.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(V.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(V.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
|
|
12
|
+
`).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${Be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!p.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new At(e,this._consumerScreen,this._signaling))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!p.producerScreenDataChannel||!this._producerScreen||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new bt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(V.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(V.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!p.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==pe.video)return;let r=!this._disabledSenders.has(i),a=e.maxDimension!==0;if(r&&!a){c.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(y.getBlackMediaTrack()).catch(d=>{c.error("Could not disable video upload",d)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&a&&s){c.log("Enabling video upload"),this._disabledSenders.delete(i);let d=i.track;d.enabled=s.enabled,i.replaceTrack(s).then(()=>d.stop()).catch(l=>{c.error("Could not enable video upload",l)})}v.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(V.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,p.statisticsInterval)};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return o(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Jt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(V.REMOTE_DATA_STATS,{inbound:{topology:oe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:oe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=Be.AUDIO_MIX,r=this._statBytes[i],a=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(a=!0),r.stalled!==a&&this._triggerEvent(V.REMOTE_ALL_STALL,a)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:a}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:pt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:p.producerNotificationDataChannel?7:0,producerCommandDataChannelVersion:p.producerCommandDataChannel?3:0,consumerScreenDataChannelVersion:p.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:p.producerScreenDataChannel?1:0,asrDataChannelVersion:p.asrDataChannel?1:0,onDemandTracks:!0,unifiedPlan:!0,singleSession:!0,videoTracksCount:p.videoTracksCount,red:p.serverAudioRed,audioShare:p.audioShareCapabilityEnabled};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return o(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,c.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:v.patchRemoteSDP(e)});if(c.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw c.error("[single] unable to set remote offer",i),f.log(T.ERROR,"setRemoteDescription-single"),i}).then(()=>o(this,null,function*(){if(c.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this.handleTracks(),this._pc.createAnswer()})).catch(i=>{throw c.error("[single] unable to create answer",i),f.log(T.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=v.patchLocalSDP(i.sdp,!1,y.isBrokenH264(),!1,p.h264spsPpsIdrInKeyframe),i)).then(i=>o(this,null,function*(){if(c.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw c.error("[single] unable to set local answer",i),f.log(T.ERROR,"setLocalDescription-single"),i}).then(i=>o(this,null,function*(){c.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),c.debug("[single] remote offer has been processed")})).catch(i=>{c.warn("[single] unable to send local answer",i),f.log(T.ERROR,"acceptProducer")}).then(()=>o(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){c.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}handleTracks(){this._newAudioShareTrack&&(this._pc.getTransceivers().forEach(e=>{e.mid.endsWith("s")&&(e.sender.track!==null&&c.warn("Unexpected track assigned to audioshare"),e.direction="sendonly",e.sender.replaceTrack(this._newAudioShareTrack).catch(t=>{c.error("ServerTransport: Unable to replace track",t),f.log(T.ERROR,"replaceTrack-single")}),this._newAudioShareTrack=null)}),this._newAudioShareTrack&&c.warn("Cannot find audioshare transceiver"))}_onSignalingNotification(e){return o(this,null,function*(){if(!!this._isOpen)switch(e.notification){case 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}})}_onAsrTranscription(e){this._triggerEvent(V.ASR_TRANSCRIPTION,e)}_onProducerUpdated(e){return o(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),p.breakVideoPayloadTypes&&(c.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes",null)),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){c.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=a=>{this._triggerEvent(V.REMOTE_TRACK_REMOVED,i.id,i,a.track)}),i.getTracks().find(a=>a.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(V.REMOTE_TRACK_ADDED,i.id,i,t.track)):c.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){c.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(c.debug("[single] connection state changed",{state:e.connectionState},t),f.log(T.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===H.IDLE||i===H.OPENED?this._setState(H.CONNECTING):e.iceConnectionState==="checking"&&this._setState(H.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(H.RECONNECTING);break;case"connected":this._setState(H.CONNECTED),v.getPeerConnectionHostInfo(e).then(r=>{r&&f.log(T.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){if(this._pc){p.consumerScreenDataChannel&&t&&(e=t);let i=!1;this._pc.getSenders().forEach(r=>{r.track&&r.track.kind===e.kind&&!this._disabledSenders.has(r)&&r.track.contentHint===e.contentHint&&(r.track.enabled=e.enabled,r.replaceTrack(e).catch(a=>{c.error("ServerTransport: Unable to replace track",a),f.log(T.ERROR,"replaceTrack-single")}),i=!0)}),!i&&e.kind===pe.audio&&e.contentHint==="music"&&(this._newAudioShareTrack=e)}this._applyConsumerSettings()}getStreamWaitingTimeMs(e,t){if(!this._pc)return f.log(T.PAT_WAITING_TIME_ERROR,"noConnection"),c.error("Cannot get stream waiting time, peer connection is not initialized"),0;if(!RTCRtpReceiver.prototype.getSynchronizationSources)return f.log(T.PAT_WAITING_TIME_ERROR,"oldBrowser"),c.error("Cannot get stream waiting time, RTCRtpReceiver.getSynchronizationSources is not supported"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return f.log(T.PAT_WAITING_TIME_ERROR,"noReceiver"),c.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return c.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return f.log(T.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),c.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let d=t-s&_s,l=Math.ceil(d/hs);return Math.min(100,Math.max(0,l))}};var V=(w=>(w.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",w.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",w.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",w.REMOTE_ALL_STALL="REMOTE_ALL_STALL",w.REMOTE_DATA_STATS="REMOTE_DATA_STATS",w.STATE_CHANGED="STATE_CHANGED",w.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",w.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",w.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",w.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",w.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",w.NETWORK_STATUS="NETWORK_STATUS",w.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",w.ASR_TRANSCRIPTION="ASR_TRANSCRIPTION",w))(V||{}),H=(d=>(d.IDLE="IDLE",d.OPENED="OPENED",d.CONNECTING="CONNECTING",d.RECONNECTING="RECONNECTING",d.CONNECTED="CONNECTED",d.CLOSED="CLOSED",d.FAILED="FAILED",d))(H||{}),oe=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(oe||{}),Sr=class extends ae{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){c.log("Update transport settings",e),this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(c.log(`Trying allocate participant [${e}]`),this._allocated.indexOf(e)!==-1){c.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null,i=!1,r=!1){c.log("Trying open participant",{participantIds:e});let a=r;for(let s of e){if(this._opened.indexOf(s)!==-1){c.warn(`The participant [${s}] has already had opened transport`);continue}if(this._allocated.indexOf(s)===-1){c.warn(`The participant [${s}] has no allocated transport`);continue}this._opened.push(s),a=!0}!a||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(i),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),c.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&c.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}getState(){var e,t;return this._topology==="SERVER"?(e=this._serverTransport)==null?void 0:e.getState():(t=this._directTransport)==null?void 0:t.getState()}_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)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),f.log(T.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],a=e.offerToDeviceIdxs||[],s=i.length&&r.length?v.composeParticipantId(i[0],r[0],a[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){c.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&c.warn("Topology changed to DIRECT, but the allocated participants count more then one");let d=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=s===d;this._directTransport=this._createDirectTransport(d,l)}this._opened.indexOf(d)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_createDirectTransport(e,t=!1){let i=new ut(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._dtListeners&&this._dtListeners.length>0&&c.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new Ve(this._signaling,this._mediaSource,this._serverSettings);return this._stListeners&&this._stListeners.length>0&&c.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER")),e.addEventListener("ASR_TRANSCRIPTION",this._onAsrTranscription.bind(this))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;p.noiseSuppression!==e&&(p.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onAsrTranscription(e){this._triggerEvent("ASR_TRANSCRIPTION",e)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(f.log(T.PAT_WAITING_TIME_ERROR,"wrongTopology"),c.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(f.log(T.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var mt=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(mt||{}),vr=class extends ae{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,V.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,V.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,V.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,V.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===pe.audio&&((r=this._detector)==null||r.destroy(),this._detector=new zt(e,t),!this._interval)){let a=()=>{this._collectVolumes(),this._interval=window.setTimeout(a,p.voiceParams.interval)};this._interval=window.setTimeout(a,p.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===pe.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===Be.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onTopologyChanged(e){e===oe.DIRECT&&(this._activeParticipants=null)}};var Er=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(Er||{}),Ir=class extends ae{constructor(e,t,i){super();this._speakerId=null;this._serverSideSpeakerDetection=!1;this._serverSideSpeakerDetection=i===oe.SERVER,this.subscribe(e,mt.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,V.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,V.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverSideSpeakerDetection)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let a=e[r].smoothed;a>t&&a>p.voiceParams.threshold&&(t=a,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*p.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverSideSpeakerDetection&&this._triggerEvent("SPEAKER_CHANGED",e)}_onTopologyChanged(e){this._serverSideSpeakerDetection=e===oe.SERVER}};var bi=class extends ae{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,V.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,mt.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===H.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),p.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),p.specListenerParams.volumeTimeout))),t===H.FAILED&&this._connectionTimeout&&(c.warn("Transport failed, send callSpecError"),f.log(T.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==H.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(c.warn("There is not connected transport, send callSpecError"),f.log(T.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),f.log(T.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&c.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var gs=1e3,fs=1e4;var Ss=15,$=class extends ae{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._myLastRequestedLayouts={};this._state="IDLE";this._participantState=K.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;f.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),f.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new Ti,p.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),gs))}static current(){return $._current}static hangupAfterInit(){$._activationMutex&&!$._current&&($._delayedHangup=!0)}static id(){var e,t;return((t=(e=$._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",a=!1,s=!1,d){return o(this,null,function*(){if($._activationMutex)throw f.log(T.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new B(D.FAILED);$._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let l=this._mediaSource.getMediaSettings();t===je.CHAT||e.length>1?this._logWithMediaSettings(T.OUTGOING_MULTIPARTY_CALL,l):this._logWithMediaSettings(T.OUTGOING_CALL,l);let u=yield this._startConversation(e,t,Qe.OUTGOING,i,r,a,s,d);if(!this._conversation)throw new B(D.UNKNOWN_ERROR);if(this._participantState=K.ACCEPTED,this._signaling.changeMediaSettings(l),yield this._processConnection(u),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),$._delayedHangup)throw new B(D.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let E=Object.values(this._participants),C;return p.batchParticipantsOnStart&&(C=v.mapSharedParticipants(E)),yield this._processConnectionSharedMovieInfo(u),g.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),C),this._onConversationParticipantListChunk(u),g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),$._current=this,this._conversation.concurrent?yield this._acceptConcurrent():p.batchParticipantsOnStart||this._setParticipantsStatus(E,J.WAITING),this._conversation}catch(l){throw this._close(l,"Unable to start conversation"),l}finally{$._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){var t;if($._activationMutex)throw f.log(T.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new B(D.FAILED);$._activationMutex=!0,this._state="PROCESSING";try{let i=!!((t=e.observedIds)==null?void 0:t.length);this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions,!i);let r=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.JOIN_CONVERSATION,r);let a=yield this._joinConversation(e);if(!this._conversation)throw new B(D.UNKNOWN_ERROR);return this._conversation.observer=i,g.onLocalStream(this._mediaSource.getStream(),r),this._conversation.waitingHall?(c.log("In waiting hall"),$._current=this,$._activationMutex=!1,this._signaling.readyToSend(),g.onLocalStatus(J.WAITING_HALL),this._conversation):this._onJoinPart2(a)}catch(i){throw $._activationMutex=!1,this._close(i,"Unable to join conversation"),i}})}_onJoinPart2(e){return o(this,null,function*(){var t,i,r,a,s,d,l;c.debug("Join conversation part 2"),$._activationMutex=!0;try{if(this._participantState=K.ACCEPTED,!this._conversation||!this._mediaSource)throw new B(D.UNKNOWN_ERROR);if(this._conversation.observer||this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._processConnection(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),$._delayedHangup)throw new B(D.CANCELED);let u=Object.values(this._participants),E;p.batchParticipantsOnStart&&(E=v.mapSharedParticipants(u.filter(O=>!O.isInRoom)));let C=[];if((i=(t=e==null?void 0:e.rooms)==null?void 0:t.rooms)==null?void 0:i.length)for(let O of e.rooms.rooms)C.push({id:O.id,name:O.name,participantCount:O.participantCount,participantIds:yield Promise.all(((a=(r=O==null?void 0:O.participantIds)==null?void 0:r.map)==null?void 0:a.call(r,this._getExternalIdByParticipantId.bind(this)))||[]),participants:((s=O==null?void 0:O.participants)==null?void 0:s.participants)?this._participantListChunkToExternalChunk(O.participants):void 0,active:O.active,muteStates:O.muteStates});let M=(l=(d=e==null?void 0:e.rooms)==null?void 0:d.roomId)!=null?l:null;return yield this._processConnectionSharedMovieInfo(e),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),E,{rooms:C,roomId:M}),this._onConversationParticipantListChunk(e),g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),$._current=this,p.batchParticipantsOnStart||this._setParticipantsStatus(u,J.WAITING),this._openTransport(u,!1),this._conversation}catch(u){throw this._close(u,"Unable to join conversation"),u}finally{$._activationMutex=!1}})}onPush(r){return o(this,arguments,function*(e,t=te.USER,i){if($._activationMutex)throw c.warn("Conversation: there is already running activation"),new B(D.REJECTED);$._activationMutex=!0;try{let a=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new B(D.UNKNOWN_ERROR);if(!a.conversation.participants.find(d=>{var l;return d.state===K.CALLED&&d.id===((l=this._conversation)==null?void 0:l.userId)}))throw c.log("Push rejected (there is an active call)"),f.log(T.PUSH,"rejected"),new B(D.REJECTED);if(yield this._processConnection(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),f.log(T.PUSH,"accepted"),$._current=this,$._delayedHangup)throw new B(D.CANCELED);$._activationMutex=!1}catch(a){throw $._activationMutex=!1,this._close(a,"Unable to handle inbound call push"),a}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(ai.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>v.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return o(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new B(D.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.ACCEPT_CONCURRENT,e),c.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),g.onCallAccepted(),this._state="ACTIVE",this._participantState=K.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return o(this,null,function*(){var t;if(this._state!=="IDLE")throw f.log(T.ERROR,"acceptIncoming"),c.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new B(D.UNKNOWN_ERROR);this._state="PROCESSING",c.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let i=this._mediaSource.getMediaSettings();this._logWithMediaSettings(T.ACCEPT_INCOMING,i),this._signaling.changeMediaSettings(i),yield this._signaling.acceptCall(i),this._participantState=K.ACCEPTED;let r=Object.values(this._participants),a;if(p.batchParticipantsOnStart&&(a=v.mapSharedParticipants(r)),g.onCallAccepted(),g.onLocalStream(this._mediaSource.getStream(),i),g.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._getMuteStatesForCurrentRoom(),a),p.useParticipantListChunk){let l=yield this._getInitialParticiapntListChunk();(t=l==null?void 0:l.participants)==null||t.forEach(u=>{let E=v.composeId(u),C=this._participants[E];C&&(C.movieShareInfos=u.movieShareInfos)}),this._onConversationParticipantListChunk({participants:l})}g.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let s=Dt(this._getMuteStatesForCurrentRoom(),Oe.MUTE),d=Dt(this._getMuteStatesForCurrentRoom(),Oe.MUTE_PERMANENT);for(let l of[s,d])l.length&&(yield this._processMuteState({mediaOptions:l,stateUpdated:!0}));return this._state="ACTIVE",this._changeFeatureSet(),p.batchParticipantsOnStart||this._setParticipantsStatus(r,J.WAITING),this._openTransport(r,!0),this._conversation}catch(i){throw this._close(i,"Unable to accept call"),i}})}decline(){return o(this,null,function*(){var e;if(this._state!=="IDLE")throw f.log(T.ERROR,"declineIncoming"),c.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",c.debug("Decline incoming call"),this._logWithMediaSettings(T.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=K.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(D.REJECTED)),this._close(new B(D.REJECTED))})}hangup(){return o(this,null,function*(){c.debug("Hangup");let e=this._state==="ACTIVE"?D.HUNGUP:D.CANCELED;f.log(T.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new B(e))):g.onHangup(new B(D.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new B(D.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=D.UNKNOWN_ERROR);let a=i.participant;yield this._onAddParticipant(v.composeId(a),a,r)})}removeParticipant(e,t=!1){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){var r;if(!this._transport)return;let i=[];for(let a of e)(a.state===K.CALLED||a.state===K.ACCEPTED)&&(this._transport.isAllocated(a.id)||this._transport.allocate(a.id,t)),a.state===K.ACCEPTED&&i.push(a.id);i.length&&this._transport.open(i,null,!!((r=this._conversation)==null?void 0:r.observer))}_close(e,t){t&&c.error(t,e),c.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(D.FAILED):f.log(T.ERROR,e.hangup),$._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([D.CANCELED,D.NOT_FRIENDS,D.CALLEE_IS_OFFLINE,D.CALLER_IS_BLOCKED,D.CALLER_IS_REJECTED].indexOf(e.hangup)!==-1||e.hangup===D.REJECTED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===D.HUNGUP&&(!e.remote||this._participantState===K.CALLED)){g.onHangup(e,i),this.destroy();return}if(e.hangup===D.MISSED&&!e.remote){g.onHangup(e,i),this.destroy();return}if(e.hangup===D.SOCKET_CLOSED&&$._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===D.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=K.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),f.destroy(),this._conversation=null,this._myLastRequestedLayouts={},$._current=null,$._delayedHangup=!1,g.onHangup(e||new B(D.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;c.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),f.destroy(),this._conversation=null,this._myLastRequestedLayouts={},$._current=null,$._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return o(this,null,function*(){let t=yield this._api.getConversationParams(e);c.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:a}=t;if(a&&i.push(a),r){let s=r.urls.filter((d,l,u)=>u.indexOf(d)===l);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return p.iceServers=i,p.wssBase=t.endpoint,p.wssToken=t.token,t.client_type&&(p.clientType=t.client_type),p.externalUserType=t.external_user_type,t})}_addGeoParamsToEndpoint(e,t){return t.isp_as_no&&(e+=`&ispAsNo=${t.isp_as_no}`),t.isp_as_org&&(e+=`&ispAsOrg=${t.isp_as_org}`),t.loc_cc&&(e+=`&locCc=${t.loc_cc}`),t.loc_reg&&(e+=`&locReg=${t.loc_reg}`),e}_startConversation(e,t,i,r,a="",s=!1,d=!1,l){return o(this,null,function*(){let u=v.uuid();c.debug("Conversation: start",{conversationId:u,opponentIds:e,opponentType:t,direction:i});let E=r.includes(le.VIDEO),C=yield this._api.startConversation(u,e,t,E,a,s,d,{onlyAdminCanShareMovie:l});c.debug("Api.startConversation",C);let M=yield this._getConversationParams(C.id);C.endpoint=this._addGeoParamsToEndpoint(C.endpoint,M);let O=yield this._connectSignaling(Ke.START,C);return yield this._setConversation(C,O,i),O})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:a,observedIds:s,payload:d}=e;c.debug("Conversation: join",{conversationId:t,joinLink:a,observedIds:s});let l=i.includes(le.VIDEO),u;if(t)u=yield this._api.joinConversation(t,l,r);else if(a)u=yield this._api.joinConversationByLink(a,l,s,d);else throw new B(D.UNKNOWN_ERROR);c.debug("Api.joinConversation",u),yield this._getConversationParams(u.id);let E=yield this._connectSignaling(Ke.JOIN,u);return yield this._setConversation(u,E,Qe.JOINING),E})}_prepareConversation(r){return o(this,arguments,function*(e,t=te.USER,i){c.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let a=this._api.getUserId();if(!a)throw new B(D.UNKNOWN_ERROR);let s=yield this._getConversationParams(e),d=s.device_idx||0,l=`${p.wssBase}?userId=${a}&entityType=${t}&deviceIdx=${d}&conversationId=${e}&token=${p.wssToken}`;l=this._addGeoParamsToEndpoint(l,s);let u={id:e,peerId:i,endpoint:l,is_concurrent:!1,p2p_forbidden:!1,device_idx:d},E=yield this._connectSignaling(Ke.ACCEPT,u);return $._current&&($._current._participantState===K.ACCEPTED||$._current._participantState===K.CALLED)?(c.log("Push rejected (busy)"),f.log(T.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(D.BUSY),Promise.reject({hangup:D.BUSY})):($._current&&($._current.destroy(),$._current=null),yield this._setConversation(u,E,Qe.INCOMING,t),E)})}_createParticipant(e){return o(this,null,function*(){var i;let t=Object.assign({id:null,externalId:null,mediaSettings:ge(),participantState:{},state:K.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[],observedIds:[],isInRoom:!1},e);if(e.externalId){let r=v.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(r,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return((i=t.observedIds)==null?void 0:i.length)&&(t.externalId.observer=!0),this._setParticipantMarkers(t,t.markers),t})}_getParticipantId(e){return o(this,null,function*(){try{let t=v.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new B(D.NETWORK_ERROR),t),t}})}_setConversation(a,s,d){return o(this,arguments,function*(e,t,i,r=te.USER){yield this._prepareParticipants(t.conversation.participants);let l=this._api.getUserId(),u=e.device_idx||0;if(!l){let M=(t.conversation.participants||[]).find(O=>v.comparePeerId(O.peerId,t.peerId));if(!M)throw new B(D.UNKNOWN_ERROR);l=Number(M.id),M.idType&&(r=M.idType),M.deviceIdx&&(u=M.deviceIdx),this._api.setUserId(l)}let E=v.composeParticipantId(l,r,u),C=yield this._getParticipantId(E);this._conversation={userId:l,compositeUserId:E,externalId:C,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],featuresPerRole:t.conversation.featuresPerRole,id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||oe.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordsInfoByRoom:new Map,muteStates:new Map,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t),observer:!1,asrInfo:null,roomId:null},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(p.forceRelayPolicy=e.p2p_forbidden),f.log(T.RELAY_POLICY,p.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new B(D.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.featuresPerRole=e.conversation.featuresPerRole,this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||oe.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 zi;return this.subscribe(e,Me.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Me.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new qt(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,Te.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,Te.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,Te.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_processConnection(e){return o(this,null,function*(){yield this._registerConnectionParticipants(e),this._processConnectionData(e)})}_prepareParticipants(e){return o(this,null,function*(){let t=e.map(i=>i.id);t.length&&(yield this._api.prepareUserIds(t))})}_onConversationParticipantListChunk(e){let t=e.participants;t&&g.onConversationParticipantListChunk(this._participantListChunkToExternalChunk(this._createParticipantListChunk(t)))}_createParticipantListChunk(e){return Ue(Ue({},{participants:[],countBefore:0,countAfter:0,markerFound:!1}),e)}_participantListChunkToExternalChunk(e){let t=v.mapSharedParticipants(e.participants.map(i=>{let r=v.composeId(i);return this._participants[r]}));return gt(Ue({},e),{participants:t})}_registerConnectionParticipants(e){return o(this,null,function*(){var i,r,a,s,d,l;yield this._registerParticipants(e.conversation.participants),((i=e.participants)==null?void 0:i.participants)&&(yield this._registerParticipants((r=e.participants)==null?void 0:r.participants));let t=(s=(a=e==null?void 0:e.rooms)==null?void 0:a.rooms)!=null?s:[];for(let u of t)yield this._registerParticipants((l=(d=u==null?void 0:u.participants)==null?void 0:d.participants)!=null?l:[],!0)})}_registerParticipants(e,t=!1){return o(this,null,function*(){if(!!this._conversation)for(let i of e){let r=v.composeId(i);if(this._isMe(r)){this._conversation.roles=i.roles||[],this._conversation.roles.length&&(c.debug(`Local roles changed: ${i.roles}`),g.onLocalRolesChanged(this._conversation.roles)),yield this._registerParticipantLocalMuteState(i);continue}if(i.state===K.HUNGUP||i.state===K.REJECTED){this._participants[i.id]&&this._removeParticipant(this._participants[i.id],D.HUNGUP);continue}this._registerParticipantInCache(yield this._createParticipant({id:r,externalId:i.externalId&&fe.fromSignaling(i.externalId,i.deviceIdx||0),mediaSettings:ge(i.mediaSettings),participantState:v.mapParticipantState(i),state:i.state,roles:i.roles||[],status:p.batchParticipantsOnStart?J.WAITING:null,muteStates:i.muteStates||{},unmuteOptions:i.unmuteOptions||[],observedIds:i.observedIds||[],markers:this._denormalizeMarkers(r,i.markers),movieShareInfos:i.movieShareInfos,isInRoom:t})),i.roles&&i.roles.length&&(c.debug(`Roles for participant [${r}] changed: ${i.roles}`),g.onRolesChanged(this._participants[r].externalId,i.roles))}})}_registerParticipantLocalMuteState(e){return o(this,null,function*(){if(!e.muteStates)return Promise.resolve();let t=Dt(e.muteStates,Oe.MUTE),i=Dt(e.muteStates,Oe.MUTE_PERMANENT);for(let r of[t,i])!r.length||(yield this._onMuteParticipant({muteStates:e.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:r,stateUpdated:!0}))})}_getStatusByTransportState(e){let t;return e===H.CONNECTED?t=J.CONNECTED:e===H.CONNECTING||e===H.OPENED?t=J.CONNECTING:e===H.RECONNECTING&&(t=J.RECONNECT),t}_registerParticipantInCache(e){return this._participants[e.id]=e}_getExistedParticipantByIdOrCreate(e){return o(this,null,function*(){return this._participants[e]||this._createParticipant({id:e})})}_getExternalIdByParticipantId(e){return o(this,null,function*(){var t;if(this._isMe(e))return this._conversation.externalId;if(p.useParticipantListChunk)return(yield this._getExistedParticipantByIdOrCreate(e)).externalId;if((t=this._participants[e])==null?void 0:t.externalId)return this._participants[e].externalId;{let i=yield this._getParticipantId(e);return this._api.cacheExternalId(e,i),i}})}_registerParticipantAndSetMarkersIfChunkEnabled(e,t){return o(this,null,function*(){if(p.useParticipantListChunk){let i=this._registerParticipantInCache(yield this._getExistedParticipantByIdOrCreate(e));return this._setParticipantMarkers(i,t),i}return this._participants[e]})}_warnParticipantNotInConversation(e){c.warn(`Participant [${e}] isn't in conversation`)}_setParticipantMarkers(e,t){return e.markers=this._denormalizeMarkers(e.id,t),e}_denormalizeMarkers(e,t){if(!t)return null;let i=Object.values(t).find(r=>"ts"in r&&"rank"in r);return Object.entries(t).reduce((r,[a,s])=>(r[a]=gt(Ue(Ue({},i),s),{id:e}),r),{})}_processConnectionData(e){return o(this,null,function*(){this._processRooms(e),this._processMuteStates(e),e.conversation.pinnedParticipantId&&(yield this._onPinParticipant(e.conversation.pinnedParticipantId)),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(ii.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)})}_processRooms(e){var i,r;let t=(r=(i=e.rooms)==null?void 0:i.roomId)!=null?r:null;this._onRoomSwitched(t,!0)}_processMuteStates(e){var i,r,a;this._setMuteStatesForRoomId((i=e.conversation)==null?void 0:i.muteStates,null);for(let s of(a=(r=e.rooms)==null?void 0:r.rooms)!=null?a:[])this._setMuteStatesForRoomId(s.muteStates,s.id);let t=this._getMuteStatesForCurrentRoom();this._onMuteParticipant({muteStates:t,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(t),muteAll:!0,stateUpdated:!0,roomId:this._conversation.roomId})}_processRecordInfos(e){var t,i,r,a;this._onRecordInfo((t=e.conversation.recordInfo)!=null?t:null);for(let s of(r=(i=e.rooms)==null?void 0:i.rooms)!=null?r:[])this._onRecordInfo((a=s.recordInfo)!=null?a:null,s.id)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new Sr(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new Ci,this.subscribe(this._transport,V.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,V.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,V.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,V.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,V.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,V.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,V.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,V.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,V.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,V.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,V.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this)),this.subscribe(this._transport,V.ASR_TRANSCRIPTION,this._onAsrTranscription.bind(this));let e=this._conversation.direction===Qe.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===K.ACCEPTED||t.state===K.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new vr(this._transport),this.subscribe(this._volumesDetector,mt.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new Ir(this._volumesDetector,this._transport,this._conversation.topology),this.subscribe(this._speakerDetector,Er.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Ri(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new bi(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=y.getCameras().length,t=y.getMicrophones().length;c.debug("Cameras: "+e+(y.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(y.hasMicrophonePermission()?"✔":"✖")),f.log(T.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){f.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===K.CALLED||e.state===K.ACCEPTED||this._state==="CLOSE"||(e.id===this._lastSignalledActiveSpeakerId&&(this._lastSignalledActiveSpeakerId=null),!!this._participants[e.id]&&(t===D.HUNGUP?this._setParticipantsStatus([e],J.HANGUP):this._setParticipantsStatus([e],J.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Pe.CAMERA,stopStream:!0}]),delete this._participants[e.id],g.onRemoteRemoved(e.externalId,e.markers)))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(a=>a.stop()),(i=e.secondStream)==null||i.getTracks().forEach(a=>a.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){c.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return o(this,null,function*(){c.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===K.ACCEPTED||r.state===K.CALLED)){c.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(r=this._registerParticipantInCache(yield this._createParticipant({id:e,externalId:t.externalId&&fe.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:ge(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[],observedIds:t.observedIds||[]}))),this._setParticipantsStatus([r],J.WAITING),i?(r.state=K.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=K.CALLED,this._transport.allocate(r.id,!0),f.log(T.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){c.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=Ss;i++){let r=v.compose(e,i),a=this._participants[r];a&&t.push(a)}if(!t.length){this._warnParticipantNotInConversation(e);return}if(this._transport)for(let i of t)this._transport.close(i.id);f.log(T.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new qt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(se.UNKNOWN)})}toggleScreenCapturing(e,t){return o(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e,t):Promise.reject(se.UNKNOWN)})}setVideoStream(e,t=!1){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return o(this,null,function*(){if(this._mediaSource)return f.log(T.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return f.log(T.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return o(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let a=typeof r.uid=="object"?r.uid:fe.fromId(r.uid),s=fe.toString(a);i[s]=r.priority}for(let r of Object.values(this._participants)){let a=fe.toString(r.externalId);i.hasOwnProperty(a)&&(t[r.id]=i[a])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return o(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return o(this,null,function*(){let t={};return t[qe(e)]={keyFrameRequested:!0},this._signaling.updateDisplayLayout(t)})}requestTestMode(e,t){return o(this,null,function*(){return this._signaling.requestTestMode(e,t)})}updateDisplayLayout(e){return o(this,null,function*(){if(e.length<1||!this._signaling.ready)return;c.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let a=typeof r.uid=="object"?r.uid:fe.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(a);if(!s){let E=fe.toString(a);c.log(`Unknown participant external ID ${E}`);continue}let d=v.compose(s,a.deviceIdx),l=qe({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),u=this._participants[d];u?u.lastRequestedLayouts[l]=r:this._isMe(d)&&(this._myLastRequestedLayouts[l]=r),Kt(r)?(this._isMe(d)&&delete this._myLastRequestedLayouts[l],this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now())):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&p.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=r)}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>p.videoTracksCount;){let r=i.next();if(r.done){c.error("Cannot accommodate all streaming requests: tracks available "+p.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]={stopStream:!0}}yield this._sendUpdateDisplayLayout(t)})}feedback(e){return this._signaling.feedback(e)}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(c.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=$t(e),r=this._participants[i.participantId],{externalId:a}=this._conversation,s=this._isMe(i.participantId);if(r){if(i.streamName&&(i.mediaType===Pe.STREAM||i.mediaType===Pe.MOVIE)){let d={stream:null,streamName:i.streamName,mediaType:i.mediaType};s?g.onLocalLive(a,d):g.onRemoteLive(r.externalId,d)}else s||g.onRemoteStream(r.externalId,null);f.log(T.PAT_DEALLOCATED)}else c.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return o(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,a]of Object.entries(t.errorCodeByParticipantId||{})){let s=$t(r),d=this._participants[s.participantId];if(d){let l;typeof a!="number"?(c.warn(`Unexpected error code ${a} received for participant ${s.participantId}`),l=ea.UNKNOWN_ERROR):l=ta(a),i.push({externalId:d.externalId,errorReason:l})}}if(i&&i.length)throw new Mi("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+fs>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]={stopStream:!0}}while(!0);this._sendUpdateDisplayLayout(e)}_onParticipantSourcesUpdate(e){if(this._conversation){c.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){c.log("Promoted in waiting hall",!e.demote),e.demote?(c.log("Kicked from waiting hall"),this._close(new B(D.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return o(this,arguments,function*(e,t=0,i=[]){c.log(`Chat room updated: ${e}`);let a=[],s=[];i.length&&(i.forEach(d=>{if(d.externalId){let l=ve.fromSignaling(d.externalId);a.push(l),this._api.cacheExternalId(d.id.id,l)}else s.push(v.decomposeId(d.id.id).id)}),s.length&&!a.length&&(a=yield this._api.getExternalIdsByOkIds(s))),g.onChatRoomUpdated(e,t,a)})}_onSharedMovieUpdate(e){return o(this,null,function*(){let{externalId:t}=this._conversation,{data:i}=e;for(let r of i)if(this._isMe(r.participantId))g.onLocalLiveUpdate(t,r);else{let s=yield this._getExternalIdByParticipantId(r.participantId);s&&g.onRemoteLiveUpdate(s,r)}})}_onSharedMovieInfoStarted(e){return o(this,null,function*(){c.log(`Shared movie started data received: ${e.notification}`),yield this._processSharedMovieInfo(e.movieShareInfo)})}_processSharedMovieInfos(e){return o(this,null,function*(){e&&(yield Promise.all(e.map(t=>this._processSharedMovieInfo(t))))})}_processSharedMovieInfo(e){return o(this,null,function*(){var r;if(!e)return;let{externalId:t}=this._conversation;if(this._isMe(e.initiatorId))g.onLocalSharedMovieInfo(t,e);else{let a=yield this._getExternalIdByParticipantId(e.initiatorId);a&&g.onRemoteSharedMovieInfo(a,e)}this._transport.getTopology()===oe.SERVER&&this._transport.getState()===H.IDLE&&this._participantState!==K.CALLED&&this._transport.open(this._transport.allocated(),null,!!((r=this._conversation)==null?void 0:r.observer),!0)})}_processConnectionSharedMovieInfo(e){return o(this,null,function*(){let t=e.conversation.participants.find(i=>this._isMe(v.composeId(i)));yield this._processSharedMovieInfos(t==null?void 0:t.movieShareInfos)})}_onSharedMovieInfoStopped(e){return o(this,null,function*(){c.log(`Shared movie stopped data received: ${e.notification}`);let{externalId:t}=this._conversation,{initiatorId:i,movieId:r,source:a}=e,s={initiatorId:i,movieId:r,source:a};if(this._isMe(i))g.onLocalSharedMovieStoppedInfo(t,s);else{let l=yield this._getExternalIdByParticipantId(i);l&&g.onRemoteSharedMovieStoppedInfo(l,s)}})}_onFeaturesPerRoleChanged(e){c.log(`Features per role changed: ${e.notification}`),g.onFeaturesPerRoleChanged(e.featuresPerRole)}_waitForStreamIfNeeded(e){var d,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||p.producerScreenDataChannel&&t.mediaType===Pe.SCREEN)return;let i=qe(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){c.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),f.log(T.PAT_OUTDATED_RESPONSE);return}let a=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(a,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let u=t.participantId,E=this._participants[u],{externalId:C}=this._conversation,M=this._isMe(u);if(!E&&!M){f.log(T.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${u}`);return}let O=M?C:E.externalId,w=this._streamByStreamId.get(a);if(!w){f.log(T.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}f.log(T.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,a);let F=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(F===Pe.STREAM||F===Pe.MOVIE){if((l=e.participantStreamDescription)==null?void 0:l.streamName){let de={streamName:e.participantStreamDescription.streamName,stream:w,mediaType:F};M?g.onLocalLive(O,de):g.onRemoteLive(O,de)}}else if(p.producerScreenTrack&&F===Pe.SCREEN)g.onRemoteScreenStream(E.externalId,w);else if(!M){let de=(p.producerScreenTrack?null:E.secondStream)||w;g.onRemoteStream(E.externalId,de)}}else{c.debug(`Waiting for ${s} until stream ${a} for ${i} is switched`);let u=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,u)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(qe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(qe(i)))return i}else{let i={participantId:t,mediaType:Pe.CAMERA};if(this._streamIdByStreamDescription.has(qe(i)))return i;let r={participantId:t,mediaType:Pe.SCREEN};if(this._streamIdByStreamDescription.has(qe(r)))return r}return c.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?v.includesOneOf(this._conversation.roles,[Xe.ADMIN,Xe.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!v.includesOneOf(this._conversation.roles,[Xe.ADMIN,Xe.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}startAsr(){return o(this,null,function*(){yield this._signaling.startAsr()})}stopAsr(){return o(this,null,function*(){yield this._signaling.stopAsr()})}requestAsr(e){return o(this,null,function*(){yield this._signaling.requestAsr(e)})}muteParticipant(){return o(this,arguments,function*(e=null,t,i=[],r=null){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i,r)})}enableFeatureForRoles(e,t){return o(this,null,function*(){yield this._signaling.enableFeatureForRoles(e,t)})}pinParticipant(e,t){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return o(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return o(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Hr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return o(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Oa(e));let a=yield this._signaling.getWaitingHall(r,t,i);if(a.error)return Promise.reject(a.message);let s=a.participants||[],d=[],l=[],u=null;return s.length&&(s.forEach(E=>{if(E.externalId){let C=ve.fromSignaling(E.externalId);d.push(C),this._api.cacheExternalId(E.id.id,C)}else l.push(v.decomposeId(E.id.id).id)}),l.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(l)),a.hasMore&&(u=ka(s[s.length-1].id))),{participants:d,pageMarker:u,totalCount:a.totalCount||0}})}promoteParticipant(e,t){return o(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return o(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return o(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return o(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(r){return o(this,arguments,function*({movieId:e,gain:t,metadata:i}){let a={movieId:e};(t||t===0)&&(a.gain=t),i&&(a.metadata=i);let s=yield this._signaling.addMovie(a);if(s.error)throw new Error(s.error);return{movieId:s.movieId,streamType:s.streamType}})}updateMovie(e){return o(this,null,function*(){let t=yield this._signaling.updateMovie(e);if(t.error)throw new Error(t.error)})}removeMovie(e){return o(this,null,function*(){let t={movieId:e},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}updateRooms(e,t){return o(this,null,function*(){let i=yield this._signaling.updateRooms(e,t);if(i.error)throw new Error(i.error)})}activateRooms(e,t){return o(this,null,function*(){let i=yield this._signaling.activateRooms(e,t);if(i.error)throw new Error(i.error)})}switchRoom(e,t){return o(this,null,function*(){let i=yield this._signaling.switchRoom(e,t);if(i.error)throw new Error(i.error)})}removeRooms(e){return o(this,null,function*(){let t=yield this._signaling.removeRooms(e);if(t.error)throw new Error(t.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",a=null,s=null){return o(this,null,function*(){let d={movieId:i,name:t,privacy:r,groupId:a,roomId:s,streamMovie:!e},l=yield this._signaling.startStream(d);return l.error?Promise.reject(l.message):l})}stopStream(e=null){return o(this,null,function*(){let t=yield this._signaling.stopStream({roomId:e});return t.error?Promise.reject():t})}recordSetRole(e,t,i=null){return o(this,null,function*(){let r=yield this._signaling.recordSetRole(e,t,i);if(r.error)throw new Error(r.error)})}getStreamInfo(){return o(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return o(this,null,function*(){var r;if(e<p.videoMinWidth||t<p.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<p.videoMinWidth||i.effect.height<p.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");p.videoEffectMaxHeight=i.effect.height,p.videoEffectMaxWidth=i.effect.width}return p.videoMaxWidth=e,p.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return o(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}getParticipants(e){return o(this,null,function*(){let t=e.externalIds.map(s=>({id:s.id,type:p.externalUserType})),i=yield this._signaling.getParticipants(t);if(i.error)throw new Error(i.error);let r=i.participants,a=this._transport.getState();return Promise.all(r.map(s=>o(this,null,function*(){var l;let d=v.composeId(s);return this._createParticipant({id:d,externalId:s.externalId&&fe.fromSignaling(s.externalId,s.deviceIdx||0),mediaSettings:ge(s.mediaSettings),participantState:v.mapParticipantState(s),state:s.state,roles:s.roles||[],status:(l=this._getStatusByTransportState(a))!=null?l:J.WAITING,muteStates:s.muteStates||{},unmuteOptions:s.unmuteOptions||[],observedIds:s.observedIds||[],markers:this._denormalizeMarkers(d,s.markers)})}))).then(v.mapSharedParticipants)})}getParticipantListChunk(e){return o(this,null,function*(){var d;c.log("Request participant list chunk",e);let t=yield this._signaling.getParticipantListChunk(e);if(t.error)throw new Error(t.error);let i=this._createParticipantListChunk(t.chunk),r=i.participants.filter(l=>{let u=v.composeId(l);return!this._participants[u]});yield this._registerParticipants(r);let a=(d=this._transport)==null?void 0:d.getState();return i.participants.forEach(l=>{var C,M;let u=v.composeId(l),E=this._participants[u];E.status=(C=this._getStatusByTransportState(a))!=null?C:J.WAITING,E.movieShareInfos=l.movieShareInfos,Object.assign(E.mediaSettings,ge(l.mediaSettings)),Object.assign(E.muteStates,l.muteStates),E.unmuteOptions=(M=l.unmuteOptions)!=null?M:E.unmuteOptions,this._openTransport([E],!0)}),this._participantListChunkToExternalChunk(i)})}_getInitialParticiapntListChunk(){return o(this,null,function*(){let e=p.participantListChunkInitIndex,t=p.participantListChunkInitCount,i="GRID",r=yield this._signaling.getParticipantListChunk({listType:i,fromIdx:e,count:t});return c.debug("Get initial participant list chunk",r.chunk),r.chunk})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t,i;!this._conversation||(c.debug("Local media stream changed",e.mediaSettings),g.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return o(this,null,function*(){var t,i;if(c.log("Screen sharing changed",e.track,e.mediaSettings),p.consumerScreenTrack){let r=e.track?new MediaStream([e.track]):null;g.onScreenStream(r,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&!((i=this._conversation)==null?void 0:i.observer)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){c.debug(`Remote media settings changed [${e}]`,t);let{externalId:i}=this._conversation;if(this._isMe(e)){g.onLocalMediaSettings(i,t);return}let a=this._participants[e];if(!a){this._warnParticipantNotInConversation(e);return}a.mediaSettings=t,this._state==="ACTIVE"&&g.onRemoteMediaSettings(a.externalId,t,a.markers),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t)}_changeRemoteParticipantState(e,t){c.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];if(!i){this._warnParticipantNotInConversation(e);return}i.participantState=t||{},this._state==="ACTIVE"&&g.onRemoteParticipantState(i.externalId,i.participantState,i.markers)}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(c.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),g.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case 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,e.roomId);case k.RECORD_STOPPED:return this._onRecordInfo(null,e.roomId);case k.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case k.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case k.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin,e.markers);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);case k.JOIN_LINK_CHANGED:return this._onJoinLinkChanged(e);case k.FEEDBACK:return this._onFeedback(e);case k.MOVIE_UPDATE_NOTIFICATION:return this._onSharedMovieUpdate(e);case k.MOVIE_SHARE_STARTED:return this._onSharedMovieInfoStarted(e);case k.MOVIE_SHARE_STOPPED:return this._onSharedMovieInfoStopped(e);case k.ROOMS_UPDATED:return this._onRoomsUpdated(e);case k.ROOM_UPDATED:return this._onRoomUpdated(e);case k.ROOM_PARTICIPANTS_UPDATED:return this._onRoomParticipantsUpdated(e);case k.FEATURES_PER_ROLE_CHANGED:return this._onFeaturesPerRoleChanged(e);case k.ASR_STARTED:return this._onAsrInfo(e.asrInfo);case k.ASR_STOPPED:return this._onAsrInfo(null)}}_onSignalingReconnect(e){return o(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._conversation.featuresPerRole=e.conversation.featuresPerRole,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?yield this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&(yield this._onPinParticipant(this._conversation.pinnedParticipantId,!0))),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let a of e.conversation.participants){let s=v.composeId(a),d=a.roles||[];if(this._isMe(s)){t=ge(a.mediaSettings),Nt(this._conversation.roles,d)||this._onRolesChanged(s,d);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:a.id,participant:a,mediaSettings:a.mediaSettings});else{let u=ge(a.mediaSettings);la(u,l.mediaSettings)||this._changeRemoteMediaSettings(s,u);let E=v.mapParticipantState(a),C=l.participantState;v.isEqualParticipantState(E,C)||this._changeRemoteParticipantState(s,E),Nt(d,l.roles)||this._onRolesChanged(l.id,d)}}for(let a of i)r.indexOf(a)<0&&this._removeParticipant(this._participants[a],D.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._processRecordInfos(e),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){c.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return o(this,null,function*(){let t=v.composeMessageId(e),i=v.getPeerIdString(e.peerId);if(c.debug(`Participant accepted call [${t}]`),this._conversation&&this._isMe(t)){this._close(new B(D.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(r=this._registerParticipantInCache(yield this._createParticipant({id:t,mediaSettings:ge(e.mediaSettings)}))),r.state=K.ACCEPTED,r.mediaSettings=ge(e.mediaSettings),this._logWithMediaSettings(T.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Qe.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){return o(this,null,function*(){c.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=v.composeMessageId(e);if(this._conversation&&this._isMe(t)){this._close(new B(e.reason,{remote:!0}));return}yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers);let i=this._participants[t];if(!i){this._warnParticipantNotInConversation(t);return}this._transport&&this._transport.close(t),i.state=e.reason===D.REJECTED?K.REJECTED:K.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,D.HUNGUP)})}_onAddedParticipant(e){return o(this,null,function*(){var r,a;c.debug(`Participant added [${e.participantId}]`);let t=v.composeMessageId(e),i=this._participants[t];if(i&&i.state!==K.HUNGUP&&i.state!==K.REJECTED){c.debug(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&fe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:v.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[]}))),i.state=K.CALLED,i.mediaSettings=ge((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=v.mapParticipantState(e.participant),i.roles=((a=e.participant)==null?void 0:a.roles)||[],this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),g.onParticipantAdded(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return o(this,null,function*(){var r,a;c.debug(`Participant joined [${e.participantId}]`);let t=v.composeMessageId(e),i=this._participants[t];if(i&&i.state===K.ACCEPTED){c.warn(`Participant [${t}] is already in conversation and is active`);return}i||(i=this._registerParticipantInCache(yield this._createParticipant({id:t,externalId:e.participant.externalId&&fe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:ge(e.participant.mediaSettings),state:e.participant.state,participantState:v.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},movieShareInfos:e.participant.movieShareInfos,unmuteOptions:e.participant.unmuteOptions||[],observedIds:e.participant.observedIds||[],markers:this._denormalizeMarkers(t,e.participant.markers)}))),this._conversation&&this._conversation.direction===Qe.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=K.ACCEPTED,i.mediaSettings=ge(e.mediaSettings),i.participantState=v.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],J.CONNECTED):this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id],null,!!((a=this._conversation)==null?void 0:a.observer))),g.onParticipantJoined(i.externalId,i.markers),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i),g.onMuteStates(i.muteStates,i.unmuteOptions,Object.keys(i.muteStates),!1,!1,i.externalId,void 0,!0),yield this._processSharedMovieInfos(i.movieShareInfos)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new B(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){return o(this,null,function*(){let t=v.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteMediaSettings(t,ge(e.mediaSettings))})}_onParticipantStateChanged(e){return o(this,null,function*(){let t=v.composeMessageId(e);yield this._registerParticipantAndSetMarkersIfChunkEnabled(t,e.markers),this._changeRemoteParticipantState(t,v.mapParticipantState(e))})}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._conversation.featuresPerRole=e.featuresPerRole,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),g.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ge(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),p.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled,i.isAudioSharingEnabled))})}_onSettingsUpdate(e){c.debug("Got settings update notification",e);let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=_r(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){c.debug("Got video quality update notification",e);let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=_r(this._serverSettings,r),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=v.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return o(this,null,function*(){g.onDeviceSwitched(le.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return o(this,null,function*(){let t=v.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),g.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return o(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=v.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),g.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e,t=null){return o(this,null,function*(){var a;if(!this._conversation)return;let i=this._conversation.recordsInfoByRoom.get(t),r=!1;if(!i!=!e?r=!0:i&&e&&(r=i.recordMovieId!==e.recordMovieId),r)if(this._conversation.recordsInfoByRoom.set(t,e),e){let s=yield this._getParticipantId(e.initiator);g.onRecordStarted(s,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId,t)}else g.onRecordStopped(t);e&&this._transport.getTopology()===oe.SERVER&&this._participantState!==K.CALLED&&this._transport.open(this._transport.allocated(),null,!!((a=this._conversation)==null?void 0:a.observer),!0)})}_changeRecordInfoForRoom(){return o(this,null,function*(){if(!this._conversation)return;let e=this._conversation.roomId,t=this._conversation.recordsInfoByRoom.get(e);if(t){let i=yield this._getParticipantId(t.initiator);g.onRecordStarted(i,t.recordMovieId,t.recordStartTime,t.recordType,t.recordExternalMovieId,t.recordExternalOwnerId,e)}else g.onRecordStopped(e)})}_onAsrInfo(e){return o(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.asrInfo!=!e?t=!0:this._conversation.asrInfo&&e&&(t=this._conversation.asrInfo.movieId!==e.movieId),t)if(e){let i=yield this._getParticipantId(e.initiatorId);g.onAsrStarted(i,e.movieId)}else g.onAsrStopped();this._conversation.asrInfo=e})}_onAsrTranscription(e){return o(this,null,function*(){if(!this._conversation)return;let t=yield this._getParticipantId(e.participantId);g.onAsrTranscription(t,e.text,e.timestamp,e.duration)})}_onRolesChanged(e,t){if(this._conversation&&this._isMe(e)&&!Nt(this._conversation.roles,t)){c.debug(`Local roles changed: ${t}`),this._conversation.roles=t,g.onLocalRolesChanged(t),this._processMuteState({mediaOptions:Dt(this._getMuteStatesForCurrentRoom(),Oe.MUTE_PERMANENT),stateUpdated:!0}),v.includesOneOf(t,[Xe.ADMIN,Xe.CREATOR])&&this._refreshRooms(!0);return}let i=this._participants[e];i&&!Nt(i.roles,t)&&(c.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,g.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){var u;if(!this._conversation)return;let i=(u=e.roomId)!=null?u:null,r=e.muteStates||{},a=e.unmuteOptions||[],s=e.mediaOptions||[],d=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&!this._isMe(e.participantId)){if(!this._isCallAdmin()){c.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let E=this._participants[e.participantId];E&&(c.debug(`Mute states for participant [${e.participantId}] changed`,r),g.onMuteStates(r,a,s,e.muteAll,e.unmute,E.externalId,d==null?void 0:d.externalId,e.stateUpdated,e.requestedMedia,e.roomId));return}let l=this._getMuteStatesForRoomId(i);if(!(v.isObjectsEquals(l,r)&&v.isArraysEquals(this._conversation.unmuteOptions,a)&&!s.length)){if(this._setMuteStatesForRoomId(r,i),this._conversation.unmuteOptions=a,this._isMe(e.adminId)){e.muteAll&&g.onMuteStates(r,a,s,e.muteAll,e.unmute,null,this._conversation.externalId,e.stateUpdated,e.requestedMedia,e.roomId);return}yield this._processMuteState({mediaOptions:s,muteAll:e.muteAll,unmute:e.unmute,serverSettings:t,admin:d,stateUpdated:e.stateUpdated,requestedMedia:e.requestedMedia,roomId:e.roomId})}})}_changeMuteStatesForRoom(e,t){if(!this._conversation)return;this._conversation.unmuteOptions=[];let i=this._getMuteStatesForRoomId(t),r=this._getMuteStatesForRoomId(e),a=Object.keys(i),s=Object.keys(r);this._processMuteState({mediaOptions:Array.from(new Set([...a,...s])),roomId:e,muteAll:!0,stateUpdated:!0})}_processMuteState(u){return o(this,arguments,function*({mediaOptions:e=[],muteAll:t=!1,unmute:i=!1,serverSettings:r=null,admin:a=null,stateUpdated:s,requestedMedia:d,roomId:l=null}){if(!this._conversation||!this._mediaSource||this._participantState!==K.ACCEPTED)return;let E=Object.assign({},this._getMuteStatesForRoomId(l)),C=this._conversation.unmuteOptions,M=this._mediaSource.getMediaSettings(),O=Object.entries(E);for(let[w,F]of O)if(!(F!==Oe.MUTE&&F!==Oe.MUTE_PERMANENT)&&(this._isCallAdmin()&&F===Oe.MUTE_PERMANENT&&!t&&(E[w]=Oe.MUTE),!(!e.includes(w)||i)))switch(w){case le.VIDEO:M.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(g.onDeviceSwitched(le.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case le.AUDIO:M.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(g.onDeviceSwitched(le.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case le.SCREEN_SHARING:M.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(g.onDeviceSwitched(le.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1,!1));break;case le.AUDIO_SHARING:M.isAudioSharingEnabled&&!(r==null?void 0:r.isAudioSharingEnabled)&&(g.onDeviceSwitched(le.AUDIO_SHARING,!1),yield this.toggleScreenCapturing(M.isScreenSharingEnabled,!1));break}g.onMuteStates(E,C,e,t,i,null,a==null?void 0:a.externalId,s,d,l)})}_onPinParticipant(e,t=!1,i){return o(this,null,function*(){if(!this._conversation)return;let r=this._conversation.pinnedParticipantId;if(r&&r!==e)if(this._isMe(r))g.onLocalPin(!0);else{let a=yield this._getExternalIdByParticipantId(r);a&&g.onPinnedParticipant(a,!0,this._denormalizeMarkers(e,i))}if(this._isMe(e))g.onLocalPin(t);else{let a=yield this._getExternalIdByParticipantId(e);a&&g.onPinnedParticipant(a,t,this._denormalizeMarkers(e,i))}this._conversation.pinnedParticipantId=t?null:e})}_onOptionsChanged(e){this._conversation&&!Vr(this._conversation.options,e)&&(this._conversation.options=e,g.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let a;if(this._isMe(i)||i==="")a=this._conversation.networkRating;else if(this._participants[i])a=this._participants[i].networkRating;else continue;if(a!==r)if(this._isMe(i)||i==="")this._conversation.networkRating=r,g.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;c.log("Received network status update: ",e),g.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(p.producerScreenTrack){g.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,p.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){c.error("Received remote stream notification for a participant that has no track associated with it",r);return}let a=this._streamIdByStreamDescription.get(r);if(!a||this._streamWaitTimerByStreamDescription.has(r)){c.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(a);if(!s){f.log(T.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}g.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&g.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===oe.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(ri.ADD_PARTICIPANT);g.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&g.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let a=this._participants[i];a&&a.externalId&&t.push({uid:a.externalId,volume:r.real})}g.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){c.debug(`Transport state has changed: ${t}`,e);let i=this._getStatusByTransportState(t);if(!i)return;let r=e.reduce((a,s)=>{if(s in this._participants){let d=this._participants[s];a.push(d),t===H.CONNECTED&&(d.remoteStream||(d.mediaSettings&&this._changeRemoteMediaSettings(s,d.mediaSettings),this._changeRemoteParticipantState(s,d.participantState)),this._updateDisplayLayoutFromCache(s))}else this._warnParticipantNotInConversation(s);return a},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){var t;if(c.debug(`Local transport state has changed: ${e}`),e===H.CONNECTED&&(g.onLocalStatus(J.CONNECTED),((t=this._transport)==null?void 0:t.getTopology())===oe.SERVER)){let i=Object.values(this._myLastRequestedLayouts);yield this.updateDisplayLayout(i)}e===H.CONNECTING&&g.onLocalStatus(J.CONNECTING),e===H.RECONNECTING&&g.onLocalStatus(J.RECONNECT),e===H.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(D.FAILED)),this._close(new B(D.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(Be.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i),g.onRemoteMixedAudioStream(t);else if(e.startsWith(Be.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))c.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{c.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(c.warn(`Conversation: track added before participant [${e}]`),r=this._registerParticipantInCache(yield this._createParticipant({id:e})),this._setParticipantsStatus([r],J.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(g.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===pe.audio&&(this._audioOutput.add(i),p.preserveAudioTracks||t.removeTrack(i)),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;g.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),p.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(c.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case pe.audio:this._removeAudioTrack(e,t,i);break;case pe.video:case pe.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==Be.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onTopologyChanged(e){e===oe.DIRECT&&(this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)),this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let a=this._participants[r];e||this._lastStalled[r]?t.push(a):i.push(a)}t.length&&this._setParticipantsStatus(t,J.RECONNECT),i.length&&this._setParticipantsStatus(i,J.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(a=>{if(t[a]=!0,!this._lastStalled[a]){let s=this._participants[a];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[a]}),Object.keys(this._lastStalled).forEach(a=>{let s=this._participants[a];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,J.RECONNECT),r.length&&this._setParticipantsStatus(r,J.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!y.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(c.debug("Toggle join availability",{available:t,chatId:e}),g.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==oe.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((a,s)=>(s.status!==t&&(s.status=t,p.batchParticipantsOnStart?a.push(s.externalId):g.onParticipantStatus(s.externalId,t,i)),a),[]);!r.length||p.batchParticipantsOnStart&&g.onRemoteStatus(r,t,i)}_onJoinLinkChanged(e){g.onJoinLinkChanged(e.joinLink)}_onRoomsUpdated(e){return o(this,null,function*(){var i,r;let t={};for(let a of Object.keys(Et)){let s=e.updates[a];!s||(t[a]={rooms:yield Promise.all(((r=(i=s==null?void 0:s.rooms)==null?void 0:i.map)==null?void 0:r.call(i,this._convertRoomToExternal.bind(this)))||[]),roomIds:s==null?void 0:s.roomIds,deactivated:s==null?void 0:s.deactivated})}g.onRoomsUpdated(t)})}_onRoomUpdated(e){return o(this,null,function*(){let t=yield this._convertRoomToExternal(e.room);e.events.some(i=>i===Et.UPDATE)&&(e.muteStates!==void 0&&this._setMuteStatesForRoomId(e.muteStates,e.roomId),e.recordInfo!==void 0&&this._conversation.recordsInfoByRoom.set(e.roomId,e.recordInfo)),g.onRoomUpdated(e.events,e.roomId,t,e.deactivate)})}_convertRoomToExternal(e){return o(this,null,function*(){var a,s,d,l,u,E;if(!e)return null;let[t,i,r]=yield Promise.all([Promise.all(((s=(a=e==null?void 0:e.participantIds)==null?void 0:a.map)==null?void 0:s.call(a,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((l=(d=e==null?void 0:e.addParticipantIds)==null?void 0:d.map)==null?void 0:l.call(d,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((E=(u=e==null?void 0:e.removeParticipantIds)==null?void 0:u.map)==null?void 0:E.call(u,this._getExternalIdByParticipantId.bind(this)))||[])]);return{id:e.id,name:e.name,participantCount:e.participantCount,participantIds:t,addParticipantIds:i,removeParticipantIds:r,participants:e.participants,active:e.active,muteStates:e.muteStates}})}_onRoomParticipantsUpdated(e){return o(this,null,function*(){var E,C,M,O,w;let t=this._transport.getState(),i=(E=e.roomId)!=null?E:null,[r,a]=yield Promise.all([Promise.all(((M=(C=e.addedParticipantIds)==null?void 0:C.map)==null?void 0:M.call(C,this._getExternalIdByParticipantId.bind(this)))||[]),Promise.all(((w=(O=e==null?void 0:e.addedParticipants)==null?void 0:O.map)==null?void 0:w.call(O,F=>o(this,null,function*(){var q;let de=v.composeId(F);return this._createParticipant({id:de,externalId:F.externalId&&fe.fromSignaling(F.externalId,F.deviceIdx||0),mediaSettings:ge(F.mediaSettings),participantState:v.mapParticipantState(F),state:F.state,roles:F.roles||[],status:(q=this._getStatusByTransportState(t))!=null?q:J.WAITING,muteStates:F.muteStates||{},unmuteOptions:F.unmuteOptions||[],observedIds:F.observedIds||[],markers:this._denormalizeMarkers(de,F.markers)})})))||[])]),s=!1;for(let F of a)F.id===this._conversation.compositeUserId&&(s=!0),this._registerParticipantInCache(F);this._openTransport(a,!0);let d=[],l=[];if(e==null?void 0:e.removedParticipantMarkers){for(let F of e.removedParticipantMarkers)F.GRID&&l.push(this._getExternalIdByParticipantId(F.GRID.id));d=yield Promise.all(l)}s&&this._onRoomSwitched(i);let u={roomId:i,participantCount:e.participantCount,addedParticipantIds:r,addedParticipants:v.mapSharedParticipants(a),removedParticipantMarkers:e==null?void 0:e.removedParticipantMarkers,removedParticipantIds:d};g.onRoomParticipantsUpdated(u)})}_onRoomSwitched(e,t=!1){if(!this._conversation||this._conversation.roomId===e)return;let i=this._conversation.roomId;if(this._conversation.roomId=e,t){g.onRoomStart(e);return}g.onRoomSwitched(e),e!==null&&!this._isCallAdmin()&&this._refreshRooms(!1),this._changeRecordInfoForRoom(),this._changeMuteStatesForRoom(e,i)}_refreshRooms(e){return o(this,null,function*(){var r,a;let i=(a=(r=(yield this._signaling.getRooms(e)).rooms)==null?void 0:r.rooms)!=null?a:[];for(let s of i)this._setMuteStatesForRoomId(s.muteStates,s.id),this._conversation.recordsInfoByRoom.set(s.id,s.recordInfo);e&&g.onRoomsUpdated({[Et.UPDATE]:{rooms:yield Promise.all(i.map(this._convertRoomToExternal.bind(this)))}})})}_onFeedback(e){return o(this,null,function*(){let t=a=>o(this,null,function*(){return(yield this._registerParticipantAndSetMarkersIfChunkEnabled(a)).externalId}),i=e.feedback.map(a=>o(this,null,function*(){let s=a.items.map(l=>o(this,null,function*(){if(l.participantId===this._conversation.compositeUserId)return Promise.resolve(gt(Ue({},l),{participantId:this._conversation.externalId}));let u=yield t(l.participantId);return gt(Ue({},l),{participantId:u})})),d=yield Promise.all(s);return gt(Ue({},a),{items:d})})),r=yield Promise.all(i);g.onFeedback(r,e.roomId)})}_isMe(e){var t;return e===((t=this._conversation)==null?void 0:t.compositeUserId)}_getMuteStatesForRoomId(e=null){var i;return(i=this._conversation.muteStates.get(e))!=null?i:{}}_getMuteStatesForCurrentRoom(){return this._getMuteStatesForRoomId(this._conversation.roomId)}_setMuteStatesForRoomId(e={},t=null){this._conversation.muteStates.set(t,e)}},N=$;N._delayedHangup=!1;var Mi=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Mi.prototype),this.participantErrors=t}};var Ot,Qt=null;function vs(){return o(this,null,function*(){var n;if(p.apiEnv!=="AUTO")return p.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(n=i==null?void 0:i.Answer[0])==null?void 0:n.data;if(!r)throw new Error("Wrong DNS response");return c.debug("Resolved API endpoint",r),r}catch(e){return c.warn("Failed to resolve API endpoint using DNS, default is used",e),p.apiEndpoint}})}function Na(){return o(this,null,function*(){return Ot||Qt||(Qt=vs(),Ot=yield Qt,Qt=null,Ot)})}function Ua(){if(!p.apiKey)throw new B(se.API,{message:"Required argument apiAppKey not passed"})}function Tr(i){return o(this,arguments,function*(n,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;yield Na();let r=Fa(n,e,t),a=new window.Blob([r],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${Ot}/fb.do`,a)})}function Ba(i){return o(this,arguments,function*(n,e={},t=!1){yield Na();let r=Fa(n,e,t);return Es(r)})}function Es(n){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${Ot}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(a){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(n)})})}function Fa(n,e={},t=!1){e.method=n,e.format="JSON",e.application_key||(e.application_key=p.apiKey),t||(ne.sessionKey?e.session_key=ne.sessionKey:ne.accessToken&&(e.access_token=ne.accessToken));for(let[r,a]of Object.entries(e))typeof a=="object"&&(e[r]=JSON.stringify(a));let i="";for(let[r,a]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(a)}`;return i}var Ts=10,Cs=700,Rs=3e3,Xt=class extends ft{constructor(){super(...arguments);this._userId=null;this._externalUidsCache=new Map;this._extrnalUidsBatch=new Set;this._extrnalUidsBatchTimeout=null}_callUnsafe(r){return o(this,arguments,function*(e,t={},i=!1){let a=s=>o(this,null,function*(){try{return yield Ba(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<Ts))return yield v.delay(Math.min(s*Cs,Rs)),a(s);throw c.warn(e,"error",d),d}});return a(0)})}_call(r){return o(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(a){c.warn("Api call error",a);let s=se.API;switch(a.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=D.SERVICE_DISABLED;break;case 1102:s=D.CALLEE_IS_OFFLINE;break;case 1103:s=D.NOT_FRIENDS;break;case 1104:case 1106:s=D.EXTERNAL_API_ERROR;break;case 1113:s=D.CALLER_IS_REJECTED;break}throw new B(s,{message:a.error_msg,code:a.error_code})}})}userId(e){return o(this,null,function*(){let t=v.decomposeId(e).id;return ne.isEmpty()?ve.fromId(String(t)):(yield this._prepareUserIdsByOkIdsBatched([t]),ve.fromString(this._externalUidsCache.get(t)))})}prepareUserIds(e){return o(this,null,function*(){ne.isEmpty()||(yield this._prepareUserIdsByOkIdsBatched(e))})}_prepareUserIdsByOkIdsBatched(e){return e.some(i=>!this._externalUidsCache.has(i))?(e.forEach(i=>this._extrnalUidsBatch.add(i)),this._extrnalUidsBatchTimeout||(this._extrnalUidsBatchPromise=new Promise(i=>{this._extrnalUidsBatchTimeout=window.setTimeout(()=>{if(this._extrnalUidsBatch.size>0){let r=[...this._extrnalUidsBatch];this._extrnalUidsBatch.clear(),this._getExternalIdsByOkIds(r).then(a=>{for(let s in a)!a.hasOwnProperty(s)||this._externalUidsCache.set(parseInt(s,10),a[s]);i()})}this._extrnalUidsBatchTimeout=null},p.api.userIdsByOkBatchedTimeout)})),this._extrnalUidsBatchPromise):Promise.resolve()}authorize(){return o(this,null,function*(){if(!this._uuid){let t=et.get("uuid");t||(t=v.uuid(),et.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:p.appVersion,client_type:"SDK_JS"}};return p.authToken&&(e.session_data.auth_token=p.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),ne.sessionKey=t.session_key,ne.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&g.onTokenExpired(),new B(se.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${p.appName}:${p.sdkVersion}`,platform:p.platform,items:e})};Tr("log.externalLog",t)}init(){Ua()}joinConversation(e,t=!1,i){return o(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:p.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(a){return o(this,arguments,function*(e,t="",i=!1,{onlyAdminCanShareMovie:r}={}){let s=this._preareStartConversationData({conversationId:e,isVideo:!1,joiningAllowed:!0,payload:t,requireAuthToJoin:i,onlyAdminCanShareMovie:r});return this._startConversation(s)})}startConversation(u,E,C){return o(this,arguments,function*(e,t,i,r=!1,a="",s=!1,d=!1,{onlyAdminCanShareMovie:l}={}){let M=this._preareStartConversationData({conversationId:e,isVideo:r,joiningAllowed:s,payload:a,requireAuthToJoin:d,onlyAdminCanShareMovie:l});if(t&&t.length)switch(i){case je.USER:M.uids=t.join(",");break;case je.GROUP:M.gid=t[0];break;case je.CHAT:M.chatId=t[0];break}return this._startConversation(M)})}_preareStartConversationData({conversationId:e,isVideo:t,payload:i="",joiningAllowed:r=!1,requireAuthToJoin:a=!1,onlyAdminCanShareMovie:s}){let d={conversationId:e,isVideo:t,protocolVersion:p.protocolVersion};return r&&(d.createJoinLink=!0),i&&(d.payload=i),p.domain&&(d.domainId=p.domain),p.externalDomain&&(d.externalDomain=p.externalDomain),a&&(d.requireAuthToJoin=!0),s!==void 0&&(d.onlyAdminCanShareMovie=s),d}_startConversation(e){return o(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return o(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return o(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return o(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1,i,r){return o(this,null,function*(){let a={joinLink:e,isVideo:t,protocolVersion:p.protocolVersion};return(i==null?void 0:i.length)&&(a.observedIds=i.join(",")),p.anonymToken&&(a.anonymToken=p.anonymToken),r&&(a.payload=r),this._call("vchat.joinConversationByLink",a)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=ve.fromIds(e),i=[],r={methods:[]},a=[],s=[...this._externalUidsCache.keys()],d=[...this._externalUidsCache.values()];for(let u of t){let E=ve.toString(u),C=d.indexOf(E);C>-1?i.push(Number(s[C])):(a.push(E),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:u.id,anonym:u.type===lt.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((u,E)=>{if(u.ok){let C=Number(u.ok.ok_id);this._externalUidsCache.set(C,a[E]),i.push(C)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let a of e)this._externalUidsCache.has(a)?t.push(ve.fromString(this._externalUidsCache.get(a))):i.push(a);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);for(let a in r)!r.hasOwnProperty(a)||this._externalUidsCache.set(parseInt(a,10),r[a]);for(let a of i)r.hasOwnProperty(a)&&t.push(ve.fromString(r[a]));return t})}getCachedOkIdByExternalId(e){let t=[...this._externalUidsCache.keys()],i=[...this._externalUidsCache.values()],r=ve.toString(e),a=i.indexOf(r);return a>-1?v.composeUserId(t[a],te.USER):null}cacheExternalId(e,t){let i=v.decomposeId(e).id;this._externalUidsCache.set(i,ve.toString(t))}getConversationParams(e){return o(this,null,function*(){let t={};return p.anonymToken&&(t.anonymToken=p.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:D.HUNGUP};p.anonymToken&&(t.anonymToken=p.anonymToken),Tr("vchat.hangupConversation",t)}removeHistoryRecords(e){return o(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return o(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,a]of Object.entries(i.external_ids))t[r]=ve.fromIdToString(a,lt.USER);if(i.anonym_ids)for(let[r,a]of Object.entries(i.anonym_ids))t[r]=ve.fromIdToString(a,lt.ANONYM);return t}catch(i){return t}})}};var Cr=class{requestAsr(e){let t=new ArrayBuffer(2),i=new DataView(t);return i.setUint8(0,1),i.setUint8(1,e?0:1),t}};var G=nt(require("messagepack"));var Va=(L=>(L.RECOVER="recover",L.ACCEPT_CALL="accept-call",L.ADD_PARTICIPANT="add-participant",L.REMOVE_PARTICIPANT="remove-participant",L.HANGUP="hangup",L.TRANSMIT_DATA="transmit-data",L.ACCEPT_PRODUCER="accept-producer",L.ALLOCATE_CONSUMER="allocate-consumer",L.CHANGE_MEDIA_SETTINGS="change-media-settings",L.CHANGE_PARTICIPANT_STATE="change-participant-state",L.CHANGE_STREAM_PRIORITIES="change-streams-priorities",L.UPDATE_DISPLAY_LAYOUT="update-display-layout",L.REPORT_PERF_STAT="report-perf-stat",L.REPORT_SHARING_STAT="report-sharing-stat",L.RECORD_START="record-start",L.RECORD_STOP="record-stop",L.RECORD_SET_ROLE="record-set-role",L.RECORD_GET_STATUS="record-get-status",L.SWITCH_MICRO="switch-micro",L.SWITCH_TOPOLOGY="switch-topology",L.REQUEST_REALLOC="request-realloc",L.CHAT_MESSAGE="chat-message",L.CHAT_HISTORY="chat-history",L.CUSTOM_DATA="custom-data",L.GRANT_ROLES="grant-roles",L.MUTE_PARTICIPANT="mute-participant",L.ENABLE_FEATURE_FOR_ROLES="enable-feature-for-roles",L.PIN_PARTICIPANT="pin-participant",L.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",L.CHANGE_OPTIONS="change-options",L.GET_WAITING_HALL="get-waiting-hall",L.GET_PARTICIPANT_LIST_CHUNK="get-participant-list-chunk",L.GET_PARTICIPANTS="get-participants",L.PROMOTE_PARTICIPANT="promote-participant",L.REQUEST_TEST_MODE="request-test-mode",L.ADD_MOVIE="add-movie",L.UPDATE_MOVIE="update-movie",L.REMOVE_MOVIE="remove-movie",L.GET_ROOMS="get-rooms",L.UPDATE_ROOMS="update-rooms",L.ACTIVATE_ROOMS="activate-rooms",L.REMOVE_ROOMS="remove-rooms",L.SWITCH_ROOM="switch-room",L.FEEDBACK="feedback",L.ASR_START="asr-start",L.ASR_STOP="asr-stop",L.REQUEST_ASR="request-asr",L))(Va||{}),x=Va;function Zt(){let n=new DataView(new ArrayBuffer(64)),e=0;function t(i){if(e+i>n.byteLength){let r=new Uint8Array(Math.max(e+i,n.byteLength+64));r.set(new Uint8Array(n.buffer.slice(0,e))),n=new DataView(r.buffer)}}return{put(i){if(t(i.byteLength),ys(i)){let r=i.buffer;new Uint8Array(n.buffer).set(new Uint8Array(r),e)}else new Uint8Array(n.buffer).set(new Uint8Array(i),e);e+=i.byteLength},putI8(i){t(1),n.setInt8(e,i),++e},putI16(i){t(2),n.setInt16(e,i),e+=2},putI32(i){t(4),n.setInt32(e,i),e+=4},putI64(i){t(8);let r=i<0;r&&(i=-i);let a=i/4294967296|0,s=i%4294967296|0;r&&(s=~s+1|0,a=s===0?~a+1|0:~a),n.setUint32(e,a),n.setUint32(e+4,s),e+=8},putUi8(i){t(1),n.setUint8(e,i),++e},putUi16(i){t(2),n.setUint16(e,i),e+=2},putUi32(i){t(4),n.setUint32(e,i),e+=4},putUi64(i){t(8),n.setUint32(e,i/4294967296|0),n.setUint32(e+4,i%4294967296),e+=8},putF(i){t(8),n.setFloat64(e,i),e+=8},ui8array(){return new Uint8Array(n.buffer.slice(0,e))}}}function ys(n){return n.buffer!==void 0}function Ai(n){let e=ArrayBuffer.isView(n)?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),t=0;return{peek(){return e.getUint8(t)},get(i){t+=i;let r=e.byteOffset;return e.buffer.slice(r+t-i,r+t)},getI8(){return e.getInt8(t++)},getI16(){return t+=2,e.getInt16(t-2)},getI32(){return t+=4,e.getInt32(t-4)},getI64(){t+=8;let i=e.getInt32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getUi8(){return e.getUint8(t++)},getUi16(){return t+=2,e.getUint16(t-2)},getUi32(){return t+=4,e.getUint32(t-4)},getUi64(){t+=8;let i=e.getUint32(t-8),r=e.getUint32(t-4);return i*4294967296+r},getF32(){return t+=4,e.getFloat32(t-4)},getF64(){return t+=8,e.getFloat64(t-8)}}}var Ha=0,Ga=1,Ps=2,bs=0,Ms=1,As=2,Di=0,Ds=0,ks=0,Os=1,Rr=class{constructor(){this.participantIdRegistry=null}setParticipantIdRegistry(e){this.participantIdRegistry=e}serializeUpdateDisplayLayout(e,t){let i=Zt();G.Int.enc(i,Ha),G.Int.enc(i,Di),G.Int.enc(i,e),G.Nil.enc(i,null);let r=[];for(let a in t)t.hasOwnProperty(a)&&this.writeLayout(t,a,r);return G.Arr.enc(i,r),G.Nil.enc(i,null),i.ui8array()}writeLayout(e,t,i){let r=e[t],a=Zt();if(this.writeStreamDesc(t,a),Kt(r))G.Int.enc(a,Ms);else if(mr(r))G.Int.enc(a,As);else if(G.Int.enc(a,bs),r.priority!==void 0?G.Int.enc(a,r.priority):G.Nil.enc(a,null),r.width!==void 0&&r.height!==void 0?(G.Int.enc(a,Math.round(r.width)),G.Int.enc(a,Math.round(r.height))):(G.Nil.enc(a,null),G.Nil.enc(a,null)),r.fit!==void 0)switch(r.fit){case"cv":G.Int.enc(a,ks);break;case"cn":G.Int.enc(a,Os);break;default:G.Nil.enc(a,null)}else G.Nil.enc(a,null);i.push(a.ui8array())}writeStreamDesc(e,t){if(this.participantIdRegistry){let i=this.participantIdRegistry.getCompactId(e);if(i!==void 0){G.Int.enc(t,i);return}}G.Str.enc(t,e)}serializePerfStatReport(e,t){let i=Zt();return G.Int.enc(i,Ga),G.Int.enc(i,Di),G.Int.enc(i,e),G.Int.enc(i,t.framesDecoded),G.Int.enc(i,t.framesReceived),i.ui8array()}serializeSharingStatReport(e,t){let i=Zt();return G.Int.enc(i,Ps),G.Int.enc(i,Di),G.Int.enc(i,e),G.Int.enc(i,t.minDelay),G.Int.enc(i,t.maxDelay),G.Int.enc(i,t.avgDelay),G.Int.enc(i,t.largeDelayDuration),i.ui8array()}deserializeCommandResponse(e){return o(this,null,function*(){let t;if(e instanceof Blob){let s=Blob.prototype.arrayBuffer?yield e.arrayBuffer():yield _a(e);t=Ai(s)}else t=Ai(e);let i=G.Int.dec(t),r=G.Int.dec(t);if(r!==Di){c.warn("Unsupported version for command type: "+i+", version "+r);return}if(G.Int.dec(t)!==Ds){c.warn("Error code: "+i+"received for command type: "+i+", version "+r);return}switch(i){case Ha:return this.deserializeUpdateDisplayLayoutResponse(t);case Ga:return this.deserializeReportPerfStatResponse(t);default:return c.warn("unsupported command response commandType: "+i),null}})}deserializeUpdateDisplayLayoutResponse(e){let t=G.Int.dec(e),i=G.Arr.dec(e),r={};return i.forEach(a=>{let s=Ai(a),d=G.Any.dec(s);if(typeof d=="string")r[d]=G.Int.dec(s);else{let l=d,u=qe(this.participantIdRegistry.getStreamDescription(l));r[u]=G.Int.dec(s)}}),{type:"response",sequence:t,response:x.UPDATE_DISPLAY_LAYOUT.toString(),errorCodeByParticipantId:r}}deserializeReportPerfStatResponse(e){let t=G.Int.dec(e),i=G.Int.dec(e);return{type:"response",sequence:t,response:x.REPORT_PERF_STAT.toString(),estimatedPerformanceIndex:i}}};var ki="open",Wa=[()=>p.producerScreenTrack,()=>p.videoTracksCount>0,()=>!0,()=>p.filteredMessages,()=>p.consumerScreenTrack,()=>!0,()=>p.movieShare,()=>p.useParticipantListChunk,()=>p.useRooms],ws=10,we=class extends vt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.asrCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+p.platform+"&appVersion="+p.appVersion+"&version="+p.protocolVersion+"&device="+p.device+"&capabilities="+we._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null;this.asrDataChannel=null;this.producerCommandDataChannelEnabled=!1;this.producerCommandSerializationService=new Rr;this.asrCommandSerializer=new Cr}static _getCapabilityFlags(){let e=0;for(let t=0;t<Wa.length;t++)Wa[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e,this.producerCommandSerializationService.setParticipantIdRegistry(e)}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=t=>{this.producerCommandSerializationService.deserializeCommandResponse(t.data).then(i=>{i&&this._handleMessage(i)}).catch(i=>{c.warn("Cannot parse message at producerCommandDataChannel",i)})},this._handleCommandsQueue(this.datachannelCommandsQueue)}useCommandDataChannel(e){this.producerCommandDataChannelEnabled=e}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return o(this,null,function*(){return this.postfix+=`&clientType=${p.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){f.log(T.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return o(this,arguments,function*(e,t={},i=0){if(t.participantId){let a=v.decomposeParticipantId(t.participantId),s=v.decomposeId(a.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),a.deviceIdx&&(t.deviceIdx=a.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return o(this,arguments,function*(e,t={},i=0){let a=s=>{var d,l;if(e===x.REQUEST_ASR)this.asrCommandsQueue.push(s),((d=this.asrDataChannel)==null?void 0:d.readyState)===ki&&this._handleCommandsQueue(this.asrCommandsQueue);else if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===ki&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){f.log(T.SOCKET_ACTION,"not_opened"),c.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(f.log(T.SOCKET_ACTION,"invalid_state"),c.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,d)=>{let l=(E,C=!1)=>{!i||C?d(E):(c.debug("Resending a signaling message",e,u.sequence),i--,a(u))},u={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};a(u)})})}_isDataChannelCommand(e){return this.producerCommandDataChannelEnabled?e===x.UPDATE_DISPLAY_LAYOUT||e===x.REPORT_PERF_STAT||e===x.REPORT_SHARING_STAT:!1}static _isDataChannelResponseRequired(e){return e===x.UPDATE_DISPLAY_LAYOUT||e===x.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(x.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(x.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e,t){return o(this,null,function*(){return this._send(x.REQUEST_TEST_MODE,{consumer:e,producer:t})})}sendSdp(e,t){return o(this,null,function*(){return this._send(x.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(x.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(x.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},ws)})}changeParticipantState(e){return o(this,null,function*(){return this._send(x.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(x.ADD_PARTICIPANT,Ue({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(x.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return o(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(x.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(x.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(x.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(x.UPDATE_DISPLAY_LAYOUT,e)})}addMovie(e){return o(this,null,function*(){return this._send(x.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(x.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(x.REMOVE_MOVIE,e)})}updateRooms(e,t){return o(this,null,function*(){return this._send(x.UPDATE_ROOMS,{rooms:e,assignRandomly:t})})}activateRooms(e,t){return o(this,null,function*(){return this._send(x.ACTIVATE_ROOMS,{roomIds:e,deactivate:t})})}switchRoom(e,t){return o(this,null,function*(){return this._sendRaw(x.SWITCH_ROOM,{toRoomId:e,participantId:t})})}getRooms(e){return o(this,null,function*(){return this._sendRaw(x.GET_ROOMS,{withParticipants:e})})}removeRooms(e){return o(this,null,function*(){return this._send(x.REMOVE_ROOMS,{roomIds:e})})}startStream(e){return o(this,null,function*(){return this._send(x.RECORD_START,e)})}stopStream(){return o(this,arguments,function*(e={roomId:null}){return this._send(x.RECORD_STOP,e)})}recordSetRole(e,t,i=null){return o(this,null,function*(){return this._send(x.RECORD_SET_ROLE,{participantId:e,role:t,roomId:i})})}getRecordStatus(){return o(this,null,function*(){return this._send(x.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(x.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(x.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(x.REPORT_PERF_STAT,e)})}reportSharingStat(e){return o(this,null,function*(){return this._send(x.REPORT_SHARING_STAT,e)})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(x.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(x.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(x.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return o(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(x.GRANT_ROLES,r)})}muteParticipant(e,t,i,r=null){return o(this,null,function*(){return this._sendRaw(x.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i,roomId:r})})}enableFeatureForRoles(e,t){return o(this,null,function*(){return this._sendRaw(x.ENABLE_FEATURE_FOR_ROLES,{feature:e,roles:t})})}pinParticipant(e,t){return o(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(x.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(x.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(x.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return o(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(x.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(x.PROMOTE_PARTICIPANT,i)})}feedback(e){return o(this,null,function*(){return this._sendRaw(x.FEEDBACK,{key:e})})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}getParticipantListChunk(e){return o(this,null,function*(){return this._send(x.GET_PARTICIPANT_LIST_CHUNK,e)})}getParticipants(e){return o(this,null,function*(){return this._send(x.GET_PARTICIPANTS,{externalIds:e})})}startAsr(){return o(this,null,function*(){return this._send(x.ASR_START)})}stopAsr(){return o(this,null,function*(){return this._send(x.ASR_STOP)})}requestAsr(e){return o(this,null,function*(){return this._send(x.REQUEST_ASR,{request:e})})}setAsrDataChannel(e){this.asrDataChannel=e,this._handleCommandsQueue(this.asrCommandsQueue)}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ke.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),t=i(t),c.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor();function i(r){if(!p.useParticipantListChunk)return r;r+=`&partIdx=${p.participantListChunkInitIndex}`;let s=p.participantListChunkInitCount;return s!==null&&(r+=`&partCount=${s}`),r}}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){c.debug("Socket opened"),f.log(T.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){f.log(T.SOCKET_ACTION,"parse_error"),c.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(c.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(Te.RECONNECT,e),e.conversation.topology&&this._triggerEvent(Te.NOTIFICATION,{type:"notification",notification: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(Te.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(f.log(T.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(f.log(T.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new B(D.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(Te.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 B(se.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(f.log(T.SOCKET_ACTION,"unknown_message"),c.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(Te.FAILED,e)}_onError(e){f.log(T.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){f.log(T.SOCKET_ACTION,"closed"),c.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<we.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(we.RECONNECT_MAX_DELAY,we.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),f.log(T.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ke.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],f.log(T.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),we.WAIT_RESPONSE_DELAY)}_serializeAsrCommand(e){let t=e.params;return this.asrCommandSerializer.requestAsr(t.request)}_handleCommandsQueue(e){var t,i,r,a;for(;e.length>0;){let s=e.shift();if(s.name===x.REQUEST_ASR){if(((t=this.asrDataChannel)==null?void 0:t.readyState)!==ki){s.reject(new Error(`Invalid data channel state: ${(i=this.asrDataChannel)==null?void 0:i.readyState}`));return}let d=this._serializeAsrCommand(s);d!==null&&this.asrDataChannel.send(d)}else if(this._isDataChannelCommand(s.name)){if(((r=this.producerCommandDataChannel)==null?void 0:r.readyState)!==ki){s.reject(new Error(`Invalid data channel state: ${(a=this.producerCommandDataChannel)==null?void 0:a.readyState}`));return}we._isDataChannelResponseRequired(s.name)&&(s.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:s.name,sequence:s.sequence}),we.WAIT_RESPONSE_DELAY),this.responseHandlers[s.sequence]=s);let d=this._serializeBinary(s);d!==null&&this.producerCommandDataChannel.send(d)}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){s.reject(new Error("Invalid state or socket already closed"));continue}s.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,{command:s.name,sequence:s.sequence}),we.WAIT_RESPONSE_DELAY),this.responseHandlers[s.sequence]=s,this.socket.send(this._serializeJson(s))}}}_serializeBinary(e){switch(e.name){case x.UPDATE_DISPLAY_LAYOUT:return this.producerCommandSerializationService.serializeUpdateDisplayLayout(e.sequence,e.params);case x.REPORT_PERF_STAT:return this.producerCommandSerializationService.serializePerfStatReport(e.sequence,e.params);case x.REPORT_SHARING_STAT:return this.producerCommandSerializationService.serializeSharingStatReport(e.sequence,e.params)}return c.warn("cannot get binary data for data channel command: "+e.name),null}_serializeJson(e){let t;e.name===x.UPDATE_DISPLAY_LAYOUT?t=this._convertDisplayLayout(e.params):t=e.params;let i=Object.assign({command:e.name,sequence:e.sequence},t);return JSON.stringify(i)}_convertDisplayLayout(e){let t=e,i={};for(let r in t)t.hasOwnProperty(r)&&(i[r]=Ma(t[r]));return{layouts:i}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new B(se.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},we.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{c.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Ke.RETRY)},we.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},He=we;He.RECONNECT_DELAY=p.signalingReconnectDelay,He.RECONNECT_MAX_DELAY=p.signalingReconnectMaxDelay,He.RECONNECT_MAX_COUNT=p.signalingReconnectMaxCount,He.WAIT_CONNECTION_DELAY=p.waitConnectionDelay,He.WAIT_RESPONSE_DELAY=p.waitResponseDelay,He.WAIT_MESSAGE_DELAY=p.waitMessageDelay;var ja=(t=>(t.KING="KING",t.PAWN="PAWN",t))(ja||{}),Ka=ja;var yr=class{constructor(e){this._queue=new Array(e).fill(null),this._readCursor=this._writeCursor=this._left=0,this._moveReadCursor=!1}get length(){return this._queue.length}get left(){return this._left}toArray(){return Array.from(this._queue)}add(e){this._moveReadCursor&&(this._readCursor=this.nextCursor(this._readCursor)),this._queue[this._writeCursor]===null&&(this._left+=1),this._queue[this._writeCursor]=e,this._writeCursor=this.nextCursor(this._writeCursor),this._moveReadCursor=this._writeCursor===this._readCursor}nextCursor(e){return(e+1)%this._queue.length}next(){let e=this._queue[this._readCursor];return e&&(this._moveReadCursor=!1,this._queue[this._readCursor]=null,this._readCursor=this.nextCursor(this._readCursor),this._left-=1),e}};var wt,me,ei=null,xs={getCameras:y.getCameras,getMicrophones:y.getMicrophones,getOutput:y.getOutput,hasCamera:y.hasCamera,hasMicrophone:y.hasMicrophone,getSavedCamera:y.getSavedCamera,getSavedMicrophone:y.getSavedMicrophone,getSavedOutput:y.getSavedOutput,hasCameraPermission:y.hasCameraPermission,hasMicrophonePermission:y.hasMicrophonePermission,hasPermissions:y.hasPermissions,getUserMedia:y.getUserMedia,getUserVideo:y.getUserVideo,getUserAudio:y.getUserAudio,saveDeviceId:y.saveDeviceId,isBrowserSupported:y.isBrowserSupported,isScreenCapturingSupported:y.isScreenCapturingSupported,os:y.os,isMobile:y.isMobile,browserName:y.browserName,browserVersion:y.browserVersion,baseChromeVersion:y.baseChromeVersion,getAudioContext:y.getAudioContext};function $a(n){me=n}function qa(n){wt=n}function Ls(n){ei=n}function Ns(n){p.videoEffects=n}function Us(n){return o(this,null,function*(){if(p.set(n),y.browserName()==="Sferum"&&(p.platform=`SFERUM:${y.browserVersion()}`),me||$a(new Xt),wt||qa(()=>new He),p.debug&&(Pr.default.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${p.sdkVersion}`,n),yield y.init(),!y.isBrowserSupported())throw new B(se.UNSUPPORTED);c.log("UserAgent:",navigator.userAgent),c.log("Screen resolution:",`${window.screen.width}x${window.screen.height}`),c.log("Permissions:",`Camera: ${y.hasCameraPermission()}, Mic: ${y.hasMicrophonePermission()}`),me.init()})}function Bs(s){return o(this,arguments,function*(n,e=[le.AUDIO],t="",i=!1,r=!1,a){let d=[],l=[];if(Array.isArray(n)?d=n.length?n:[]:n&&(d=[n]),d.length&&(l=yield me.getOkIdsByExternalIds(d),!l.length))throw new B(D.CALLEE_IS_OFFLINE);return za(l,je.USER,e,t,i,r,a)})}function za(d){return o(this,arguments,function*(n,e=je.USER,t,i="",r=!1,a=!1,s){if(N.current())throw c.error("There is already active call"),new B(D.FAILED);return new N(me,wt(),ei).onStart(n,e,t,i,r,a,s)})}function Fs(n){return o(this,null,function*(){return Ja(n)})}function Ja(i){return o(this,arguments,function*(n,e=te.USER,t){if(n===N.id())throw new Error("Push has already been processed");return new N(me,wt(),ei).onPush(n,e,t)})}function Vs(n){return o(this,null,function*(){return n&&(p.authToken=n),me.authorize()})}function Hs(){return o(this,arguments,function*(n=[le.AUDIO]){return ht().accept(n)})}function Gs(){return o(this,null,function*(){let n=N.current();if(n)return n.decline()})}function Ws(t){return o(this,arguments,function*(n,e=[le.AUDIO]){return Ya(n,e)})}function Ya(n,e,t){return o(this,null,function*(){if(N.current())throw c.error("There is already active call"),new B(D.FAILED);return new N(me,wt(),ei).onJoin({conversationId:n,mediaOptions:e,chatId:t})})}function js(a){return o(this,arguments,function*(n,e=[le.AUDIO],t,i,r){if(N.current())throw c.error("There is already active call"),new B(D.FAILED);return t&&(p.anonymToken=t),new N(me,wt(),ei).onJoin({joinLink:n,mediaOptions:e,observedIds:i,payload:r})})}function Ks(){return o(this,null,function*(){let n=N.current();if(n)return n.hangup();N.hangupAfterInit()})}function $s(n,e){return o(this,null,function*(){let t=yield me.getOkIdsByExternalIds([n]);if(!t.length)throw new Error("User not found");return Qa(t[0],e)})}function Qa(n,e){return o(this,null,function*(){let t=N.current();t&&(yield t.addParticipant(v.composeUserId(n,te.USER),e))})}function qs(n,e=!1){return o(this,null,function*(){let t=yield me.getOkIdsByExternalIds([n]);return Xa(t[0],e)})}function Xa(n,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.removeParticipant(v.composeUserId(n,te.USER),e))})}function zs(n,e){return o(this,null,function*(){let t=yield y.saveDeviceId(n,e),i=N.current();return t&&i?i.changeDevice(n):Promise.reject()})}function Js(n){return o(this,null,function*(){return Za(n,!1)})}function Za(n,e){return o(this,null,function*(){if(e){if(!p.audioShareCapabilityEnabled)throw new Error("Audio share capability is disabled");if(!n)throw new Error("Audio share without screen share is not allowed")}let t=N.current();return t?t.toggleScreenCapturing(n,e):Promise.reject()})}function Ys(n,e=!1){return o(this,null,function*(){let t=N.current();t&&(yield t.setVideoStream(n,e))})}function Qs(n){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalVideo(n))})}function Xs(n){return o(this,null,function*(){let e=N.current();e&&(yield e.toggleLocalAudio(n))})}function Zs(n,e,t){return o(this,null,function*(){let i=N.current();if(i)return i.setLocalResolution(n,e,t)})}function eo(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changePriorities(n))})}function to(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changeParticipantState(n))})}function io(n){return o(this,null,function*(){let e=N.current();e&&(yield e.updateDisplayLayout(n))})}function ro(n,e,t=!1){return o(this,null,function*(){let i=yield me.getOkIdsByExternalIds([n]);return en(i[0],e,t)})}function en(n,e,t=!1){return o(this,null,function*(){let i=N.current();i&&(yield i.grantRoles(v.composeUserId(n,te.USER),e,t))})}function ao(r){return o(this,arguments,function*({externalId:n=null,muteStates:e,requestedMedia:t=[],roomId:i=null}){let a=null;return n&&(a=(yield me.getOkIdsByExternalIds([n]))[0]),tn({uid:a,muteStates:e,requestedMedia:t,deviceIdx:fe.getDeviceIdx(n),roomId:i})})}function tn(a){return o(this,arguments,function*({uid:n=null,muteStates:e,requestedMedia:t=[],deviceIdx:i=0,roomId:r=null}){let s=N.current();if(s){let d=n?v.composeParticipantId(n,te.USER,i):null;yield s.muteParticipant(d,e,t,r)}})}function no(n,e=!1){return o(this,null,function*(){let t=yield me.getOkIdsByExternalIds([n]);return rn(t[0],e,fe.getDeviceIdx(n))})}function rn(n,e=!1,t=0){return o(this,null,function*(){let i=N.current();i&&(yield i.pinParticipant(v.composeParticipantId(n,te.USER,t),e))})}function so(n){return o(this,null,function*(){let e=N.current();e&&(yield e.updateMediaModifiers(n))})}function oo(n){return o(this,null,function*(){let e=N.current();e&&(yield e.changeOptions(n))})}function co(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield me.getOkIdsByExternalIds([e]))[0]),an(n,t)})}function an(n,e=null){return o(this,null,function*(){let t=N.current();if(t){let i=e?v.composeUserId(e,te.USER):null;yield t.chatMessage(n,i)}})}function lo(n=10){return o(this,null,function*(){let e=N.current();if(e)return e.chatHistory(n)})}function po(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield me.getOkIdsByExternalIds([e]))[0]),nn(n,t,fe.getDeviceIdx(e))})}function nn(n,e=null,t=0){return o(this,null,function*(){let i=N.current();if(i){let r=e?v.composeParticipantId(e,te.USER,t):null;yield i.customData(n,r)}})}function uo(){return o(this,arguments,function*(n="",e=!1,{onlyAdminCanShareMovie:t=!1}={}){return(yield me.createConversation(v.uuid(),n,e,{onlyAdminCanShareMovie:t})).join_link})}function mo(){return o(this,null,function*(){let n=N.current();return n?n.createJoinLink():Promise.reject()})}function ho(){return o(this,null,function*(){let n=N.current();return n?n.removeJoinLink():Promise.reject()})}function _o(n,e){return o(this,null,function*(){return me.getAnonymTokenByLink(n,e)})}function go(n){let e=N.current();e&&e.setVolume(n)}function fo(n){p.forceRelayPolicy=n}function So(n=!1,e=null,t=null,i="DIRECT_LINK",r=null,a=null){return o(this,null,function*(){let s=N.current();return s?s.startStream(n,e,t,i,r,a):Promise.reject()})}function vo(n=null){return o(this,null,function*(){let e=N.current();return e?e.stopStream(n):Promise.reject()})}function Eo(n,e,t=null){return o(this,null,function*(){let i=N.current();if(i){let r=yield me.getOkIdsByExternalIds([n]),a=fe.getDeviceIdx(n);return i.recordSetRole(v.composeParticipantId(r[0],te.USER,a),e,t)}return Promise.reject()})}function Io(){return o(this,null,function*(){let n=N.current();return n?n.getStreamInfo():Promise.reject()})}function To(n){return o(this,null,function*(){let e=N.current();return e?e.addMovie(n):Promise.reject()})}function Co(n){return o(this,null,function*(){let e=N.current();return e?e.updateMovie(n):Promise.reject()})}function Ro(n){return o(this,null,function*(){let e=N.current();return e?e.removeMovie(n):Promise.reject()})}function yo(n,e){return o(this,null,function*(){let t=N.current();return t?t.updateRooms(n,e):Promise.reject()})}function Po(n,e){return o(this,null,function*(){let t=N.current();return t?t.activateRooms(n,e):Promise.reject()})}function bo(n=null,e=null){return o(this,null,function*(){let t=null;if(e){let r=yield me.getOkIdsByExternalIds([e]);t=v.composeUserId(r[0],te.USER)}let i=N.current();return i?i.switchRoom(n,t):Promise.reject()})}function Mo(n){return o(this,null,function*(){let e=N.current();return e?e.removeRooms(n):Promise.reject()})}function Ao(n){p.statisticsInterval=n;let e=N.current();if(e)return e.updateStatisticsInterval()}function Do(n){Pr.default.disableLog(!n),c.toggle(n)}function ko(n,...e){!p.debugLog||c.send(n,"[external]",...e)}function Oo(n){return o(this,null,function*(){let e=N.current();if(e)return e.videoEffect(n)})}function wo(n){return o(this,null,function*(){let e=N.current();e&&(yield e.setAudioStream(n))})}function xo(n=null,e,t=!1){return o(this,null,function*(){return ht().getWaitingHall(n,e,t)})}function Lo(n,e=!1){return o(this,null,function*(){let t=ht(),i=yield me.getOkIdsByExternalIds([n]);return t.promoteParticipant(v.composeUserId(i[0],te.USER),e)})}function No(n){return o(this,null,function*(){return ht().getParticipantListChunk(n)})}function Uo(n){return o(this,null,function*(){return ht().getParticipants(n)})}function Bo(n){return o(this,null,function*(){return ht().feedback(n)})}function Fo(n,e){return o(this,null,function*(){return ht().enableFeatureForRoles(n,e)})}function ht(){let n=N.current();if(!n)throw new Error("Conversation not found");return n}function Vo(n){return o(this,null,function*(){yield me.removeHistoryRecords(n)})}function Ho(){return o(this,null,function*(){let n=N.current();n&&(yield n.startAsr())})}function Go(){return o(this,null,function*(){let n=N.current();n&&(yield n.stopAsr())})}function Wo(n){return o(this,null,function*(){let e=N.current();e&&(yield e.requestAsr(n))})}function jo(){return p.sdkVersion}
|